Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django retrieving submitted value from table
I am trying to create a simple django project, with the following model: class dealerinfo(models.Model): name = models.CharField(max_length=255) required_field_1 = models.ImageField() required_field_2= models.ImageField() How to create a django app that after a user logs in to upload the required files required_field_1 and required_field_2. Thank you for your suggestions and help -
Can't debug Django unit tests within Visual Studio Code
I want to be able to run and debug unit tests for a Django project from within Visual Studio Code. I am an experienced developer, but fairly new to both Django and Visual Studio Code. The crux of the problem is that either the tests are undiscoverable within Visual Studio Code, or if they are discoverable, I get a ConnectionHandler exception when I run them. I provide details for both of these situations below. I apologize for the length of this question, but I thought I should list the many solutions to the problem that I have tried unsuccessfully. I also think that it might be useful to put all of them into one place, rather than have them scattered all over StackOverflow and the rest of the Internet. Best Solution So Far The best solution I have found is at Problem with Django app unit tests under Visual Studio Code . It involves putting these four lines into an __init__.py file: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_app_project.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() This works in my simple tutorial projects, described below, but in a real application some of the tests fail. It looks as though either Django isn't running … -
Django POST stores everything in key instead of key-value pair
I am trying to post several form data in one go (Yes, they need to go in as one post content. No this can not be changed. Don't even suggest having multiple submits.) and I can build correct type of object. convert_to_object is a custom function that converts serialized array into an object with correct key-value pairs save_button.click(function(){ //Collect information console.log("Collecting form data"); var data = {}; data.form1= convert_to_object($("[data-formtype='form1']").serializeArray()); data.form2= convert_to_object($("[data-formtype='form2']").serializeArray()); data.form3= convert_to_object($("[data-formtype='form3']").serializeArray()); var items= []; forms_list.forEach(form_in_list=> { items.push(convert_to_object(form_in_list.serializeArray())); }); data.list_of_items = items; //Send our data object to our endpoint $.post("add", data) .done(function(data, status){ //Success handling }) .fail(function(data, status){ //Failure handling }) }); This creates correct JavaScript object that has all the values in correct shape and I can convert this to JSON string. Issue is that when I send this JSON string to Django I don't get key-value pairs in request.POST, instead I get the entire json string as key and value as empty string. So instead of <QueryDict: { "form1":{"field1":"","field2":"","field3":""}, "form2":{"field1":"","field2":"","field3":"","field4":""}, "form3":{"field1":"","field2":"","field3":"","field4":""}, "list_of_items":[ {"key1":"value1", "key2":"value"}, {"key1":"value1", "key2":"value2"}] }> I get <QueryDict: '{"form1":{"field1":"","field2":"","id":""},"form2":{"field1":"","field2":"","field3":"","field4":""},"form3":{"field1":"","field2":"","field3":"","field4":""},"list_of_items":[ {"key1":"value1", "key2":"value"}, {"key1":"value1", "key2":"value2"}]}' : '' }> As you can see, in the second one the entire set is made into key, instead of series of … -
Django migrations success but Sqlite db failed
just a question regarding migrations in Django with SQlite3: I've created some models in my Django project following the architecture below: EP_project │ db.sqlite3 │ manage.py │ ├───ep │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ 0001_initial.py │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ 0001_initial.cpython-38.pyc │ │ 0002_address.cpython-38.pyc │ │ __init__.cpython-38.pyc │ │ │ ├───models │ │ │ model_address.py │ │ │ model_ap.py │ │ │ model_as.py │ │ │ model_at.py │ │ │ model_user.py │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ model_address.cpython-38.pyc │ │ model_ap.cpython-38.pyc │ │ model_as.cpython-38.pyc │ │ model_at.cpython-38.pyc │ │ model_user.cpython-38.pyc │ │ __init__.cpython-38.pyc │ │ │ ├───tests │ │ test_user.py │ │ │ └───__pycache__ │ admin.cpython-38.pyc │ apps.cpython-38.pyc │ tests.cpython-38.pyc │ urls.cpython-38.pyc │ views.cpython-38.pyc │ __init__.cpython-38.pyc │ ├───ep_project │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ settings.cpython-38.pyc │ urls.cpython-38.pyc │ wsgi.cpython-38.pyc │ __init__.cpython-38.pyc │ └───media └───ad_pics default.jpg The problem is that when I'm making my migrations, it seems that migrations are done properly … -
ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: How I solve it?
When I run: pip install djangorestframework I got this error message: ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/usr/local/lib/python3.6/dist-packages/asgiref' Consider using the --user option or check the permissions. -
Why django don't need all fields to test a model
I have a model like this: class CreateDeal(models.Model): name = models.CharField(max_length=100) fuel = models.CharField(max_length=15) mileage = models.PositiveIntegerField(db_index=True) phone_number = models.CharField(max_length=17) location = models.CharField(max_length=100, db_index=True) car_picture = models.ImageField(upload_to='car_picture') description = models.TextField() price = models.PositiveSmallIntegerField(db_index=True) available = models.BooleanField(default=True) created_on = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) and I have a test class to test the model above like this: class CreateDealTest(TestCase): def setUp(self): self.user = User.objects.create_user( username='alfa', email='alfa@hotmail.com', password='top_secret' ) self.deal = CreateDeal.objects.create( name='deal1', mileage=100, price=25, user=self.user ) def test_deal_name(self): deal = CreateDeal.objects.get(name='deal1') expected_deal_name = f'{self.deal.name}' self.assertAlmostEqual(expected_deal_name, str(deal)) if I run the test I have: Ran 1 test in 0.166s OK My question is why django don't raise an exception since almost all fields in my model are required. And what I don't understand is if I remove one field of Createdeal in my setUp (like mileage, price, user or name) I have an error. For instance if I remove mileage, I have this error: raise utils.IntegrityError(*tuple(e.args)) django.db.utils.IntegrityError: (1048, "Column 'mileage' cannot be null") -
Loading Scripts Conditionally with JS for multilingual django app that uses jquery validation plugin
I have a Django form in which I use the Jquery Validation Plugin to validate. My form needs to appear in multiple languages and I allow the user to change the form language on the click of a button (one button for each possible language). There is a separate script to load for each language to allow for built-in validation messages to show up in that language. For example, if I want default validation messages from this plugin to be in Russian, I would load the "https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/localization/messages_ru.min.js" script. My questions are as follows: Should I really be just appending new scripts to the header section as I do below? Then, if the user clicks back and forth on language buttons, there are going to be a bunch of scripts in my DOM that are completely unnecessary and are just overridden by the last script loaded. Is this problematic? Bad style? Is there a better way to do this? I'm not sure what to do if they click on the 'English' button because in that case, I have to get rid of all of the other language scripts so that it defaults to English. Is there an easy way to go … -
How to pass choices dynamically into a django form
How can I set choices dynamically in my form ? You can see below that I am setting the choices in the RegistrationForm. forms.py class RegistrationForm(forms.Form): options = () camp_dates = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=options) I would like to set the choices from my view.py file so that I can set these choices dynamically. views.py def camp_datailed_view(request,slug): options = ( ("1", "Jan"), ("2", "Feb"), ) form = RegistrationForm() ##How can I pass options into the form field camp_dates as selectable choices -
Django get count of nested related object
I'm using Django 2.2 I have three models class LeadList(SafeDeleteModel): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=128, verbose_name='Lead List Name') def entries_count(self): return LeadListEntry.objects.filter( dynamic_url_object__lead_list=self ).count() class DynamicUrlObject(SafeDeleteModel): lead_list = models.ForeignKey( LeadList, on_delete=models.SET_NULL, blank=True, null=True, default=None, related_name='dynamic_url_object' ) class LeadListEntry(models.Model): dynamic_url_object = models.ForeignKey( 'otherapp.DynamicUrlObject', on_delete=models.CASCADE, related_name='lead_list_entry' ) data = models.TextField(help_text='Lead List entry data. (JSON data)', blank=False) LeadList has reference in the DynamicUrlObject. LeadList can be linked to multiple DynamicUrlObject instances. The LeadListEntry is linked to DynamicUrlObject to record data for each DynamicUrlObject instance. I want to get the count of LeadListEntry for particular LeadList. For that I have a model method in the LeadList model to return the count of the LeadListEntry entries. But on getting the list of LeadList, it is producing N+1 problem where entries_count is called for each lead_list object which in turn runs a query on LeadListEntry to get the count. I tried to use prefetch_related in the view like def get_queryset(self): return self.serializer_class.Meta.model.objects.filter( user=self.request.user ).prefetch_related( 'dynamic_url_object__lead_list_entry' ) But there is no benefit of it. How can I get the count for each lead_list object without running into N+1 problem? -
Django 2.2: TemplateDoesNotExist at/ error
Even after following the suggestions given in the rest of the answers to similar questions I am unable to resolve this error. -
Django Query where one field is duplicate and another is different
I want to know if I can create a query where one field is duplicate and another one is different. Basically I want to get all UsersNames where First Name is the same and user_id is different. I did this UserNames.objects.values("first_name", "user_id").annotate(ct=Count("first_name")).filter(ct__gt=0) This will retrieve a list whit all Users After tis, I make some post processing and create another query where I filter just the users with first_name__in=['aaa'] & user_id__in=[1, 2] to get the users with the same first_name but different user_id Can I do this just in one query? or in a better way? -
digital ocean not loading my product image uploaded from admin panel in django
i have digitalocean hosted site but problem is that when i upload product image from admin panel my site cant reach a image what is problem. please help to solve this problem model is this class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=100, db_index=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) stock = models.PositiveIntegerField() created_at = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) updated_at = models.DateTimeField(auto_now=True) nagix configuration file server { listen 80; server_name 167.172.154.49; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/kiran/khidki; } location /media/ { root /home/kiran/khidki/products; } location / { include proxy_params; proxy_pass http://unix:/home/kiran/khidki.sock; } } settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ] STATIC_ROOT = os.path.join(BASE_DIR,'assets') #STATIC_ROOT = os.path.join(BASE_DIR, 'static/') #managing media MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'products/') -
establishing connection with smtp.gmail.com is failing resulting in timeout error in Django project when i am behind proxy server (gateway)
so i have spent the last two months trying to figure out why my django app that i run locally on my company pc is not sending any emails through smtp.gmail.com. i finally figured that my app is not connecting with the gmail smtp server at all and at the end result in timeout error. i tested this on machines that are connected to the internet directly without a server gateway and everything works perfectly. however on my work machine it doesn't. when i use trace command : sudo traceroute -n -T -p 25 gmail-smtp-in.l.google.com it results in traceroute to gmail-smtp-in.l.google.com (108.177.15.26), 30 hops max, 60 byte packets 1 * * * 2 * * * 3 * * * 4 * * * 5 * * * 6 * * * 7 * * * 8 * * * 9 * * * 10 * * * 11 * * * 12 * * * 13 * * * 14 * * * 15 * * * 16 * * * 17 * * * 18 * * * 19 * * * 20 * * * 21 * * * 22 * * * 23 * * * … -
How to run django task in celery without using django framework
I am running an application-1 (using django framework) which emits django task to rabbitmq queue. I am trying to consume django task from that queue and implement it in my application-2 which uses celery(without django framework). I am facing serialization issue : File "c:\users\kgunasekaran\appdata\local\continuum\anaconda3\envs\py36\lib\site-packages\kombu\serialization.py", line 64, in pickle_loads return load(BytesIO(s)) kombu.exceptions.DecodeError: 'ascii' codec can't decode byte 0xc2 in position 43899: ordinal not in range(128) [2020-02-25 16:04:06,052: CRITICAL/MainProcess] Can't decode message body: DecodeError(UnicodeDecodeError, ....) Dependencies : OS - Windows Python - 3.6 Celery - 3.1.24 pika - 1.1.0 -
Use Django's I18n functions with keys in the code instead of default English
Is there a way to use Django's I18n features with keys in the code instead of storing the default language in the code and the others in .po/.mo files? Something similar to Wikipedia, where the code has a "(whatlinkshere)" key that is translated in the English translation file as "What links here", in the French one as "Pages liées", etc. I guess I could make "qqq" or "qqx" the default language and work from there, but then a person with a browser set in a non-managed language would see the keys instead of English. The problem with having the English as default in the code is that if you make a slight adjustment to a string in English, the translation is lost altogether in the other language versions. -
ProgrammingError when switching from Sqlite3 to Postgresql in django admin console
In django, I have attempted to switch from using an sqlite3 database to postgresql. settings.py has been switched to connect to postgres. Both python manage.py makemigrations and python manage.py migrate run without errors. makemigrations says that it creates the models for the database, however when running migrate, it says there is no changes to be made. The django server will run, however when clicking on a specfic table in the database in the /admin webpage, it throws the error: ProgrammingError at /admin/app/tablename/ relation "app_tablename" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "app_tablename" With the same code (other than settings.py database connection) this worked when using sqlite3. -
Django - how to get length and count commands in template? (query-set in template)
I have these modules: Sales, Gender and Type in Django. Table 1: class Sales(models.Model): name = models.CharField(max_length=100, default="-") gender = models.ForeignKey(Category, on_delete=models.CASCADE) type = models.ForeignKey(Category, on_delete=models.CASCADE) date = models.TextField(default="-") +------+-----+------+------+ | name |gende| type | date | +------+-----+------+------+ | A | 1 | 1 | 2019 | +------+-----+------+------+ | B | 2 | 1 | 2018 | +------+-----+------+------+ | A | 1 | 3 | 2019 | +------+-----+------+------+ | C | 2 | 3 | 2017 | +------+-----+------+------+ | A | 1 | 2 | 2019 | +------+-----+------+------+ Table 2 (key) class Gender(models.Model): id = models.CharField(max_length=25, default="-") gender = models.CharField(max_length=25, default="-") +----+--------+ | id | gender | +----+--------+ | 1 | Male | +----+--------+ | 2 | Female | +----+--------+ | 3 | - | +----+--------+ Table 3 (key) class Types(models.Model): id = models.CharField(max_length=50, default="-") type = models.CharField(max_length=50, default="-") +----+------+ | id | type | +----+------+ | 1 | U1 | +----+------+ | 2 | X2 | +----+------+ | 3 | B1 | +----+------+ | 4 | H3 | +----+------+ Then, I want to count all the things in the main table and show them in the template as below +---------------+---+ | Total records | 5 | +---------------+---+ | Male … -
Django crontab not working in docker container
I need to run a cron job in a docker container. the code works in local environment but not in the container I installed cron in Dockerfile and (for now) manually started cron by service cron start and added crontab by python manage.py crontab add in container's terminal. the python script i'm running with cron has db insertion but there's no change in db nor outputs anything in /cron.log. What am I doing wrong? Cron in settings.py CRONJOBS = [ ('*/2 * * * *', 'api.cron.weekly.register_weekly_schedules','>> /cron.log') ] Dockerfile # Set default python image to 3.7 version # FROM python:3.8.0-alpine FROM python:3.8.0 ENV PYTHONUNBUFFERED 1 WORKDIR / RUN mkdir /logs RUN mkdir /app WORKDIR /app libffi-dev COPY requirements.txt /app/ RUN pip3 install -r requirements.txt RUN apt-get update RUN apt-get install -y cron COPY . /app/ -
How to generate different OTP token for different users using pyotp?
The code is as follows: from pyotp import TOTP In [180]: import datetime In [181]: import time In [182]: now = time.time() In [183]: secret = 'base32secret3232' In [184]: totp = TOTP(secret) In [185]: totp.at(now) Out[185]: '447195' In [186]: totp.at(now+20) Out[186]: '562455' In [187]: totp.at(now+10) Out[187]: '447195' In [188]: totp.at(now+30) Out[188]: '562455' In [189]: totp.at(now+40) Out[189]: '562455' In [190]: totp.at(now+50) Out[190]: '412255' In [191]: totp.at(now+60) Out[191]: '412255' In [192]: totp.at(now+70) Out[192]: '412255' In [193]: totp.at(now+80) Out[193]: '722023' In [194]: totp.interval Out[194]: 30 In [195]: now Out[195]: 1582627336.8869653 My questions are as follows: Why the code prints same token even when the arguments are different. What if different users try to generate the token in the same time window see (20-40 seconds window), then will they get the same token. If yes, how to avoid it? -
Pass argument to Meta class of Django Modelform
I have models that have common fields like this: class Model_1(models.Model): field_1 field_2 field_3 # Other fields class Model_2(models.Model): field_1 field_2 field_3 # Other fields Then I want to create one form for both of them like this: class CommonForm(forms.ModelForm): class Meta: variable_of_name_of_model = that pass to Meta class # this condition check for if variable_of_name_of_model == 'Model_1': model = Model_1 elif variable_of_name_of_model == 'Model_2': model = Model_2 fields = ['field_1', 'field_2', 'field_3'] In this form, I check the variable_of_name_of_model that has been passed to the Meta class and do something after that. How can I do that? In other hand, how can I pass argument to Meta class? -
Selenium in django
How can we implement the selenium in django we want to implement in the views part that is logic part we want to write the selenium code but its happening that selenium code open the browser and backend render the webpage we getting the conflict part How can we solve it -
How to get the checked items(with jquery) in django view?
Here I have a list of checked items in the <ul id ='user-list'> section with the help of jquery. However I am not being able to get these checked items in my django view. template <ul class="approval approval_scrolltab mt-3" id="search_users_results"> {% include 'user_groups/ajax_user_search_results.html' %} </ul> <div class="col-xl-6 col-lg-6 col-md-6 offset-xl-1"> <ul id="user-list" class="approval approval_scrolltab mt-3"> # here I have the checked items from jquery </ul> </div> ajax_user_search_results {% for user in users %} <div class="form-group"> <div class="checkbox"> <input data-name="{{user.first_name}" class="checkbox1" name="users" type="checkbox" value="{{user.pk}}" id="search-user{{user.pk}}"/> <label for="search-user{{user.pk}}"></label> </div> </div> views.py def create_user_group(request): users = get_user_model().objects.filter(is_active=True)[:10] form = CreateUserGroupForm() if request.method == 'POST': form = CreateUserGroupForm(request.POST) if form.is_valid(): group = form.save() users = form.cleaned_data.get('users') for user in users: user.groups.add(group) .... Script to display the checked users <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $('input[class="checkbox1"]').on('change', function() { var image_url = $(this).closest( '.approval--member' ).find( 'img' ).attr('src'); var name = $(this).closest( '.approval--member' ).find( '.approval--name ~ p' ).text(); if($(this).prop('checked')) { $('ul#user-list').append( '<li id="' + name + '">' + '<div class="approval--member">' + '<img src="' + image_url + '" class="user--image" />' + '<div class="w-100">' + '<h6 class="approval--name"></h6>' + '<p>' + name + '</p>' + '</div>' + '<span class="ic-close"></span>' + '</div>' + '</li>'); } else { $('ul#user-list #' + name).remove(); } How can … -
Django and javascript - how to use the value of dropdown box to access the static image stored on server using the static tag
{% load static %} line 1 <html> line 2 <head> line 3 <meta charset="UTF-8"> line 4 </head> <body> <select id="ddlViewBy"> <option value="Pranamasana.jpg">Pranamasana</option> </select> <img id='cat' crossorigin="anonymous" height = "620" width = "620"/> <button onclick = "myfun()">button</button> <script> function myfun() { var e = document.getElementById("ddlViewBy"); var strUser = e.options[e.selectedIndex].value; document.getElementById("cat").src = "{% static 'Pranamasana.jpg' %}"; line 16 } </script> </body> </html> Even though I have a drop down box I am hard coding the name of the image to be accessed in line 16. I want to know the way if I can use the string 'struser' so that the image selected by user can be displayed without hard coding. Any help would be appreciated and thanks in advance. I am using django and this is a html page in my project -
Django chicken and egg situation loading an app that references django modules
I have upgraded a Django app from 1.x to 2.2 but appear to be faced with a chicken and egg situation when trying to incorporate the django-permissions module [ https://pypi.org/project/django-permissions/ ] WHat seems to happen is that in attempting to load this app, Django tries to run its init.py code. But this contains imports of Django modules, which in turn calls the populate() method within Django, which (not unreasonably) complains that this method is not reentrant. Any ideas how to resolve this? I would like to take a fork of django-permissions and adapt it as nencessary to work with Django 2.2 (Rolling back to 1.x is not an option) Thanks in anticipation -
Which Type of Views I should use in Django?
There Are Three Types Of Views as far as I know. 1.Function-Based Views. 2.Class-Based Views. 3.Django Generic Views. Which Views Should I Use and Why Should I use. Thanks Good People.