Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - Runpython function to turn charfield into foreignkey
I've been strugglin to relate a csv imported data model with a spatial data model based on a charfield field, I've created both models and now im trying to transfer the data from one field to a new one to be the foreignkey field, i made a Runpython funtion to apply on the migration but it goives the an error: ValueError: Cannot assign "'921-5'": "D2015ccccccc.rol_fk" must be a "D_Base_Roles" instance. here the the models: class D_Base_Roles(models.Model): predio = models.CharField(max_length=254) dest = models.CharField(max_length=254) dir = models.CharField(max_length=254) rol = models.CharField(primary_key=True, max_length=254) vlr_tot = models.FloatField() ub_x2 = models.FloatField() ub_y2 = models.FloatField() instrum = models.CharField(max_length=254) codzona = models.CharField(max_length=254) nomzona = models.CharField(max_length=254) geom = models.MultiPointField(srid=32719) def __str__(self): return str(self.rol) class Meta(): verbose_name_plural = "Roles" class D2015ccccccc(models.Model): id = models.CharField(primary_key=True, max_length=80) nombre_archivo = models.CharField(max_length=180, blank=True, null=True) derechos = models.CharField(max_length=120, blank=True, null=True) dir_calle = models.CharField(max_length=120, blank=True, null=True) dir_numero = models.CharField(max_length=120, blank=True, null=True) fecha_certificado = models.CharField(max_length=50, blank=True, null=True) numero_certificado = models.CharField(max_length=50, blank=True, null=True) numero_solicitud = models.CharField(max_length=50, blank=True, null=True) rol_sii = models.CharField(max_length=50, blank=True, null=True) zona_prc = models.CharField(max_length=120, blank=True, null=True) ##NEW EMPTY FOREIGNKEY FIELD rol_fk = models.ForeignKey(D_Base_Roles, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return str(self.numero_certificado) class Meta: managed = True #db_table = 'domperm2015cip' verbose_name_plural = "2015 Certificados Informaciones Previas" ordering = … -
Sending emails in django
I want to send email to the user whenever the user gets registered. I have written a code for sending email in my forms.py Below is the code snippet: forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile from django.core.mail import send_mail, EmailMultiAlternatives from django.template.loader import render_to_string, get_template from django.template import Context from django.conf import settings #User registration form class UserRegisterForm(UserCreationForm): email = forms.EmailField() #default is required=True class Meta: model = User #user model will be affected fields = ['first_name','username','email','password1','password2'] def send_email(self): name = self.cleaned_data.get('first_name') username = self.cleaned_data.get('username') to_email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') subject = 'Login details for Django_app' from_email = settings.EMAIL_HOST_USER c = Context( {'name': name}, {'username': username}, {'email': to_email}, {'password': password}, ) plaintext = get_template('register_email.txt') htmly = get_template('register_email.html') text_content = plaintext.render(c) html_content = htmly.render(c) message = EmailMultiAlternatives( subject=subject, body=text_content, from_email=from_email, to=to_email ) message.attach_alternative(html_content, "text/html") message.send() When i register a user email is not sent, can anyone help with this? -
ajax call in django admin pannel with custom app
I have created a question app and I can add the question from admin. There is one Boolean field is_mcq. Now what I want to do is: if mcq is checked, show 4 more fields in the form for more answers and while submit it should store in different table mcq_answers with that question id which will be the latest insert id in the question table. I can do the jquery stuff to show the more fields but I am not sure where should I do this. -
Auto populate select2 when adding values via popup view
I have a web application to manage events with group and tags as specified below: #model.py class Event(models.Model): name = models.CharField('Event Name', max_length=100, help_text='Insert a name for the event') tags = models.ManyToManyField('Tag') group = models.ForeignKey('Group', on_delete=models.SET_NULL, null=True) class Group(models.Model): name = models.CharField('Group name', max_length=50, help_text='Insert a name for the group') description = models.CharField('Description', max_length=100, help_text='Insert a description for the group (optional)', blank=True) class Meta: verbose_name_plural = "Groups" ordering = ['name'] def __str__(self): return self.name class Tag(models.Model): name = models.CharField('Tag name', max_length=50, help_text='Insert a name for the Tag') group = models.ForeignKey('Group', on_delete=models.SET_NULL, null=True) class Meta: ordering = ['name'] # to avoid accepting a tag with the same value & group unique_together = ['name', 'group'] def __str__(self): return self.name I wish to have tags fields chained with group value selected. To do this, I took inspiration from these discussions: - https://stackoverflow.com/a/48608535 - https://stackoverflow.com/a/47843768 So I override my change_form.html: {% extends 'admin/change_form.html' %} {% block admin_change_form_document_ready %} {{ block.super }} <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script> <script type="text/javascript"> var url = 'myUrl'; getRelatedTags(url); /* get tags related to a group */ function getRelatedTags(url) { // initiate select2 $("#id_tags").select2({}); // make initial call to populate tags related to group $.getJSON(url, {id: $('select#id_group').val()}, … -
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", …