Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AJax does not seem to work on the delete button
I am really new to ajax. I want to delete the entry from database on button click and I do not want the page to reload. but the ajax doesn't seem to work at all. What is wrong in my code? Please suggest the correct code. Thanks in advance. <script> $(document).on('click','#delete',function(){ var a ; a=confirm("Do you really want to delete the user?"); if(a==true){ var newurl = "{% url 'NewApp:centredelete' pk=1%}" var id = $(this).attr('name') $.ajax( { type:"GET", url: "newurl.replace('1',id);", data:{ delete:True }, success: function( data ) { if(data.success == true){ $(id).remove(); } else{ alert(data.error) } } })} }); </script> views.py def CentreDeleteView(request, pk): centre = Centre.objects.get(pk=pk) centre.delete() return HttpResponseRedirect(reverse('NewApp:centrelist')) -
How to add checkboxes on a very specific point on the image in django?
There are two questions here. 1) I want to make check boxes solder points for a chip. So how do I go about displaying those specific soldering points/check boxes on the image? 2)If I have multiple such chips with varying number of solder points, how do I proceeding making such number of check boxes without making too many tables in my db? So far I have thought of changing the background of the page and displaying check boxes. But since I have too many images I cant keep having to specifically 20-25 check boxes. I though of using a grid layout to help, but in that case a new grid layout for each image separately will be required because some places the solder joints are too close to each other. I don't know how to make one dynamic multiple choice field that will change the number of choices depending on the image. I don't know how to set said choices in a particular pattern on the image itself either. PS: I'm fairly new to Django and web development as a whole so any help whatsoever is most welcome -
How to limit the choices of foreignkey in Inline Admin model?
I'm working on this survey application. So the questions are classified into sections of different survey forms. The designing of the form is to be done from the admin panel. (I use grappelli). Each survey design form has section inline form and multiple question inline forms. When deciding the section for question, the drop down lists all the sections, irrespective of the survey form it is associated with. How do I populate the dropdown with the sections of the same survey form? This is for python 3.7 and Django 2.1.5. I've the models hierarchy as -> Survey -user ... Section -survey ... Question -section -survey ... The admin form has these components -> FeedbackAdmin -QuestionInline -SectionInline In the SectionInline I tried defining it like this after many attempts and reading multiple answers, but in vain field = super(QuestionInline, self).formfield_for_foreignkey(db_field, request, **kwargs) if db_field.name == 'sections': if request._obj_ is not None: field.queryset = field.queryset.filter(sections = request._obj_) else: field.queryset = field.queryset.none() return field This works without any error but doesn't do as expected. If the survey I has sections A and B, survey II has sections C and D, every question in survey should have a choice between A and B, but … -
Django: can we alter filefield such that when a file is selected, it immediately gets uploaded
I was just wondering: Will it be possible to alter the File Field such that when a file is selected, it immediately gets uploaded, without the means of additional button? Assuming that I imported everything from .models, .forms, urls.py, etc successfully, Codes in models.py: class data(models.Model): Datas = models.FileField(upload_to='datas/upload') Codes in forms.py: class form1(forms.ModelForm): class Meta: model = data fields = ('Datas',) Codes in views.py: def upload(request): if request.method == 'POST' and 'btnform1' in request.POST: newform1 = form1(request.POST, request.FILES) if newform1.is_valid(): newform1.save() return redirect('list') Codes in upload.html: <h2>Data</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{newform1.as_p}} <!-- <button type="submit" class="btn btn-primary" name="btnform1">Upload Data</button>--> </form> Can anyone guide me and possibly give a solution on how to do it if it is even possible? Thank you. -
Django Celery & Django-Celery-Beat
I'm new to asynchronous tasks and I'm using django-celery and was hoping to use django-celery-beat to schedule periodic tasks. However it looks like celery-beat doesn't pick up one-off tasks. Do I need two Celery instances, one as a worker for one off tasks and one as beat for scheduled tasks for this to work? -
Want to Authenticate only Superuser
I want want give access to an html file to only the Superuser. Just how {% if user.is_authenticated %} authenticates all the users including the superusers, is there any way i can only authenticate superusers and not non superusers? {% block title %}base{% endblock %} {% block content %} {% if user.is_authenticated %} {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{% block title %}Django{% endblock %}</title> </head> <body> <main> {% block content %} {% endblock %} </main> </body> </html> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">login</a> {% endif %} {% endblock %} -
How to write a django filter query for multiple values selected from a dropdown list?
I wrote a views function to search/filter my data in django based on certain parameters. In the fields categories and locations the user can select multiple options to make the search. My views function is as follows: def search(request): queryset_list = Influencer.objects.order_by('-followers').distinct().values('id', 'full_name','username','photo','email_id','location_city','categories__name','website') if 'username' in request.GET: username = request.GET['username'] if username: queryset_list = queryset_list.filter(username__icontains=username) #Full Name if 'fullname' in request.GET: fullname = request.GET['fullname'] if fullname: queryset_list = queryset_list.filter(full_name__icontains=fullname) if 'location' in request.GET: location = request.GET['location'] for i in location: queryset_list = queryset_list.filter(location_city__icontains=i) if 'categories' in request.GET: categories = request.GET['categories'] if categories: queryset_list = queryset_list.filter(categories__name__iexact=categories) The search function should return the data of all the categories and location for which the search is made. For e.g. if search is made for location Delhi and Mumbai then it should return all the Influencers which have their location as Delhi or Mumbai, same is for categories also. The search function works perfect for single values but doesn't work for multiple values. For e.g if Delhi is send in the location category, then it returns correct results but if Delhi, Mumbai is selected then it reads only the first value i.e Delhi and applies the filter accordingly. How should I modify the search … -
How to do unit testing in django?
Here I am trying to do testing for my add_course view but it is not working even though the add_course function works properly .I think the problem is in test.py file .This is my first unit-testing so is there any mistake in my code ? Got this when i do python manage.py test: AssertionError: 302 != 200 ---------------------------------------------------------------------- Ran 1 test in 0.022s FAILED (failures=1) Destroying test database for alias 'default'... app/urls.py app_name = 'admin' urlpatterns = [ path('add-course/', views.add_course, name='add_course'), ] views.py def add_course(request): if request.method == 'POST': form = AddCourseForm(request.POST or None) if form.is_valid(): course = form.save() course.save() messages.success(request, 'course with title {} added.'.format(course.title)) return redirect('admin:add_course') else: form = AddCourseForm() return render(request, 'admin/add_course.html', {'form': form}) tests.py import unittest # from django.test import TestCase from django.test import Client from django.urls import reverse # Create your tests here. COURSE_URL = reverse('admin:add_course') class AddCourseTest(unittest.TestCase): def setUp(self): self.client = Client() def test_details(self): response = self.client.post('/admin/add-course/') self.assertEqual(response.status_code, 200) -
how to get date after some specific number of days from given date in django template
I am new in django. I want to get date after some specific number of days or number of weeks in html template file. my template file code: {% for factors in c.factor %} {% for factor_details in factors.factor_values %} {{factor_details.id}} {{factor_details.factor_value}} # here this is given date {{order_detail.oderdate}} and this is number of days and weeks {{factor_details.factor_value}}. {% endfor %} {% endfor %} -
django field required erroe while submitting form
I am trying to submit my problem but again and again it is showing "this field is required" instead of filling all fields. models.py class Cabin(models.Model): random_string = str(random.randint(100000, 999999)) centre_name = models.ForeignKey(Centre, on_delete=models.CASCADE ) code = models.CharField(max_length=6, blank=False, unique=True, default=random_string) total_seats = models.IntegerField(blank='False') views.py class CabinCreateView(CreateView): fields = '__all__' model = Cabin success_url = reverse_lazy("NewApp:logindex") "this field is required" -
join and aggregate using django orm
I have two tables user and purchase purchase table has columns user purchase_total and user table has columns userid and username In here i want to do inner join to find the total purchase for each user I need to how do I do the inner join between user and purchase and aggregate to find the total purchase for each given user. using django ORM Query below is the query i have that would do this type of join: select user.* sum(purchase_total) AS total purchase from user inner join purchase on purchase.id = user.id How do I create a django orm query using this. -
Effect of translate google translate
I work on a number convector, the essence of the problem is that there are two fields, one for input and the other for reading only. I would like to make the server process real time, but for now I only thought of a button. Tell me what options there are. I use Django 2.2 -
How to get list of all objects of logged in user's here in django?
I tried getting the list of objects from the current logged users. There something missing in the codes. I wrote a class-based view as well as function-based views. Class-based views give an error like 1 positional argument but two were given. And in function-based view it giving only first item instead looping through it. I want to show the pass investments inventory record of each investor. Thank you! views.py (Function-Based Views) def InvestmentListView(request): investors = Investment.objects.all(id=request.user.id) args = {'investors':investors} return render(request, 'investors/myinvest.html', args) This only retrieving an only first item. views.py (class-Based viewa) class InvestmentListView(ListView): model = Investment template_name = 'investors/myinvest.html' context_object_name = 'total_invested_by_user' def get_queryset(self): return Investment.objects.filter(investor=self.request.user.id) This CBV gives an error like 1 positional argument, but 2 were given. myinvest.html <div class="container"> {% if user.is_authenticated %} <h2>Investor Name: {{ request.user }}</h2> <table> <tr> <th>Amount Invested</th> <th>Date</th> <th>Rate Of Interest</th> <th>Return</th> <th>Profit</th> </tr> <tr> {% for invest in investors %} <th>{{ invest.amount }}</th> <th>{{ invest.timestamp }}</th> <th>{{ invest.rate }}</th> <th>None</th> <th>None</th> {% endfor %} </tr> </table> {% endif %} Here, models.py class Investor(models.Model): name = models.CharField(max_length=99) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class Investment(models.Model): amount = models.FloatField(blank=False) rate = models.FloatField(blank=False) timestamp = models.DateField(default=datetime.now) investor = models.ForeignKey(Investor, on_delete=models.CASCADE) … -
Django:In this situation, how can I migrate? migrate is not working
First, the existing model is in '0001_initial.py'. After adding the 'models' I added, and when I did 'makemigrations', It's going into '0002_xxx.py'. I succeeded in Migrate, and there was no problem with the database. And then when these 'models' were added, I wanted to put the initial data into the database. so I made fixture folder for putting in initial data after make migrations. I put the json file in it. However, when I changed the name of 'model' and did 'makemigrations' again, I had an error finding the table. So I went directly to sqlite and erased all the tables on the new models. Then I did makemigrations. After that, python3 manage.py migrate sbimage When I do 'migrate' here like this, django.db.utils.OperationalError: table "sbimage_camerathreshold" already exists There's an error like this. python3 manage.py migrate sbimage --fake This has made both 0001, 0002 'FAKED'. It's my 0002 file was created after 'makemigrations'. from django.db import migrations, models def load_my_initial_data(apps, schema_editor): call_command("loaddata", "addition.json") class Migration(migrations.Migration): dependencies = [ ('sbimage', '0001_initial'), ] operations = [ migrations.CreateModel( name='AuthNumberR', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('auth_number_r', models.CharField(max_length=64)), ], ), migrations.CreateModel( name='AuthNumberT', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('auth_number_t', models.CharField(max_length=64)), ], ), migrations.CreateModel( name='Claimant', fields=[ … -
How to do INNER JOIN to another queryset/query
I have a problem with Django ORM. I have a model Weather: class Weather(models.Model): city = models.ForeignKey(City, verbose_name='Город', on_delete=models.CASCADE) temperature = models.FloatField('Температура') source = models.CharField('Источник', max_length=100) date = models.DateTimeField('Дата и время') I want to get actual weather from every source for every city. I created sql query for that but I don't understand how to do it with Django ORM. Query: SELECT * FROM api_weather t1 INNER JOIN ( SELECT MAX(date) AS latest_date, city_id, source FROM api_weather WHERE date<='2019-07-04 15:50' GROUP BY city_id, source ) t2 ON t1.city_id = t2.city_id AND t1.source = t2.source AND t1.date = t2.latest_date I realized how to do SELECT MAX(date) AS latest_date, city_id, source FROM api_weather WHERE date<='2019-07-04 15:50' GROUP BY city_id, source with Django ORM, it's Weather.objects.filter(date__lte=datetime.datetime.now()).values('city_id', 'source').annotate(latest_date=Max('date')) but I don't understand how to do INNER JOIN from model Weather to this query. -
pip install mysqlclient installation error in django
when I'm trying to install mysqlclient i faced this problem.How can i fix this error C:\Users\santhoshe.e\loginpro>pip install mysqlclient==1.3.12 Collecting mysqlclient==1.3.12 Downloading https://files.pythonhosted.org/packages/6f/86/bad31f1c1bb0cc99e88ca2adb7cb5c71f7a6540c1bb001480513de76a931/mysqlclient-1.3.12.tar.gz (89kB) |████████████████████████████████| 92kB 590kB/s Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Complete output from command 'c:\users\santhoshe.e\appdata\local\programs\python\python37-32\python.exe' -u -c 'import setuptools, tokenize;file='"'"'C:\Users\SANTHO~1.E\AppData\Local\Temp\pip-install-v3kt5jg5\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\SANTHO~1.E\AppData\Local\Temp\pip-record-fqec09fa\install-record.txt' --single-version-externally-managed --compile: ERROR: running install running build running build_py creating build creating build\lib.win32-3.7 copying _mysql_exceptions.py -> build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building '_mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command "'c:\users\santhoshe.e\appdata\local\programs\python\python37-32\python.exe' -u -c 'import setuptools, tokenize;file='"'"'C:\Users\SANTHO~1.E\AppData\Local\Temp\pip-install-v3kt5jg5\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\SANTHO~1.E\AppData\Local\Temp\pip-record-fqec09fa\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\Users\SANTHO~1.E\AppData\Local\Temp\pip-install-v3kt5jg5\mysqlclient\ -
Django 2.2:App registry error in django.Tried every solution available but none of the methods worked available on the internet.
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. checked all INSTALLED_APPS in settings.py registered models,apps.py. Earlier this error was not coming when i was working with core and users applications under the same project. settings.py """ Django settings for jam project. Generated by 'django-admin startproject' using Django 2.2.1. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'bj))qqcyggizpqmxp9zru$pb%m@bt0--_z%$@z6!xz^$ij3#^@' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition #All applications are working INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'core.apps.CoreConfig', 'users.apps.UsersConfig', 'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'jam.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'jam.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } … -
Django Custom Management Script: Deleting all migrations and database in one single command
I am trying to write a management script for django polling app.. the command should delete all the migrations and pycache, and dbfile so that i can start out again later new with new migrations.... my file is management/commands/removemigrations.py below: from django.core.management.base import BaseCommand, CommandError from polls.models import Question as Poll class Command(BaseCommand): help = 'Delete migrations, pycache, dbfile, and all unwanted file' def add_arguments(self, parser): def handle(self, *args, **options): I am very new in django, can anyone help me to craft this script? I am very new.. Thanks -
Limiting choice to Foreign key
I have a model which had a self relationship Foreign key and a Foreign key, I want to use limit_choices_to = self.parent = parent. But its not working, i tried different things but cant get any to work class State(models.Model): workflow = models.ForeignKey(Workflow, on_delete=models.CASCADE, null=True, blank=True) level = models.IntegerField() name = models.CharField(max_length=100) next_level = models.ForeignKey('flow.State', on_delete=models.CASCADE, related_name='get_next_level', blank=True, null=True, limit_choices_to=(Q(workflow_id=workflow))) return_level = models.ForeignKey('flow.State', on_delete=models.CASCADE, related_name='get_return_level', blank=True, null=True) approver = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) -
How change the password of another user
I'm constructing site by Django. I'm setting some authentications in this site, like Site Manager, Group Manager and Normal User. When System Manager or Group Manager logged in, they could change the password of Normal Users as a part of system management. In django, PasswordChangeForm or SetPasswordForm provide some user password change form. I think these forms are for changing password of users themselves. Yes, I need that too. But I also need the form of changing th password of another users like django admin site. How can I construct the form ? I read the code of django's admin site. I found AdminPasswordChangeForm, can I use this class ? forms.py class MyAdminPasswordChangeForm(AdminPasswordChangeForm): def __init__(self, user, *args, **kwargs): self.user = user super().__init__(user, *args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' views.py class PasswordChange(PasswordChangeView): form_class = MyAdminPasswordChangeForm success_url = reverse_lazy('password_change_done') template_name = 'accounts/password_change/password_admin_change.html' def get(self, request, *args, **kwargs): if 'user_id' in self.request.session: user = User.objects.get(id=self.request.session['user_id']) form_class = self.get_form_class() form = form_class(user=user) return self.render_to_response(self.get_context_data()) def get_form_class(self): return self.form_class -
Uploading video from admin panel [django]
I have a problem in uploading video from admin panel - when i loop video like src='{{uploading.video.url}}' it gives nothing and I have another problem that when I make a form in HTML file and make user upload the video file or any another file [not image] and save it in my database and when I loop it gives me no else enter image description here -
Filter across three tables using django ORM
I have 3 django models, where the second has a foreign key to the first, and the third has a foreign key to the first. Like this: NewRegistration Model class NewRegistration(models.Model): registration_date = models.DateField() ward_no = models.ForeignKey(system_settings.models.Wardno) latitude = models.DecimalField(decimal_places=16, max_digits=30) longitude = models.DecimalField(decimal_places=16, max_digits=30) is_forwarded = models.BooleanField(default=False)` Landowner Model class Landowner(models.Model): lo_address_roadname_en = models.TextField(max_length=100, null=True, blank=True) reg = models.ForeignKey(NewRegistration) Application model class Application(models.Model): building_storey = models.IntegerField(blank=True, null=True, default=0) reg = models.ForeignKey(NewRegistration) I want to count the data of application table on the basis of no_of_storey having certain lo_address_roadname_en from Landowner model and certain ward_no from NewRegistration Model and having certain registration_date from NewRegistration Model I have tried like this. building_storey = Application.objects.filter(reg__ward_no=ward_no).filter(reg__registration_date__gte=start_date,reg__registration_date__lte=end_date).values('building_storey').annotate(Count('building_storey')) context['building_storey'] = building_storey How can i filter from three tables? Please help me. -
nginx serving from html instead of gunicorn
I have a nginx / gunicorn / django app I've set up following https://medium.com/@_christopher/deploying-my-django-app-to-a-real-server-part-ii-f0c277c338f4 It works when I go to the main IP from the browser (I got Django tried these URL patterns, in this order: admin/...) but when I go to /admin I got a 404. Nginx logs are as follows: 2019/07/05 00:30:28 [error] 13600#13600: *1 open() "/usr/share/nginx/html/admin" failed (2: No such file or directory), client: 186.190.207.228, server: 127.0.0.1, request: "GET /admin HTTP/1.1", host: "128.199.62.118" So it is trying to serve files from html/ instead of serving gunicorn, why? Nginx config: server { listen 80; server_name 127.0.0.1; location = /favicon.ico {access_log off;log_not_found off;} location = /static/ { root /home/juan/site; } location = /media/ { root /home/juan/site; } location = / { include proxy_params; proxy_pass http://unix:/home/juan/site/site.sock; } } -
How to order a list of objects containing longitude and latitude by distance? [duplicate]
This question already has an answer here: Haversine Formula in Python (Bearing and Distance between two GPS points) 10 answers I have a list of objects that contain the following properties: latitude, longitude. Given an origin location, how can I sort this list based on their distance to this given origin location? -
Django: pycharm: unversioned files
When I did 'makemigrations' on 'django', the generated file became 'unversioned files'. I don't know why. How can I turn into versioned files these unversioned one?