Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RelatedObjectDoesNotExist at /rest-auth/user/: User has no userprofile
I am trying to update UserDetailsSerializer and the problem is when I run my code in my test model it works but when I use it in my actual app, it throws this error: 'User' object has no attribute 'userprofile' model.py class userProfileModel(models.Model): GENDER = [ ('', ""), ('M', "Male"), ('F', "Female") ] user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userprofile', default='') avatar = models.ImageField(upload_to='avatar/', default='avatar/no-avatar.png') age = models.DateField(auto_now_add=True) gender = models.CharField(max_length=10, choices=GENDER, default='') address = models.CharField(max_length=500, default='') longitude = models.FloatField(default=0.0) latitude = models.FloatField(default=0.0) phone = models.IntegerField(default=0) user_is_active = models.BooleanField(default=False) def __str__(self): return self.user.username serializers.py class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = userProfileModel fields = ( 'id', 'avatar', 'age', 'gender', 'address', 'longitude', 'latitude', 'phone', ) class UserDetailsSerializer(UserDetailsSerializer): profile = UserProfileSerializer(source='userprofile') class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ('profile',) read_only_fields = ('',) def update(self, instance, validated_data): # User data nested_serializer = self.fields['profile'] nested_instance = instance.userprofile nested_data = validated_data.pop('userprofile') nested_serializer.update(nested_instance, nested_data) return super(UserDetailsSerializer, self).update(instance, validated_data) The error: RelatedObjectDoesNotExist at /rest-auth/user/ User has no userprofile. -
why i am getting 500 server error on heroku while deploying django app?
i am trying my django app on django but it shows server error(500). when i run herkou logs --tail , it shows following error:- » Error: Missing required flag: » -a, --app APP app to run command against » See more help with --help and my Procfile file is, web: gunicorn Diary.wsgi --log-file - what point i am mising? -
Instance value not being selected in edit form field
I have a ModelForm with the following field: CHOICES = (('', 'no answer'), (0, 'no'), (1, 'yes')) answer = forms.ChoiceField(widget=forms.RadioSelect, initial='', choices=CHOICES) This field is actually a NullBooleanField in the model, so all possible values are None, False and True. The field is initialized if an instance exists so that the appropriate value is selected: def __init__(self, *args, **kwargs): # super... if self.instance.pk: # convert the model field value to the field value the form expects self.fields['answer'].initial = {None: '', True: 1, False: 0}[self.instance.answer] The problem is that when loading an edit form (existing instance), no value is getting selected in the radio widget. Why and what can I do to solve it? -
Django: Unable to pass signal between multiple connected models?
These are my models: class Selectdatefield(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,related_name="Users",on_delete=models.CASCADE,null=True,blank=True) start_Date = models.DateField(default=datetime.date(2018,4,1),blank=True, null=True) end_Date = models.DateField(default=datetime.date(2019,3,31),blank=True, null=True) class Group1(models.Model): group_Name = models.CharField(max_length=32) class Ledger1(models.Model) creation_Date = models.DateField(default=datetime.date.today,blank=True, null=True) name = models.CharField(max_length=32) group1_Name = models.ForeignKey(Group1,on_delete=models.CASCADE,null=True,related_name='ledgergroups') closing_balance = models.DecimalField(default=0.00,max_digits=10,decimal_places=2,blank=True) class Journal(models.Model): date = models.DateField(default=datetime.date.today) by = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='Debitledgers') to = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='Creditledgers') debit = models.DecimalField(max_digits=10,decimal_places=2,null=True) credit = models.DecimalField(max_digits=10,decimal_places=2,null=True) I want to pass a signal that when the user will create or update the Selectdatefield model automatically a Journal object should be created or updated for specific group objects of specific ledger objects with their closing balance field values (which is calculated in the views). unable to understand who will be the sender and how to connect the instance of journal to that of those specific ledgers of those specific groups. hierarchy: Datefield surrounds [Journal> ledger> groups]. Can someone suggest the solution? thanx in advance ! -
django - got stuck in path generation problem
The function: def custom_path(path): new_path = os.path.abspath(path) def get_path(): return new_path return get_path the problem is in custom_path that when called inside this get_image_path function, creates a directory with absolute path like <function custom_path at 0x7f432d99e158>/somedir/finalName.*ext, but I want it to return as a string representation def get_image_path(instance, file): ''' saves file to some location ''' file_path = custom_path* new_file = random.randint(1, 45360789120) name, ext = get_file_ext(file) ranstr = random_string_generator(size=4) final_ = f'{ranstr}_{new_file}{ext}' return f'{file_path}/{new_file}/{final_}' The sender: from ... import custom_path, get_image_path custom_path('posts') class Post(models.Model): ... ... image = models.FileField(upload_to=get_image_path, null=True, blank=True, verbose_name='article image (optional)') ... ... otherwise, i've to modify this fucntion as ... def get_image_path(instance, file): ... ... return f'posts*/{new_file}/{final_}' # and so on for *different models.. I've also tried something like this... def get_image_path(instance, file): ... ... return f'{new_file}/{final_}' base = os.path.dirname('posts/') upload_path = base + os.path.join(str(get_image_path)) class Post(models.Model): ... ... image = models.FileField(upload_to=upload_path, null=True, blank=True, verbose_name='article image (optional)') ... ... outputs: ''/newDir/newFile.*ext, how to get rid from it? 🙄️😶️ -
How can I save picture that I captured with js and html to my django database
I am building a webapp that can allow user to take picture from camera and save it to the database and then process it using opencv, before uploading it back to the client. -
Right way to convert to date
I have a field where users can choose vehicle warranty. They can choose 1 year, 2, years and end datum. When I get it from the database it's unicoded. When I do print(car['warranty']) I get 2019-12-20T08:59:49.897Z" When I do print(type(car["warranty"])) I get <type 'unicode'>. How can I convert it and check if it's a date or if it's a or something else. Depending on that I want to show a label: If its a date I want to show: Valid until formated_date If its a number I want to show: 2 year warranty I use python 2.7. -
Accessing Django's template folder via /static/js/
In a Djano project of mine, I have a JS file inside /project/static/js/. It needs access to a files stored at /project/templates/. I'm unable to access this location from the js file. Can someone suggest a work around (short of keeping duplicates of the said files in the JS folder). I'd like to avoid duplication (since it doubles my maintenance down the road) -
Python / Django fails at decoding file encoded as base64 by javascript
I'm using this, in react, to base64 encode an image file: fileToBase64 = (filename, filepath) => { return new Promise(resolve => { var file = new File([filename], filepath); var reader = new FileReader(); reader.onload = function(event) { resolve(event.target.result); }; reader.readAsDataURL(file); }); }; Which gets called by this: handleChangeFile = event => { const { name, files } = event.target; if (files.length) { const file = files[0]; let fields = this.state.fields; this.fileToBase64(file).then(result => { fields[name].value = result; }); fields[name].isFilled = true; this.setState({ fields: fields }); } }; And the whole fields variable gets posted to a django server, no issues so far. On the python django end: str_encoded = request.data["file"] str_decoded = base64.b64decode(str_encoded) The second line returns an error that binascii.Error: Invalid base64-encoded string: length cannot be 1 more than a multiple of 4. I've googled and read that this is probably a padding issue, but I don't know how to fix it. -
Unable to load libraries in Django
I have an ongoing virtual environment and have installed all the libraries too still getting import Error Showing Errors for Numpy, sklearn, pandas, quandl, scikit-learn I have imported the libraries too. So whats the main problem here! It's not working in Virtual Environment Only ! -
user.is_authenticated returns False with custom backend
I've created a custom backend for my application in order to let people log in with ldap. Seems like everything is working, apart from one thing: I am checking if "user.is_authenticated" in template to show "Log out" button for authenticated users, and it seems to return false all the time. I am using standard django LoginView. Before I added my custom backend it all worked just fine, and I only rewrote the "authenticate()" function the way it says in django docs. How could I fix it? -
How to remove port 8000 from url react.js appli using django and aws. Url like:http://dev.myapplication.io:8000 & want output:dev.myapplication.io
I bulid an application using django,postgres, reactjs and AWS in windows 10. IN which i need to remove port 8000 from the url :http://dev.myapplication.io:8000 to http://dev.myapplication.io -
Form field for NullBooleanField not selecting None value
I am using a ModelForm for a model that has a NullBooleanField. I am trying to display all three choices as radio buttons so I am using a TypedChoiceField with a RadioSelect widget: class MyForm(forms.ModelForm): CHOICES = ((True, 'Yes'), (False, 'No'), (None, 'no answer')) answer = forms.TypedChoiceForm(widget=forms.RadioSelect, empty_value=None, coerce=bool, choices=CHOICE) However when loading a new form, "no answer" is not selected by default, as it should; it isn't selecting either when loading an edit form with that selected answer. The field simply shows up unselected. -
Django - filter from db or compute in python
Suppose now I have 2 models, A and B. And there is a many-to-many relationship between A and B class B(models.Model): score_b = model.IntegerField() class A(models.Model): b = models.ManyToMany(B, related_name='b_set') score_a = models.IntegerField() == The work flow is first I filter some A instance by score_a, and use them to query B with score_b So a naive piece of code may look like this (Solution A) ## Solution A b_list = [] a_list = A.objects.filter(score_a__gte=100) for a in a_list: qs = a.b_set.filter(score_b__gte=200) b_list.extend(list(qs)) return b_list But I'm trying my best to improve the performance And the previous code seems to require 1 + len(a_list) database access So I would try to use prefetch_related (Solution B) ## Solution B b_list = [] a_list = A.objects.filter(score_a__gte=100).prefetch_related('b') for a in a_list: qs = a.b_set.filter(score_b__gte=200) b_list.extend(list(qs)) return b_list However, it seems like the cached b will be ignore because filter is a different query. So the above code is not helping at all. It now requires 1 + 1 + len(a_list) database access because of the additional prefetch_related query Now I come up with another idea which is filter b in python to reduce database access (Solution C) ## Solution C b_list = [] … -
Naming Convention for fields of a model in django
What are some naming convention for fields of a model in django. My problem is I am getting an error django.core.exceptions.ImproperlyConfigured: Field name `tutor1` is not valid for model `ClientEntry` Is using integers in a field name is just wrong? What are my options to name it in number like tutor1, tutor2, tutor3? I also tried tutor_1 but got the same error. Note: tutor1 postgres ArrayField -
OperationalError at /admin/auth/user/add/ no such table: main.auth_user__old
Iḿ a newbee br learning programming. I'm having this error when running my Django server on Manjaro Gnome after clicking in save to add user in the section users from admin area. Saw similar error [here]`Django - No such table: main.auth_user__old' and the most voted answer told to "downgrade your version of sqlite to a version prior to 2.6 (e.g. 2.5.1)" but I don't know how to do this. Could someone help me? Already googled how to downgrade my sqlite version but couldn't find a good explained answer. Asked the instructor of udemy course but didn't have an answer yet. Tried to reinstall older version of Django but didn't work. Following is error: OperationalError at /admin/auth/user/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/auth/user/add/ Django Version: 2.1.4 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: /usr/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 296 Python Executable: /usr/bin/python3 Python Version: 3.7.1 Python Path: ['/home/erion/Área de trabalho/sistema', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/usr/lib/python3.7/site-packages'] Server time: Fri, 21 Dec 2018 11:49:24 +0000 (tried to copy the traceback but receive a warning saying there were code not idented and couldn't be able to fix it) This error and traceback appear when I tried to add … -
Django code to execute only in development and production
I need to execute some housekeeping code but only in development or production environment. Unfortunately all management commands execute similar to runserver. Is there any clean way to classify what is the execution environment and run the code selectively. I saw some solutions like 'runserver' in sys.argv but it does not work for production. And does not look very clean. Does django provide anything to classify all these different scenarios code is executing at? -
How to annotate django query based on two fields
I'm trying to get 3 values : the Surveys_count for each user, the Switches_count for each user and the for each user + SKU I need the Count of switches The first two are already solved: users = \ User.objects.prefetch_related('survey_set').filter(survey__new_brand=request.GET.get('brand'), survey__bool_switch=True, survey__date__gte=request.GET.get('date1'), survey__date__lte=request.GET.get('date2')).annotate( count_surveys=Count('survey'), count_switches=Count('survey__switch')) my models : User model + class Survey(models.Model): user = models.ForeignKey(User, models.DO_NOTHING, blank=True, null=True) date = models.DateField() behalf = models.ForeignKey(User, models.DO_NOTHING, blank=True, null=True,related_name='behalf') bool_switch = models.BooleanField(null=True, blank=True,default=False) reason = models.ForeignKey(Reason, models.DO_NOTHING, null=True, blank=True) shift = models.ForeignKey(ShiftingTime, models.DO_NOTHING, null=True, blank=True) current_brand = models.ForeignKey(CurrentBrand, models.DO_NOTHING, null=True, blank=True) new_brand = models.ForeignKey(NewBrand, models.DO_NOTHING, null=True, blank=True) current_sku = models.ForeignKey(CurrentSku, models.DO_NOTHING, null=True, blank=True) pos = models.ForeignKey(Pos,models.DO_NOTHING, null=True, blank=True,related_name='surveys') switch = models.ForeignKey(Switch, models.DO_NOTHING, null=True, blank=True,related_name='switches') class Switch(models.Model): time = models.TimeField(blank=True, null=True) count_outers = models.IntegerField(blank=True, null=True) count_packs = models.IntegerField(blank=True, null=True) smoker = models.ForeignKey(Smoker, models.DO_NOTHING, blank=True, null=True) new_brand = models.ForeignKey(NewBrand, models.DO_NOTHING, blank=True, null=True) new_sku = models.ForeignKey(NewSku, models.DO_NOTHING, blank=True, null=True) class NewSku(models.Model): sku = models.CharField(max_length=50, null=True, blank=True) brand = models.ForeignKey(NewBrand, models.DO_NOTHING, blank=True, null=True) -
Django multi-table/concrete inheritance alternatives for basic data model pattern
tl;dr Is there a simple alternative to multi-table inheritance for implementing the basic data-model pattern depicted below, in Django? Premise Please consider the very basic data-model pattern in the image below, based on e.g. Hay, 1996. Simply put: Organizations and Persons are Parties, and all Parties have Addresses. A similar pattern may apply to many other situations. The important point here is that the Address has an explicit relation with Party, rather than explicit relations with the individual sub-models Organization and Person. This specific example has several obvious shortcomings, but that is beside the point. For the sake of this discussion, suppose the pattern perfectly describes what we wish to achieve, so the only question that remains is how to implement the pattern in Django. Implementation The most obvious implementation, I believe, would use multi-table-inheritance (a.k.a. concrete inheritance): class Party(models.Model): """ Note this is a concrete model, not an abstract one. """ name = models.CharField(max_length=20) class Organization(Party): """ Note that a one-to-one relation 'party_ptr' is automatically added, and this is used as the primary key (the actual table has no 'id' column). The same holds for Person. """ type = models.CharField(max_length=20) class Person(Party): favorite_color = models.CharField(max_length=20) class Address(models.Model): """ Note … -
Django (django-ses-gateway) gives default region as EU-WEST-1 instead of US-EAST-1
I am having application on EC2 that requires to send an email. I am using Django with AWS, and module of 'django-ses-gateway' to send an email. EC2 is configured, hence on ~/.aws folder I am having appropriate credentials file with region as 'default' However, whenever application tries to send an email by default it is trying to use "EU-WEST-1" region which is not expected one, as it should use "US-EAST-1". Because of wrong region, application fails. PS: I also verified that "settings.py" file is not overwriting region, -
django test case ValueError: The given username must be set
I am testing a Django application, for its user sign-up feature, whether the posted data is correct and post request executes successfully. In views.py, the Class CustomerSignUpView class CustomerSignUpView(View): def post(self, request): name_r = request.POST.get('customer_username') password_r = request.POST.get('customer_password') email_r = request.POST.get('customer_email') contact_number_r = request.POST.get('customer_contact_number') profile_picture_r = request.POST.get('customer_profile_picture') if checkemail(email_r): # receiving an error here c = User(username=name_r, password=password_r, email=email_r) c.save() p = Profile(user=c, phone_number=contact_number_r, profile_picture=profile_picture_r) p.save() return render(request, 'catalog/customer_login.html') else: return render(request, 'catalog/customer_signup.html') def get(self, request): return render(request, 'catalog/customer_signup.html') This is the test case for user account creation class CustomerSignUpViewTest(TestCase): """ Test case for User Sign in """ def test_registration_view_post_success(self): """ A ``POST`` to the ``customer_signup`` view with valid data properly creates a new user and issues a redirect. """ data = { 'username': 'testuser1', 'password': '1X<ISRUkw+tuK', 'email': 'foobar@test.com', 'phone_number': '9876543210', } response = self.client.post(reverse('customer_signup'), data, follow=True) self.assertEqual(response.status_code, 200) self.assertTrue(response.url.startswith('/catalog/customer_login/')) The test encounters the following error: ValueError('The given username must be set') Error Traceback (most recent call last): File "/Users/sndtcsi/PycharmProjects/Library/catalog/tests.py", line 54, in test_registration_view_post_success response = self.client.post(reverse('customer_signup'), data, follow=True) File "/Users/sndtcsi/PycharmProjects/Library/venv/lib/python3.7/site-packages/django/test/client.py", line 535, in post response = super().post(path, data=data, content_type=content_type, secure=secure, **extra) File "/Users/sndtcsi/PycharmProjects/Library/venv/lib/python3.7/site-packages/django/test/client.py", line 349, in post secure=secure, **extra) File "/Users/sndtcsi/PycharmProjects/Library/venv/lib/python3.7/site-packages/django/test/client.py", line 414, in generic return self.request(**r) File "/Users/sndtcsi/PycharmProjects/Library/venv/lib/python3.7/site-packages/django/test/client.py", … -
ChoiceField with RadioSelect does not automatically select None values
I am loading a form to edit a model defining the following field: CHOICES = ((1, 'One'), (2, 'Two'), (None, 'Nothing')) choice = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) The problem is that when the initial value for choice is None, it doesn't get automatically selected in the form. What can I do about it? -
How do I pass arguments in Django REST framework modelviews?
Here is my views for DRF API class CityEventsViewSet(viewsets.ModelViewSet): def __init__(self, request, *args, **kwargs): queryset = CityEvents.objects.filter(city=kwargs.get('city_name')) serializer_class = CityEventsSerializer URL: router.register(r'cityevents/(?P<city_name>[\w\-]+)/$', CityEventsViewSet, base_name='cityevents') I am not able to access the views function. It is not able to resolve the URL. -
Djnago - Instance Value
In this u_form and p_form im getting the current user which is logged in and when i am updating another users it is filling up form with logged in user instant i want userprofile detail of the user i want. So basically i want to change instance request.user and request.user.userprofile will have current user. But i want to update the user which is not logged in. I want a this request.user from template so that i can update it. u_form = UserUpdateForm(instance=request.user) p_form = UserProfileForm(instance=request.user.userprofile) -
Overriding the UserDetailsSerializer in django-rest-auth
I am trying to modify the UserDetailsSerializer with a customized User Detail, but when the server is running, it throws an error of " 'User' object has no attribute 'user'". I tried a lot of methods and none of them work. My code is: mode.py class userProfileModel(models.Model): GENDER = [ ('', ""), ('M', "Male"), ('F', "Female") ] user = models.OneToOneField(User, related_name='userprofile', on_delete=models.CASCADE, default='') age = models.DateField(auto_now_add=True) gender = models.CharField(max_length=10, choices=GENDER, default='') phone = models.IntegerField(default=0) user_is_active = models.BooleanField(default=False) def __str__(self): return self.user.username And serializers.py from rest_auth.serializers import UserDetailsSerializer from rest_framework import serializers from .models import userProfileModel class Profile(serializers.ModelSerializer): user = UserDetailsSerializer() class Meta: model = userProfileModel fields = ('user',) class UserDetailsSerializer(UserDetailsSerializer): profile = Profile(many=True) class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ('profile',) read_only_fields = ('',) And settings.py REST_AUTH_SERIALIZERS = { 'USER_DETAILS_SERIALIZER': 'app.serializers.UserDetailsSerializer', } When I run this code, it throws this error. Got AttributeError when attempting to get a value for field profile on serializer UserDetailsSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'profile'.