RE: having problem in login rest API

2019-07-07 Thread laya
Yes Check_password attribute is in Django user model and when I write 
Customuser. Objects.filter() it errors that Student_no is not an attribute for 
User Django Model.

Sent from Mail for Windows 10

From: Aldian Fazrihady
Sent: Sunday, July 7, 2019 9:18 PM
To: django-users@googlegroups.com
Subject: Re: having problem in login rest API

It is in user object instead of student object,  right? 
Regards, 

Aldian Fazrihady
http://aldianfazrihady.com

On Mon, 8 Jul 2019, 11:12 laya,  wrote:
Hi,
Please help me in this part, I stuck in some days, 
My project is about a university system which professors and students can sign 
up and login. I use Custom User Django which inherits User Django Model. It 
should be mentioned that login is by identity number and Student-no and 
Professor-no. 
My codes are as follow:
Models.py:
class CustomUser(AbstractUser):
    USER_TYPE_CHOICES = ((1, 'student'),
 (2, 'professor'),)
    username = models.CharField(max_length=50, unique=True)
    user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES, 
null=True)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=100)
    identity_no = models.PositiveIntegerField(default=0)
    email = models.EmailField(max_length=300,
  validators=[RegexValidator
  
(regex="^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.["r"a-zA-Z0-9-.]+$",
   message='please enter the correct 
format')],
  )
    date_joined = models.DateTimeField('date joined', default=timezone.now)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)


class Student(models.Model):
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    entry_year = models.PositiveIntegerField()
    student_no = models.PositiveIntegerField()

    def get_full_name(self):
    return self.user.first_name +" "+ self.user.last_name

    def __unicode__(self):
    return self.user.first_name +" "+ self.user.last_name

    def __str__(self):
    return self.user.first_name +" "+  self.user.last_name
 
serializers.py:
 
"""STUDENT LOGIN"""
class StudentLoginSerializer(serializers.ModelSerializer):
    user = CustomUserSerializerForLogin()

    class Meta:
    model = Student
    fields = [
    "user",
    "student_no", ]

    def validate(self, data):  # validated_data
    user_data = data.pop('user', None)
    identity_no = user_data.get('identity_no')
    print("identity_no", identity_no)
    student_no = data.get("student_no")
    user = Student.objects.filter(
    Q(user__identity_no=identity_no) |
    Q(student_no=student_no)
    ).distinct()
    # user = 
user.exclude(user__identity_no__isnull=True).exclude(user__identity_no__iexact='')
    if user.exists() and user.count() == 1:
    user_obj = user.first()
    else:
    raise ValidationError("This username or student_no is not existed")
    if user_obj:
    if not user_obj.check_password(student_no):  # Return a boolean of 
whether the raw_password was correct.
    raise ValidationError("Incorrect Credential please try again")
    return user_obj
Views.py:

class StudentLoginView(APIView):
    queryset = Student.objects.all()
    serializer_class = StudentLoginSerializer
    def post(self, request, *args, **kwargs):
    data = request.data
    serializer = StudentLoginSerializer(data=data)
    if serializer.is_valid(raise_exception=True):
    new_data = serializer.data
    return Response(new_data, status= HTTP_200_OK)
    return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
Error:
The error is about check_password attribute which is not existing in Student 
Object.
 
 
Sent from Mail for Windows 10
 
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/5d22c291.1c69fb81.81d84.d526%40mx.google.com.
For more options, visit https://groups.google.com/d/optout.
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.go

Re: having problem in login rest API

2019-07-07 Thread Aldian Fazrihady
It is in user object instead of student object,  right?

Regards,

Aldian Fazrihady
http://aldianfazrihady.com

On Mon, 8 Jul 2019, 11:12 laya,  wrote:

> Hi,
>
> Please help me in this part, I stuck in some days,
>
> My project is about a university system which professors and students can
> sign up and login. I use Custom User Django which inherits User Django
> Model. It should be mentioned that login is by identity number and
> Student-no and Professor-no.
>
> My codes are as follow:
>
> Models.py:
>
> class CustomUser(AbstractUser):
> USER_TYPE_CHOICES = ((1, 'student'),
>  (2, 'professor'),)
> username = models.CharField(max_length=50, unique=True)
> user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES, 
> null=True)
> first_name = models.CharField(max_length=50)
> last_name = models.CharField(max_length=100)
> identity_no = models.PositiveIntegerField(default=0)
> email = models.EmailField(max_length=300,
>   validators=[RegexValidator
>   
> (regex="^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.["r"a-zA-Z0-9-.]+$",
>message='please enter the correct 
> format')],
>   )
> date_joined = models.DateTimeField('date joined', default=timezone.now)
> is_active = models.BooleanField(default=True)
> is_admin = models.BooleanField(default=False)
> is_staff = models.BooleanField(default=False)
>
>
> class Student(models.Model):
> user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
> entry_year = models.PositiveIntegerField()
> student_no = models.PositiveIntegerField()
>
> def get_full_name(self):
> return self.user.first_name +" "+ self.user.last_name
>
> def __unicode__(self):
> return self.user.first_name +" "+ self.user.last_name
>
> def __str__(self):
> return self.user.first_name +" "+  self.user.last_name
>
>
>
> serializers.py:
>
>
>
> """STUDENT LOGIN"""
> class StudentLoginSerializer(serializers.ModelSerializer):
> user = CustomUserSerializerForLogin()
>
> class Meta:
> model = Student
> fields = [
> "user",
> "student_no", ]
>
> def validate(self, data):  # validated_data
> user_data = data.pop('user', None)
> identity_no = user_data.get('identity_no')
> print("identity_no", identity_no)
> student_no = data.get("student_no")
> user = Student.objects.filter(
> Q(user__identity_no=identity_no) |
> Q(student_no=student_no)
> ).distinct()
> # user = 
> user.exclude(user__identity_no__isnull=True).exclude(user__identity_no__iexact='')
> if user.exists() and user.count() == 1:
> user_obj = user.first()
> else:
> raise ValidationError("This username or student_no is not 
> existed")
> if user_obj:
> if not user_obj.check_password(student_no):  # Return a boolean 
> of whether the raw_password was correct.
> raise ValidationError("Incorrect Credential please try again")
> return user_obj
>
> Views.py:
>
>
> class StudentLoginView(APIView):
> queryset = Student.objects.all()
> serializer_class = StudentLoginSerializer
> def post(self, request, *args, **kwargs):
> data = request.data
> serializer = StudentLoginSerializer(data=data)
> if serializer.is_valid(raise_exception=True):
> new_data = serializer.data
> return Response(new_data, status= HTTP_200_OK)
> return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
>
> Error:
>
> The error is about check_password attribute which is not existing in
> Student Object.
>
>
>
>
>
> Sent from Mail  for
> Windows 10
>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/5d22c291.1c69fb81.81d84.d526%40mx.google.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/djang

having problem in login rest API

2019-07-07 Thread laya
Hi,
Please help me in this part, I stuck in some days, 
My project is about a university system which professors and students can sign 
up and login. I use Custom User Django which inherits User Django Model. It 
should be mentioned that login is by identity number and Student-no and 
Professor-no. 
My codes are as follow:
Models.py:
class CustomUser(AbstractUser):
USER_TYPE_CHOICES = ((1, 'student'),
 (2, 'professor'),)
username = models.CharField(max_length=50, unique=True)
user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES, 
null=True)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=100)
identity_no = models.PositiveIntegerField(default=0)
email = models.EmailField(max_length=300,
  validators=[RegexValidator
  
(regex="^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.["r"a-zA-Z0-9-.]+$",
   message='please enter the correct 
format')],
  )
date_joined = models.DateTimeField('date joined', default=timezone.now)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)


class Student(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
entry_year = models.PositiveIntegerField()
student_no = models.PositiveIntegerField()

def get_full_name(self):
return self.user.first_name +" "+ self.user.last_name

def __unicode__(self):
return self.user.first_name +" "+ self.user.last_name

def __str__(self):
return self.user.first_name +" "+  self.user.last_name

serializers.py:

"""STUDENT LOGIN"""
class StudentLoginSerializer(serializers.ModelSerializer):
user = CustomUserSerializerForLogin()

class Meta:
model = Student
fields = [
"user",
"student_no", ]

def validate(self, data):  # validated_data
user_data = data.pop('user', None)
identity_no = user_data.get('identity_no')
print("identity_no", identity_no)
student_no = data.get("student_no")
user = Student.objects.filter(
Q(user__identity_no=identity_no) |
Q(student_no=student_no)
).distinct()
# user = 
user.exclude(user__identity_no__isnull=True).exclude(user__identity_no__iexact='')
if user.exists() and user.count() == 1:
user_obj = user.first()
else:
raise ValidationError("This username or student_no is not existed")
if user_obj:
if not user_obj.check_password(student_no):  # Return a boolean of 
whether the raw_password was correct.
raise ValidationError("Incorrect Credential please try again")
return user_obj
Views.py:

class StudentLoginView(APIView):
queryset = Student.objects.all()
serializer_class = StudentLoginSerializer
def post(self, request, *args, **kwargs):
data = request.data
serializer = StudentLoginSerializer(data=data)
if serializer.is_valid(raise_exception=True):
new_data = serializer.data
return Response(new_data, status= HTTP_200_OK)
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
 
Error:
The error is about check_password attribute which is not existing in Student 
Object.


Sent from Mail for Windows 10

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/5d22c291.1c69fb81.81d84.d526%40mx.google.com.
For more options, visit https://groups.google.com/d/optout.


Help

2019-07-07 Thread Yeashin Rabbi
Hi Everyone,

I have a model with a manyTomany field. I've created an update view for 
this model and the widget for manyTomany field is FilteredSelectMultiple. 
How to render the selected value for  the manyTomany field  in right side 
box of FilteredSelectMultiple widget while visiting the page?

Any help would be appreciated.

Thanks,

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/79380f80-db6e-43d8-99af-4f792c037401%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


insert or update on table "app_job" violates foreign key constraint "app_job_user_id_f90a6dd9_fk_accounts_user_id" DETAIL: Key (user_id)=(3) is not present in table "accounts_user".

2019-07-07 Thread Aayush Bhattarai


[image: Capture.PNG]


*I have used a function-based View to get data from post Request. I need to 
get many data that also include a primary key field too. I need to push 
data into two models. While doing so, I encountered an error.*

#accounts models.py
from django.db import models
class User(models.Model):
user_id = models.PositiveIntegerField(blank=True)

name = models.CharField(max_length=200)
phone = models.CharField(max_length=200)
email = models.EmailField(max_length=254)

#app models.py
from accounts.models import User #from accounts models.py
class job(models.Model):
user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
..

#views.py
data = job(.,map_link=map_link,user_id=user_id)
data.save()
info=User(name=name,email=email,phone=phone,user_id=user_id)
info.save()

*Error Message: http://dpaste.com/03Z0EPB *

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/9f083194-4a44-4f09-94d2-5479fed45ab5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: django sessions

2019-07-07 Thread Chetan Ganji
Hii,

below answer might ring some bells.

https://stackoverflow.com/questions/2551933/django-accessing-session-variables-from-within-a-template

Cheers!

On Sat, Jul 6, 2019, 5:24 PM Luka Lelashvili 
wrote:

> Hello, how can I access session in my base.html? {% request.session.name
> %} doesn't work on base.html any clues?
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/f9247737-44bd-4263-ace0-c1cf4d71fbde%40googlegroups.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAMKMUjuLy%2BOSBHK_fX%3DRvoYsK0hzT1CY0NKfr8%2Bybk1Y_VMLfg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: problem in login rest API framework

2019-07-07 Thread Nidhin K
I couldn't see you inherited from AbstractUser class in your defined
Student model shared here.

Thanks

On Sun, Jul 7, 2019, 10:47 AM laya  wrote:

> AttributeError:'Student' object has no attribute 'check_password'
> 
>
> I user Custom User Model named Student which inherits Django User Model. I
> have problem in its logon when I want to use check_password. The error is
> that Student which is a custom user model has not such attribute.
>
> I wanna login students with the registered information by them. and the
> fields to login is identity_no and student_no.
>
> models.py:
>
> class CustomUser(AbstractUser):
>
> USER_TYPE_CHOICES = ((1, 'student'),
>
>  (2, 'professor'),)
>
> username = models.CharField(max_length=50, unique=True)
>
> user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES, 
> null=True)
>
> first_name = models.CharField(max_length=50)
>
> last_name = models.CharField(max_length=100)
>
> identity_no = models.PositiveIntegerField(default=0)
>
> email = models.EmailField(max_length=300)
>
> date_joined = models.DateTimeField('date joined', default=timezone.now)
>
> is_active = models.BooleanField(default=True)
>
> is_admin = models.BooleanField(default=False)
>
> is_staff = models.BooleanField(default=False)
>
>
>
>
>
> class Student(models.Model):
>
> user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
>
> entry_year = models.PositiveIntegerField()
>
> student_no = models.PositiveIntegerField()
>
>
>
> def get_full_name(self):
>
> return self.user.first_name + self.user.last_name
>
>
>
> def __unicode__(self):
>
> return self.get_full_name()
>
>
>
> Serializers.py:
>
> class StudentLoginSerializer(serializers.ModelSerializer): user = 
> CustomUserSerializerForLogin()
>
> class Meta:
>
> model = Student
>
> fields = [
>
> "user",
>
> "student_no", ]
>
>
>
> def validate(self, data):  # validated_data
>
> user_data = data.pop('user', None)
>
> identity_no = user_data.get('identity_no')
>
> print("identity_no", identity_no)
>
> student_no = data.get("student_no")
>
> user = Student.objects.filter(
>
> Q(user__identity_no=identity_no) |
>
> Q(student_no=student_no)
>
> ).distinct()
>
> # user = 
> user.exclude(user__identity_no__isnull=True).exclude(user__identity_no__iexact='')
>
> if user.exists() and user.count() == 1:
>
> user_obj = user.first()
>
> else:
>
> raise ValidationError("This username or student_no is not 
> existed")
>
> if user_obj:
>
> if not user_obj.check_password(student_no):  # Return a boolean 
> of whether the raw_password was correct.
>
> raise ValidationError("Incorrect Credential please try again")
>
> return user_obj
>
>
>
> Sent from Mail  for
> Windows 10
>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/5d218062.1c69fb81.f85a6.42f3%40mx.google.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAKWugDW1jyEO8750PM9WgS7NmBHxciEatjFxzhjdoyfHCyr_wQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Multiple roles Django 2

2019-07-07 Thread Deepraj Devikar
 moldels.py



On Sun, Jul 7, 2019 at 9:33 AM laya Mahmoudi 
wrote:

> You should add some code in your settings.py like AUTH_USER_MODEL=
> 'appname.modelname' which inherits django user mode.
>
>
> در تاریخ یکشنبه ۷ ژوئیهٔ ۲۰۱۹،‏ ۳:۳۷ Shazia Nusrat 
> نوشت:
>
>> Hi All,
>> I am having hard time to get multiple roles for users in a project and I
>> am having errors.
>> I've added related_name but still getting error. Can please tell me how
>> to fix this?
>>
>> ***
>> from django.db import models
>> from django.contrib.auth.models import AbstractUser
>> # Create your models here.
>>
>> class Role(models.Model):
>>  STUDENT = 1
>>  TEACHER = 2
>>  SECRETARY = 3
>>  SUPERVISOR = 4
>>  ADMIN = 5
>>  ROLE_CHOICES = (
>>   (STUDENT, 'student'),
>>   (TEACHER, 'teacher'),
>>   (SECRETARY, 'secretary'),
>>   (SUPERVISOR, 'supervisor'),
>>   (ADMIN, 'admin'),
>>  )
>>  id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES,
>> primary_key=True)
>>  def __str__(self):
>>   return self.get_id_display()
>> class User(AbstractUser):
>>  roles = models.ManyToManyField(Role)
>> ***
>>
>> I am getting error below:
>>
>> ***
>> ERRORS:
>> auth.User.groups: (fields.E304) Reverse accessor for 'User.groups'
>> clashes with reverse accessor for 'User.groups'.
>> HINT: Add or change a related_name argument to the definition for
>> 'User.groups' or 'User.groups'.
>> auth.User.user_permissions: (fields.E304) Reverse accessor for
>> 'User.user_permissions' clashes with reverse accessor for
>> 'User.user_permissions'.
>> HINT: Add or change a related_name argument to the definition for
>> 'User.user_permissions' or 'User.user_permissions'.
>> users.User.groups: (fields.E304) Reverse accessor for 'User.groups'
>> clashes with reverse accessor for 'User.groups'.
>> HINT: Add or change a related_name argument to the definition for
>> 'User.groups' or 'User.groups'.
>> users.User.user_permissions: (fields.E304) Reverse accessor for
>> 'User.user_permissions' clashes with reverse accessor for
>> 'User.user_permissions'.
>> HINT: Add or change a related_name argument to the definition for
>> 'User.user_permissions' or 'User.user_permissions'.
>>
>> ***
>>
>> Looking forward for your kind help.
>>
>> Thanks,
>>
>> Shazia
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To post to this group, send email to django-users@googlegroups.com.
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-users/CAD83tOyrfzvb3JCrgUFPUqTpxiaf-qLvy50nhgOLgA%2BpsjbURQ%40mail.gmail.com
>> 
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CABL_bk3C5Us9AL%3DBMWwgG25xqt85b6EjNpNik7jqM_4zdujvuQ%40mail.gmail.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAL0P1EX1k0TcAGstM9WhvjrgdfYpqz0nLfxnOpB6w4GVnvfPMw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django Interview Questions

2019-07-07 Thread pooja kaur
I have updated with fresh list  of django interview questions for freshers 
and experienced persons. 

Here  is the list 

https://onlinetutorials.today/python/django-interview-questions/

On Monday, November 2, 2009 at 9:06:41 PM UTC+5:30, Dimitri Gnidash wrote:
>
> Hey guys, 
>
> For all those of you interviewing or being interviewed, I created a 
> quick list of sample interview questions. 
> While not comprehensive, it is a good start to review these before the 
> interview, if anything, to gain a perspective on how other people 
> might be using Django. 
>
>
> http://blog.lightsonsoftware.com/django-interview-questions-0 
>
>
> Dimitri Gnidash 
> www.lightsonsoftware.com

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/d63c1465-dcb5-403f-8687-e9fd54e96682%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Getting AttributeError: module 'asyncio' has no attribute '_get_running_loop'

2019-07-07 Thread Rohit Chopra
Hi Andrew,

Just a small doubt, why same code is working on my local system.
Both local and server have same  version of requirements mentioned in
requirements.txt

Rohit

On Sun 7 Jul, 2019, 9:36 PM Andrew Godwin,  wrote:

> Hi Rohit,
>
> This is my fault - we made a change in the "asgiref" library that
> inadvertently removed Python 3.5 support. Channels still needs to support
> it (even though Django doesn't).
>
> If you update to asgiref 3.1.4, which I've just released, that should fix
> the issue.
>
> Andrew
>
> On Sun, Jul 7, 2019 at 8:52 AM Rohit Chopra 
> wrote:
>
>> Hi All,
>>
>> I am using channels to implement WebSockets.
>> I am trying to send data through WebSockets from *post_save *django
>> signal.
>> Below is my code.
>>
>> **signals.py**
>>
>>
>> @receiver(post_save, sender=CheckIn)
>> def send_data_on_save(sender, instance, **kwargs):
>> channel_layer = get_channel_layer()
>> stats = get_stats()
>> async_to_sync(channel_layer.group_send)(
>> 'dashboard',
>> {
>> 'type': 'send_data',
>> 'message': stats
>> }
>> )
>>
>>
>> analytics = get_analytics()
>> async_to_sync(channel_layer.group_send)(
>> 'analytic',
>> {
>> 'type': 'send_data',
>> 'message': analytics
>> }
>> )
>>
>>
>>
>> **consumers.py**
>>
>>
>> class DashboardConsumer(WebsocketConsumer):
>> def connect(self):
>> self.room_group_name = 'dashboard'
>>
>>
>> # Join room group
>> async_to_sync(self.channel_layer.group_add)(
>> self.room_group_name,
>> self.channel_name
>> )
>>
>>
>> self.accept()
>>
>>
>> def disconnect(self, close_code):
>> # Leave room group
>> async_to_sync(self.channel_layer.group_discard)(
>> self.room_group_name,
>> self.channel_name
>> )
>>
>>
>> # Receive message from WebSocket
>> def receive(self, text_data):
>> text_data_json = json.loads(text_data)
>> message = text_data_json['message']
>>
>>
>> # Send message to room group
>> async_to_sync(self.channel_layer.group_send)(
>> self.room_group_name,
>> {
>> 'type': 'send_data',
>> 'message': message
>> }
>> )
>>
>>
>> # Receive message from room group
>> def send_data(self, event):
>> message = event['message']
>>
>>
>> # Send message to WebSocket
>> self.send(text_data=json.dumps({
>> 'message': message
>> }))
>>
>>
>>
>> this same piece of code is working on my local machine(windows) but when
>> i am trying to run this code on server(ubuntu 16.04) i am getting bellow
>> error:
>>
>> **Traceback**
>>
>>
>>
>> Exception inside application: module 'asyncio' has no attribute
>> '_get_running_loop'
>> File "/usr/lib/python3.5/asyncio/tasks.py", line 241, in _step
>> result = coro.throw(exc)
>> File
>> "/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/sessions.py"
>> , line 183, in __call__
>> return await self.inner(receive, self.send)
>> File
>> "/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/middleware.py"
>> , line 41, in coroutine_call
>> await inner_instance(receive, send)
>> File
>> "/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/consumer.py"
>> , line 59, in __call__
>> [receive, self.channel_receive], self.dispatch
>> File
>> "/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/utils.py"
>> , line 52, in await_many_dispatch
>> await dispatch(result)
>> File
>> "/home/user1/demowebapps/env/lib/python3.5/site-packages/asgiref/sync.py"
>> , line 145, in __call__
>> return await asyncio.wait_for(future, timeout=None)
>> File "/usr/lib/python3.5/asyncio/tasks.py", line 373, in wait_for
>> return (yield from fut)
>> File "/usr/lib/python3.5/asyncio/futures.py", line 361, in __iter__
>> yield self  # This tells Task to wait for completion.
>> File "/usr/lib/python3.5/asyncio/tasks.py", line 296, in _wakeup
>> future.result()
>> File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
>> raise self._exception
>> File "/usr/lib/python3.5/concurrent/futures/thread.py", line 55, in
>> run
>> result = self.fn(*self.args, **self.kwargs)
>> File
>> "/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/db.py",
>> line 14, in thread_handler
>> return super().thread_handler(loop, *args, **kwargs)
>> File
>> "/home/user1/demowebapps/env/lib/python3.5/site-packages/asgiref/sync.py"
>> , line 164, in thread_handler
>> return func(*args, **kwargs)
>> File
>> "/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/consumer.py"
>> , line 105, in dispatch
>> handler

Re: Getting AttributeError: module 'asyncio' has no attribute '_get_running_loop'

2019-07-07 Thread Andrew Godwin
Hi Rohit,

This is my fault - we made a change in the "asgiref" library that
inadvertently removed Python 3.5 support. Channels still needs to support
it (even though Django doesn't).

If you update to asgiref 3.1.4, which I've just released, that should fix
the issue.

Andrew

On Sun, Jul 7, 2019 at 8:52 AM Rohit Chopra  wrote:

> Hi All,
>
> I am using channels to implement WebSockets.
> I am trying to send data through WebSockets from *post_save *django
> signal.
> Below is my code.
>
> **signals.py**
>
>
> @receiver(post_save, sender=CheckIn)
> def send_data_on_save(sender, instance, **kwargs):
> channel_layer = get_channel_layer()
> stats = get_stats()
> async_to_sync(channel_layer.group_send)(
> 'dashboard',
> {
> 'type': 'send_data',
> 'message': stats
> }
> )
>
>
> analytics = get_analytics()
> async_to_sync(channel_layer.group_send)(
> 'analytic',
> {
> 'type': 'send_data',
> 'message': analytics
> }
> )
>
>
>
> **consumers.py**
>
>
> class DashboardConsumer(WebsocketConsumer):
> def connect(self):
> self.room_group_name = 'dashboard'
>
>
> # Join room group
> async_to_sync(self.channel_layer.group_add)(
> self.room_group_name,
> self.channel_name
> )
>
>
> self.accept()
>
>
> def disconnect(self, close_code):
> # Leave room group
> async_to_sync(self.channel_layer.group_discard)(
> self.room_group_name,
> self.channel_name
> )
>
>
> # Receive message from WebSocket
> def receive(self, text_data):
> text_data_json = json.loads(text_data)
> message = text_data_json['message']
>
>
> # Send message to room group
> async_to_sync(self.channel_layer.group_send)(
> self.room_group_name,
> {
> 'type': 'send_data',
> 'message': message
> }
> )
>
>
> # Receive message from room group
> def send_data(self, event):
> message = event['message']
>
>
> # Send message to WebSocket
> self.send(text_data=json.dumps({
> 'message': message
> }))
>
>
>
> this same piece of code is working on my local machine(windows) but when i
> am trying to run this code on server(ubuntu 16.04) i am getting bellow
> error:
>
> **Traceback**
>
>
>
> Exception inside application: module 'asyncio' has no attribute
> '_get_running_loop'
> File "/usr/lib/python3.5/asyncio/tasks.py", line 241, in _step
> result = coro.throw(exc)
> File
> "/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/sessions.py"
> , line 183, in __call__
> return await self.inner(receive, self.send)
> File
> "/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/middleware.py"
> , line 41, in coroutine_call
> await inner_instance(receive, send)
> File
> "/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/consumer.py"
> , line 59, in __call__
> [receive, self.channel_receive], self.dispatch
> File
> "/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/utils.py"
> , line 52, in await_many_dispatch
> await dispatch(result)
> File
> "/home/user1/demowebapps/env/lib/python3.5/site-packages/asgiref/sync.py",
> line 145, in __call__
> return await asyncio.wait_for(future, timeout=None)
> File "/usr/lib/python3.5/asyncio/tasks.py", line 373, in wait_for
> return (yield from fut)
> File "/usr/lib/python3.5/asyncio/futures.py", line 361, in __iter__
> yield self  # This tells Task to wait for completion.
> File "/usr/lib/python3.5/asyncio/tasks.py", line 296, in _wakeup
> future.result()
> File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
> raise self._exception
> File "/usr/lib/python3.5/concurrent/futures/thread.py", line 55, in
> run
> result = self.fn(*self.args, **self.kwargs)
> File
> "/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/db.py",
> line 14, in thread_handler
> return super().thread_handler(loop, *args, **kwargs)
> File
> "/home/user1/demowebapps/env/lib/python3.5/site-packages/asgiref/sync.py",
> line 164, in thread_handler
> return func(*args, **kwargs)
> File
> "/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/consumer.py"
> , line 105, in dispatch
> handler(message)
> File
> "/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/generic/websocket.py"
> , line 39, in websocket_connect
> self.connect()
> File "/home/user1/demowebapps/vmsbackend/check_in/consumers.py", line
> 57, in connect
> self.channel_name
> File
> "/home/user1/demowebapps/env/lib/python3.5/site-packages/asgiref/sync.py",
> line 41, in

Getting AttributeError: module 'asyncio' has no attribute '_get_running_loop'

2019-07-07 Thread Rohit Chopra
Hi All,

I am using channels to implement WebSockets.
I am trying to send data through WebSockets from *post_save *django signal.
Below is my code.

**signals.py**


@receiver(post_save, sender=CheckIn)
def send_data_on_save(sender, instance, **kwargs):
channel_layer = get_channel_layer()
stats = get_stats()
async_to_sync(channel_layer.group_send)(
'dashboard',
{
'type': 'send_data',
'message': stats
}
)


analytics = get_analytics()
async_to_sync(channel_layer.group_send)(
'analytic',
{
'type': 'send_data',
'message': analytics
}
)



**consumers.py**


class DashboardConsumer(WebsocketConsumer):
def connect(self):
self.room_group_name = 'dashboard'


# Join room group
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)


self.accept()


def disconnect(self, close_code):
# Leave room group
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)


# Receive message from WebSocket
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']


# Send message to room group
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type': 'send_data',
'message': message
}
)


# Receive message from room group
def send_data(self, event):
message = event['message']


# Send message to WebSocket
self.send(text_data=json.dumps({
'message': message
}))



this same piece of code is working on my local machine(windows) but when i 
am trying to run this code on server(ubuntu 16.04) i am getting bellow 
error:

**Traceback**



Exception inside application: module 'asyncio' has no attribute 
'_get_running_loop'
File "/usr/lib/python3.5/asyncio/tasks.py", line 241, in _step
result = coro.throw(exc)
File 
"/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/sessions.py"
, line 183, in __call__
return await self.inner(receive, self.send)
File 
"/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/middleware.py"
, line 41, in coroutine_call
await inner_instance(receive, send)
File 
"/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/consumer.py"
, line 59, in __call__
[receive, self.channel_receive], self.dispatch
File 
"/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/utils.py", 
line 52, in await_many_dispatch
await dispatch(result)
File 
"/home/user1/demowebapps/env/lib/python3.5/site-packages/asgiref/sync.py", 
line 145, in __call__
return await asyncio.wait_for(future, timeout=None)
File "/usr/lib/python3.5/asyncio/tasks.py", line 373, in wait_for
return (yield from fut)
File "/usr/lib/python3.5/asyncio/futures.py", line 361, in __iter__
yield self  # This tells Task to wait for completion.
File "/usr/lib/python3.5/asyncio/tasks.py", line 296, in _wakeup
future.result()
File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
raise self._exception
File "/usr/lib/python3.5/concurrent/futures/thread.py", line 55, in run
result = self.fn(*self.args, **self.kwargs)
File 
"/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/db.py", 
line 14, in thread_handler
return super().thread_handler(loop, *args, **kwargs)
File 
"/home/user1/demowebapps/env/lib/python3.5/site-packages/asgiref/sync.py", 
line 164, in thread_handler
return func(*args, **kwargs)
File 
"/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/consumer.py"
, line 105, in dispatch
handler(message)
File 
"/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/generic/websocket.py"
, line 39, in websocket_connect
self.connect()
File "/home/user1/demowebapps/vmsbackend/check_in/consumers.py", line 57
, in connect
self.channel_name
File 
"/home/user1/demowebapps/env/lib/python3.5/site-packages/asgiref/sync.py", 
line 41, in __call__
if asyncio._get_running_loop() is not None:
module 'asyncio' has no attribute '_get_running_loop'





also when i am sending data normally from
javascript  .send()


function it is working normally on server but when post_save signal is 
called then only i get this error on server. this is working fine on my 
local system.
I tried removing *async_to_sync *from signals then it is not giving error 
but it is not transmitting data through web socket.
then it is giving:

./check_in/signals.py:47: RuntimeWarning: Coroutine
'RedisChannelLayer.group_send' was never 

Re: get_absolute_url() necessary with ModelForm ?

2019-07-07 Thread Axel Rau

> Am 06.07.2019 um 18:28 schrieb Daniel Roseman :
> 
>> On Thursday, 4 July 2019 18:45:47 UTC+1, axe...@chaos1.de wrote:
>> I’m using a model in 2 apps with different urls. 
>> Subclasing it and overwriting get_absolute_url() did not work, 
>> because it mangled dbtable. 
>> UpdateView does not work with ModelForm w/o get_absolute_url(). 
>> 
>> Does there any workaround exist? 
>> 
>> Thanks, Axel 
>> 
> 
> UpdateView works perfectly fine without `get_absolute_url()`. It does however 
> need a `success_url` attribute, or a `get_success_url()` method, defined on 
> the view itself.
> --
> DR.

This worked perfectly!

Thanks, Axel

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/3B77821C-FC9B-4295-965E-090D4A0EE839%40Chaos1.DE.
For more options, visit https://groups.google.com/d/optout.


Re: access league by league-code REST api

2019-07-07 Thread Derek
Have you tried without the {'code'}

As per their example:

[image: api1.png]


On Thursday, 4 July 2019 23:42:05 UTC+2, omar ahmed wrote:
>
> hiii ..
> i use REST api to get data from "https://www.football-data.org"; ..
> i want to create one view that can restore any league (by league code 
> like: PL for premier league) not for particular league
> openleague.html
> {% block content %}
> 
> Premier League
> Spanish League
> Italian League
> German League
> French League
> 
> {% endblock %}
> urls.py
> urlpatterns =[
> path('', views.home,name='home'),
> path('/League', views.openleague, name='openleague'),
> ]
> views.py
> def openleague(request,code):
> connection = http.client.HTTPConnection('api.football-data.org')
> headers = { 'X-Auth-Token': '##' }
> connection.request('GET', '/v2/competitions/{'code'}', None, headers)
> response = json.loads(connection.getresponse().read().decode())
>
> return render(request, 'core/openleague.html', {'response': response})
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/b81b7c37-49da-4407-91cc-2aa5b95f464f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.