Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Checkout form not getting saved
Hi I'm trying to develop an e-commerce site with Django. So I'm at this point where, users can add items to their cart, proceed to checkout but for some reason, my checkout form is not being saved. I made sure that I have registered my models, and ran migrations, but everytime I fill out my form and go to check in my admin panel, it says: 0 user addresses. What is the problem? Can anyone please help me out? My views.py: @login_required() def checkout(request): address_form = UserAddressForm(request.POST or None) if address_form.is_valid(): new_address = address_form.save(commit= False) new_address.user = request.user new_address.save() context = {"address_form": address_form} template = "orders/checkout.html" return render(request, template, context) My checkout.html: <form method="POST" action="{% url 'ajax_add_user_address' %}?redirect=checkout"> {% csrf_token %} <fieldset class="form-group"> {{ address_form|crispy }} </fieldset> <div class="form-group"> <input type="submit" class="btn btn-outline-dark" value="Place Order"/> </div> </form> -
Convert JSON to SQLite having geoJSON content
Need help to prepare model for this dataset for SQLite using Python Django { "countryName": "India", "countryCode": "IND", "airportName": "Vishakhapatnam", "cityName": "Vishakhapatnam", "latitude": 17.722166666666666, "longitude": 83.22277777777778, "airportCode": "VOVZ", "geometry": { "type": "Point", "coordinates": [ 83.22277777777778, 17.722166666666666 ] } } -
No module named 'south'
The scenario is I am upgrading the Django projet. previous version:- Django 1.8 Python 2.7 Tastypie 0.13.0 Now the upgraded version is:- Django 2.2 Python 3.5.2 Tastypie 0.14.3 I have changed all syntax and converted it into python 3 using python convertor 2to3. Now while upgrading the structure of Django, it is raising an error. from south.db import db ImportError: No module named 'south' -
What is the best architecture to integrate AngularJS with Django?
I am trying to integrate Angular with Django. I have 2 approaches which one is the best way: Build a separate angular app and serve it's static files to django to render. In this way the routing and rendering everything will be handled by Angular. Or to build templates in django using Angular directly and use MVT architecture of Django only. Which is the correct way from architecture point of view? If not these two please suggest any good approach. -
How can I use argparse to parse a mutual exclusive argument group with defaults, so that only one of the arguments get a default value?
I have the below mutual exclusive argument group (group), where I want the default to be args.thread=10 and args.process=None, if neither --thread or --process is specified. Furhermore, if --thread or --process is specified, the other should be set to None. With my current code, the result is always args={ ..., 'thread': 10, 'process': 10, ... }. How can I fix my code to get the anticipated behavior? fmt = lambda prog: argparse.HelpFormatter(prog, width=140) p = argparse.ArgumentParser(description='Atlassian Watchdog: Search through all resources on Confluence, Bitbucket, or Jira looking for secrets.', formatter_class=fmt) group = p.add_argument_group('Concurrency') group = group.add_mutually_exclusive_group() group.add_argument('-t', '--thread', type=int, default=10, metavar='N', dest='thread', help='number of threads (default: %(default)s)') group.add_argument('-p', '--process', type=int, default=10, metavar='N', dest='process', help='number of subprocesses (default: %(default)s)') -
Django Subquery Average Employee Salary Per Company
I was looking for a better way using Subquery annotate and Avg but couldn't figure it out. This is what i have at the moment and it works giving me the average number of employees per company but it's ugly. companies = Company.objects.all() for company in companies: salary = [] for emp in company.comp_emp.all(): salary.append(emp.salary) print(sum(salary) / len(salary)) >>> 99054.4 >>> 96403.75 >>> 498351.375 I tried the following but no go, companies = Employee.objects.filter(company=OuterRef('pk')) employee_count = Company.objects.annotate(avg_emp_salary=Avg(Subquery(companies.values('salary')[:]))) >>> 46907.0 >>> 147288.0 >>> 43158.0 The values I get back are incorrect but I also can't make sense of where they're coming from either. This is just for my own learning purposes. Thanks in advance. -
How to disable use of website on mobile devices
Display an error page if website is accessed through mobile. I have already tried @media only screen (max-device-width : 768px) { html,body { display: none; } } and if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) { getElementById('body').style.display = 'none'; } -
context_processors.py: files path?
I have a context_processors.py files in one of my app that I declared in my settings.py and it works. but, as context_processors.py files's data are common to all the project, I would like to declare it at the root of my project but files is not recognized... current project's architecture - myproject - my app - context_processors.py declared as follow in settings.py : TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR,'registration/templates'), os.path.join(BASE_DIR,'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'parameters.context_processors.data_context_processor', <******************** 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] expected project's architecture - myproject - context_processors.py - my app How should I declare my context_processors.py files in settings.py? I try with os.path.join(BASE_DIR,'context_processors.data_context_processor') but it does not works... -
Django TemplateDoesNotExist (Root arrangement)
I had tried many times, and lastly I have solved this, but I can't understand why the root page need to be arrange like this? Learning_log = Project name ll_env = virtual env project01 = project name App01 = app name https://i.stack.imgur.com/zoSm1.png -
How to synchronously add files in a queue?
It's a bit hard to explain my problem but I try to, sorry in advance I have a Django server running which utilizes files in a directory /PROCESSING_DOCS/*.json An API call dynamically adds more files to this folder and now I need to maintain a queue which updates dynamically as the files added into that folder. How can I implement this? I don't have any idea? -
What happens in background when we pass the command python manage.py createsuperuser in Django?
I'm working on Django and I know to create a account to log in into admin page I have to create a superuser.And for that we have to pass the command python manage.py createsuperuser. But my question is when we pass this command what happens first and because of what in the background and after that what happens?? Which all methods and classes are called to create a superuser?? I know its a weird question but I wanted to know how this mechanism works.. Thanks in advance!! -
'AnonymousUser' object has no attribute '_meta' error when login in my user model form
I am getting 'AnonymousUser' object has no attribute '_meta' error when using get_user_model. Here are my form.py and view files be: this is forms.py file class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput()) def clean_username(self): username = self.cleaned_data.get('username') try: user = User.objects.get(username=username) except User.DoesNotExist: raise forms.ValidationError('Are you sure you are registered? we can not find this user.') return username def clean_password(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') try: user = User.objects.get(username=username) except: user = None if user is not None and not user.check_password(password): raise forms.ValidationError('Invalid password') elif user is None: pass else: password this is views.py file def login_view(request): form = LoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) login(request, user) context = { 'form':form } return render(request, 'form.html', context) -
javascript is not loading in django template....or its not working in django
this is my html page where am loading js file <!DOCTYPE html> {% load static %} <html lang="en"> <head> <title></title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'css/grid.css' %}" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'main/post.css' %}"> <script type="text/javascript" src="{% static 'js/bootstrap.min.js' %}"></script> <script type="text/javascript" src="{% static 'js/post.js' %}"></script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script> </head> and this is my js file in static/js/post.js $(".sidebar-dropdown > a").click(function() { $(".sidebar-submenu").slideUp(200); if ( $(this) .parent() .hasClass("active") ) { $(".sidebar-dropdown").removeClass("active"); $(this) .parent() .removeClass("active"); } else { $(".sidebar-dropdown").removeClass("active"); $(this) .next(".sidebar-submenu") .slideDown(200); $(this) .parent() .addClass("active"); } }); $("#close-sidebar").click(function() { $(".page-wrapper").removeClass("toggled"); }); $("#show-sidebar").click(function() { $(".page-wrapper").addClass("toggled"); }); what should i do...am not facing any error but its not working ...is there any kind of inheriting problem ? -
how to solve MySQL server has gone with query
What is error in this code ? it is giving error "Failed inserting BLOB data into MySQL table 2006 (HY000): MySQL server has gone away" def insertBLOB(request): id =(1) name=("Eric") photo = ("/home/gauri/Pictures/w3schools.jpg") biodata = ("/home/gauri/Downloads/mnum.npy") try: connection = mysql.connector.connect(host="127.0.0.1", user="root", passwd="", port=3307, db="data2") cursor = connection.cursor() sql_insert_blob_query = "INSERT INTO python_employee(id, name, photo, biodata) VALUES (%s,%s,%s,%s)" with open(photo, 'rb') as file: binaryData = file.read() with open(biodata, 'rb') as file: binaryData1 = file.read() insert_blob_tuple = (id, name, binaryData, binaryData1,) result = cursor.execute(sql_insert_blob_query,insert_blob_tuple) connection.commit() print("Image and file inserted successfully as a BLOB into python_employee table",result) except mysql.connector.Error as error: print("Failed inserting BLOB data into MySQL table {}".format(error)) return HttpResponse("data") -
How to get the slug from url () and use it to get the object? : Django
I just need to get the movie_slug and use it to get the movie object. And then make it like: context["show"] = [movie] I encountered a problem. I want to use images in the movie to be shown on slides. So I need to get movie_slug and use it to get the movie object so I can get the images to show. The problem is that the images in the movie are on different apps that I use to show on slides. And I don't know what I need to do in order to get movie_slug and use it to get the movie object. models.py in a movie app class Movie(models.Model): name = models.CharField(max_length=255) slug = AutoSlugField(populate_from=["name"]) image= models.ImageField(blank=True) cropping = ImageRatioField("image", "700x500") slider.html <div id="slide"> <ul class="slides"> {% for slide in slides %} <li> <img src="{% cropped_thumbnail slide "cropping" %}"> </li> {% endfor %} </ul> </div> show_list.html in show app {% include "slides.html" with slides=show %} # show comes from context in ShowListView in show_views.py # urls.py in show app urlpatterns = [ .... path( "movie/<str:movie_slug>/show/", ShowListView.as_view(), name="movie_list",), .... ] models.py in show app class Show(TitleSlugDescriptionModel): date = models.DateField() movie = models.ForeignKey("darma.movie", null=True, on_delete=models.SET_NULL) show_views.py in show app class … -
wagtail main search add modelAdmin models
Quick question on wagtail's main search at the top of the left sidebar beneath the logo. By default that search box searches pages, images, documents, users. Two questions: Is there a way to modify that search scope so it also includes modelAdmin models? Is there a way to remove pages from the search query list so it only searches images, documents, users? I can't seem to find anything in the docs about it. I know you can search modelAdmin models once on the model admin list view, I have that working. I was just looking for a way to extend that search to be included on the main sidebar search as well. Any direction you can provide would be much appreciated. -
MultiValueDictKeyError Request Method: GET (Django)
I have recently started to learn and work on Django i came across this error multiple times sometimes it was due to repetitive use of a name in an html and sometimes it was due the part for example "variable_name=request.POST['variable_name']" I visited various sites regarding this error and was able to find a solution i.e, once i have typed in "variable_name=request.POST['variable_name']" in a function in views.py the next time i tried to POST the data again "variable_name=request.POST['variable_name']" I had to do something like this "variable_name=request.POST.get('variable-name', 'blank_or_whatever_canBeFalseAlso') The Above statement helped me solve that error I got this solution from A Thread in StackOverflow itself Quite a useful site. Now for the Question am just Curious to know whats the difference between Variable_Name=request.POST['Variable_Name'] Variable_Name=request.POST.get('Variable_Name','Whatever') Code (views.py) Is given Below: from django.shortcuts import render from . import views from datetime import date from .models import Batch, Deleted_Batch from django.utils.datastructures import MultiValueDictKeyError # Create your views here. today = date.today() Date_Batch = str(today.day)+'/'+str(today.month)+'/'+str(today.year) def Reg_Batch(request): return render(request, 'Reg_Batch.html',{'Date_Batch':Date_Batch}) def Reg_Batch_Receive(request): Region_Code=request.POST['Region_Code'] Branch_Code=request.POST['Branch_Code'] Batch_Number=request.POST['Batch_Number'] Farm_Code=request.POST['Farm_Code'] Farm_Status=request.POST['Farm_Status'] Farmer_Name=request.POST['Farmer_Name'] Farmer_Address=request.POST['Farmer_Address'] Farmer_Phone_Number=request.POST['Farmer_Phone_Number'] Farmer_Email=request.POST['Farmer_Email'] return render(request, 'Reg_Batch_Receive.html') def Reg_Batch_View(request): Region_Code=request.POST.get('Region_Code', 'Blank') Branch_Code=request.POST.get('Branch_Code', 'Blank') Farm_Code=request.POST.get('Farm_Code', 'Blank') Farm_Status=request.POST.get('Farm_Status', 'Blank') return render(request, 'Reg_Batch_View.html',{'Region_Code':Region_Code,'Branch_Code':Branch_Code,'Farm_Code':Farm_Code,'Farm_Status':Farm_Status}) def Reg_Batch_View_Receive(request): Date_Batch= '20/08/2000' Region_Code='586001' Branch_Code='586001' Batch_Number='586001' Farm_Code='5484712' … -
How to Build a Django Chained Dropdown ModelForm
I'm building an accounting app for my project, The app contains two models 1. Account and 2. Transaction The Transaction, in turn, contains the reference to other models in the project to help us identify the association. Please refer to the image attached for flow. The challenge I'm facing is keeping the whole process confined to a single transaction model and a single form. Is there a way to structure the model in such a way? Vehicle, Driver, Customer, and Booking are other models in the project, which will need relationship with transactions. -
Password hashing algorithm in Django [closed]
I have copied data from one model(Model-Maintab) to user_auth table (table for authentication), they have the same fields so appending data is not an issue. When storing in Maintab, I have used the pbkdf2_sha256.... algorithm which stores password in the backend in the format: $pbkdf2....., but when storing this data in auth_user table, this password format is not recognized. The auth_user table stores password in the format: pbkdf2_sha256....(without the '$' sign in front). The password hashing algorithm is same, so why does auth_user not consider my appended password, or what can I provide as a solution? -
Howo to solve my below issue , celery production setup error
Hi I'm trying to setup django and celery in production. Here is the my /etc/conf.d/celery file. CELERYD_NODES="w1" CELERY_BIN="/home/.../env/bin/celery" CELERY_APP="projectname" # How to call manage.py CELERYD_MULTI="multi" # Extra command-line arguments to the worker CELERYD_OPTS="--time-limit=300 --concurrency=8" # - %n will be replaced with the first part of the nodename. # - %I will be replaced with the current child process index # and is important when using the prefork pool to avoid race conditions. CELERYD_PID_FILE="/var/run/balu/%n.pid" CELERYD_LOG_FILE="/var/log/balu/%n%I.log" CELERYD_LOG_LEVEL="INFO" Here is the my celery.service file [Unit] Description=Celery Service After=network.target [Service] Type=forking User=balu Group=balu EnvironmentFile=/etc/conf.d/celery WorkingDirectory=/home/.../projecttitle ExecStart=/bin/sh -c '${CELERY_BIN} multi start ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait ${CELERYD_NODES} \ --pidfile=${CELERYD_PID_FILE}' ExecReload=/bin/sh -c '${CELERY_BIN} multi restart ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' [Install] WantedBy=multi-user.target I have restarted sudo systemctl daemon-reload and when i'm trying to start celery I'm getting an error like this. Job for celery.service failed because the control process exited with error code. See "systemctl status celery.service" and "journalctl -xe" for details. Here is the complete list of error status ● celery.service - Celery Service Loaded: loaded (/etc/systemd/system/celery.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Tue 2020-04-21 10:13:02 IST; 10s ago … -
How to transfer your local sqlite3 data to heroku?
I made a django which works perfect,I then tried to deploy it to heroku.Everything is great but my local data.My development db was sqlite3 than I configured heroku database url in there.The data that was stored in my sqlite3.How can I transfer local data to my heroku app which uses postgres. Please can you walk me through! Here's my django database settings The database url is the heroku postgres url DATABASES = { 'default':dj_database_url.config( default=env('DATABASE_URL') ) } -
Redirect to your custom page after login- Django
Whenever I login from the Django admin site, It redirects me to the Admin Site of the django. Whereas, I want to redirect to my own custom page. How It's done? Thanks -
Django settings file not found no matter what
I searched deep and wide, but no solution has worked so far. I'm trying this with Django 1.6 in my virtual environment. In my manage.py file I have the following line: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproj.settings") With this, when I execute python ./manage.py runserver I get the traceback: Traceback (most recent call last): File "./manage.py", line 9, in <module> execute_from_command_line(sys.argv) File "/home/int/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 453, in execute_from_command_line utility.execute() File "/home/int/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/int/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 263, in fetch_command app_name = get_commands()[subcommand] File "/home/int/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 109, in get_commands apps = settings.INSTALLED_APPS File "/home/int/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/home/int/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in _setup self._wrapped = Settings(settings_module) File "/home/int/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 134, in __init__ raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e)) ImportError: Could not import settings 'myproj.settings' (Is it on sys.path?): cannot import name current_app Then I added sys.path.insert(0, '/home/int/Documents/myproj/myproj'), where the modules are to my manage.py file and got the same traceback as above. If I try relative import, i.e. changing that line in manage.py to os.environ.setdefault("DJANGO_SETTINGS_MODULE", ".myproj.settings") I get the error TypeError: relative imports require the 'package' argument The file settings.py is definitely in /home/int/Documents/myproj/myproj (triple-checked). So I don't know how to solve this … -
Mapping/connect issue on publishing Django website
Apologise but, I'm clueless on what to do. My boss bought this Namecheap domain, set web-app (example) "www.Monday.com" Now he asks me to set another web-app "www.Monday.com/ABC" with the Django framework. I did the following instruction given by Namecheap: https://www.namecheap.com/support/knowledgebase/article.aspx/10048/2182/how-to-work-with-python-app and did the setup on Django: https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ run ping check on DNS working run this webpage www.Monday.com/ABC(exmple) result: 404 that lead me to the clueless predicament; I don't even know where I could map wrongly or even to start to debug mapping issue If you could help I really appreciate it -
Django using include() as path() argument
I'm learning Django. In the tutorial it says: The path() function is passed four arguments, two required: route and view, and two optional: kwargs, and name. At this point, it’s worth reviewing what these arguments are for. path() argument: view When Django finds a matching pattern, it calls the specified view function with an HttpRequest object as the first argument and any “captured” values from the route as keyword arguments. We’ll give an example of this in a bit. In my opinion, the view is a function that takes a HttpRequest as argument and returns a HttpResponse. but in mysite/urls.py the path() is used like this path("polls/", include("polls.urls")), and the inclue method returns a tuple (urlconf_module, app_name, namespace), not a function. Why can include() be used here? I'll appreciate it if someone could help.