Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
union of django querysets duplicates item
I'm creating a union of QuerySets and something doesn't add up. For some reason, one element gets duplicated. I'm printing: print(len(one), len(two), len(one | two), len((one | two).distinct())) I get: 8 42 51 50 How is that possible!? -
NoReverseMatch at /accounts/login/ Dajngo 3.0
I get the this error while developing my django 3.0 app, but only when I try to login with the superuser. NoReverseMatch at /accounts/login/ Reverse for 'home' not found. 'home' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 3.0 Exception Type: NoReverseMatch Exception Value: Reverse for 'home' not found. 'home' is not a valid view function or pattern name. Exception Location: /Users/project/ven/lib/python3.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 676 Python Executable: /Users/project/ven/bin/python Python Version: 3.7.1 I have looked up these answers but they did not solved my question: NoReverseMatch at /account/login/ django-registration - NoReverseMatch at /accounts/login/at /accounts/login/ -
How can one securely deploy a django app on-premise?
As the title says, I'm building a python web app (django inside docker + postgresql docker) for a company that I deployed on their server. Now one of their clients asks them if they can run it on his own server (for data privacy issues). So the company asks if it's possible to do that without giving him access to the source code? The problem being that python code is not compiled and is plain text that anyone can read. Is there any solution to this ? Thank you ! -
How do I migrate in Heroku?
so I have a Django application and completed all the deployment with Heroku. However I realized that all the data from my database weren't migrated. When I go into /admin in my heroku application, I do see the models are there, but empty. I've done the heroku run python manage.py migrate command, but it got me an error that says: bash: manage.py: command not found. What is the problem? -
How to solve filer and sites dependencies problem in my project
Currently I have started working on Django project given by me for learning purpose. I have done all kind of necessary setup in my virtualenv and when running migrate command on my project I am getting below kind of dependencies problems as below. I have tried to find solution online and django doc but clueless. Traceback Traceback (most recent call last): File "manage.py", line 40, in <module> execute_from_command_line(sys.argv) File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 89, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/db/migrations/loader.py", line 306, in build_graph _reraise_missing_dependency(migration, parent, e) File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/db/migrations/loader.py", line 276, in _reraise_missing_dependency raise exc File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/db/migrations/loader.py", line 302, in build_graph self.graph.add_dependency(migration, key, parent) File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/db/migrations/graph.py", line 126, in add_dependency parent django.db.migrations.exceptions.NodeNotFoundError: Migration core.0002_auto_20200408_0215 dependencies reference nonexistent parent node ('filer', '0008_auto_20200408_0215') Snippet from migration file as below. 0002_auto_20200408_0215.py class Migration(migrations.Migration): dependencies = [ ('filer', '0008_auto_20200408_0215'), ('sites', '0003_auto_20200408_0215'), ('core', '0001_initial'), ] I have thought to comment dependencies lines from 0002_auto_20200408_0215.py files but my … -
Question regarding Form, View and dynamic queryset
Hey guys I have a question regarding form and queryset: Im creating a form where I select a faction from a list of factions. After the form is created, im redirect to another form where I can add soldiers to this list, but I see every soldiers of every factions in this form, I would like to be able to see ONLY soldiers of the faction I selected on the previous form. Can you help please on this please ? Im a bit lost on what to search for... My models: class Faction(models.Model): title = models.CharField(max_length=30) picture = models.FileField(blank=True,) race = models.ForeignKey(Race, on_delete=models.CASCADE,default=None, blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("home") class List(models.Model): faction = models.ForeignKey(Faction, on_delete=models.CASCADE) title = models.CharField(max_length=30) format_points = models.IntegerField() description = models.CharField(max_length=30) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse("home") class Soldier(models.Model): title = models.CharField(max_length=30) picture = models.FileField(blank=True,) points = models.IntegerField() factions = models.ManyToManyField(Faction) def __str__(self): return self.title class SoldierToList(models.Model): soldier = models.ForeignKey(Soldier, on_delete=models.CASCADE,) list = models.ForeignKey(List, on_delete=models.CASCADE,) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) My views: class ListCreateFormView(CreateView): template_name = 'armybuilder_list_create.html' model = List form_class = CreateListForm def form_valid(self, form): form.instance.author = self.request.user form.instance.race = "toto" return super().form_valid(form) … -
How to test my business logic using Django and DRF without creating additional models that are used as references
I want to make bug-less code. I do the registration for applicants and application form that is divided by 3 blocks - personal data, application statement and admission documents. For each step there are additional requirements, for example if applicant didn't fill up personal info questionnaire the status of his application should "Without personal data" else "Awaits verification", on registration if applicant graduated school and wants to apply to Bachelor degree I have to check if there are admission campaign with bachelor preparation level and registration opened from 1 June til 1 July. If applicant applies earlier or later that period of time etc. The application forms are big and there should be some pre-populated data that applications refer to. This is how my test module looks like: import json import datetime as dt from rest_framework.test import APITestCase from organizations.models import Organization from portal_users.models import PhoneType from .models import * class ApplicantTestCase(APITestCase): # OBJ_RANGE - how many objects (records) to create (store at test DB) OBJ_RANGE = range(1, 7) # some refs must have dates and periods today = f'{dt.date.today()}' period = f'{dt.date.today() + dt.timedelta(days=365)}' def setup_refs(self): # Setting up reference models for questionnaire and application # in create_or_update there … -
Add a formatter (beautifier) to django-html files in Visual Studio Code
I'm using the Django extension for intellisense and syntax highlighting on Jinja templates (VS Code) but cannot figure out how to use my default formatter (HookyQR Beautify) to beautify/format my django-html files. Would that be possible? -
How can i run Django channels on production?
I deployed a simple Django app to a VPS, here is my environment: virtualenv gunicorn nginx systemd Everything works perfectly, i can see my template loading. I also added a small Django Channels feature, but that part doesn't work; so while i can use it on WSGI without any problem, if i try to reach a Consumer, i will get an error. So my question is: how can i run Channels too in production? Here is what i currently did: /etc/nginx/sites-available/myproject server { listen 80; server_name 54.39.20.155; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /WaitingRoomVenv/WaitingRoom/WaitingRoom/static; } location / { include proxy_params; proxy_pass http://unix:/WaitingRoomVenv/WaitingRoomEnv.sock; } } /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/WaitingRoomVenv/WaitingRoom ExecStart=/WaitingRoomVenv/WaitingRoomEnv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/WaitingRoomVenv/WaitingRoomEnv.sock WR.wsgi:application [Install] WantedBy=multi-user.target To start gunicorn: sudo systemctl start gunicorn To start nginx: sudo systemctl restart nginx -
Add argument to all views without having to edit them all to include variable in Django
What I need I'm developing a Pull Notification System to an existing Django Project. With there begin over 100+ views I'm looking to find a way to incorporate a argument(notification queryset) into all the views, as this is rendered to my base.html which I can do by passing it into a view's arguments dictionary. Problem I want to do this without editing all of the views as this would take a long time and would be required for all future views to include this variable. What I've tried Creating a template filter and pass in request.user as variable to return notification for that user. This works, however when the user selects a 'New' notification I want to send a signal back to the server to both redirect them to the notification link and change the status of viewed to 'True' (POST or AJAX). Which would required that specific view to know how to handle that particular request. What I've considered • Editing the very core 'View' in Django. I've tried my best to explain the issue, but if further info is required feel free to ask. Thanks! -
TinyMCE GET 404
I installed TinyMCE and it was working fine on the local server. I deploy the site to Heroku and host the static files on Amazon S3 and now TinyMCE is not working. Other static files are served correctly. This is the Heroku log. 2020-04-15T07:19:17.547578+00:00 app[web.1]: - [15/Apr/2020:07:19:17 +0000] "GET /static/tiny_mce/tiny_mce.js HTTP/1.1" 404 3012 "https://...herokuapp.com/.../" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.39 Safari/537.36" This is the folder structure of my site: . ├── Procfile ├── db.sqlite3 ├── mysite │ ├── __init__.py │ ├── __pycache__ │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── media │ ├── images │ └── js ├── requirements.txt ├── runtime.txt ├── static │ └── readme.txt ├── staticfiles │ └── readme.txt └── myapp ├── __init__.py ├── __pycache__ ├── admin.py ├── apps.py ├── forms.py ├── migrations ├── models.py ├── static └── myapp └── tiny_mce ├── templates ├── tests.py ├── urls.py └── views.py This is my URL configs: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') TINYMCE_JS_URL = os.path.join(STATIC_URL, "tiny_mce/tiny_mce.js") TINYMCE_JS_ROOT = os.path.join(STATIC_URL, "tiny_mce") TINYMCE_DEFAULT_CONFIG = { 'theme': 'advanced', 'relative_urls': False, 'theme_advanced_buttons1': 'bold,italic,underline,bullist,numlist,link,unlink,styleselect,fontselect,fontsizeselect', } Any ideas? Thank you! -
Control object creation flow in Django inheritance models
I have been read some Django document about inheritance models and parent_link. Suppose that I have these models: class Parent(models.Model): #Some field goes here! class Child(Parent): #Some field goes here! I have 3 questions about this pattern: What should I do if I want to create new child object and pass id of existing parent to that? What should I do if I want to create just new child object and after a while create parent object for that child? Also I din't understand this document about parent_link: OneToOneField.parent_link When True and used in a model which inherits from another concrete model, indicates that this field should be used as the link back to the parent class, rather than the extra OneToOneField which would normally be implicitly created by subclassing. Thanks for your help! -
I'm trying to save django form in json format in mongodb without using models & model forms. My form is working, but I am stuck how to save the form
I want to save the form data submitted by the user in JSON format in mongo database. My form is getting submitted when I submit the form but I couldn't understand how to store the submitted form in MongoDB JSON format. Kindly do help with the supporting code. forms.py class appointment(forms.Form): name = forms.CharField(max_length=100, label="Name") gender = forms.ChoiceField(widget=forms.RadioSelect, choices=G_CHOICES) age = forms.CharField() phone_number = forms.CharField() email_id = forms.EmailField(max_length=250) country = CountryField().formfield() department = forms.ChoiceField(choices=D_CHOICES) reports = forms.ImageField() views.py def appointmentform(request): if request.method == "POST": form = appointment(request.POST, request.FILES) if form.is_valid(): form.save() print(form.cleaned_data) print(form.cleaned_data.get("name")) print(form.cleaned_data.get("gender")) print(form.cleaned_data.get("age")) print(form.cleaned_data.get("phone_number")) print(form.cleaned_data.get("country")) print(form.cleaned_data.get("department")) print(form.cleaned_data.get("reports")) form = appointment return render(request, "appointment.html", {"form": form}) -
Perform JOIN in tables django
Perform JOIN on in django fetching related date in reverse relationship. There are three models. Following is code for models class Question(models.Model): title = models.CharField(max_length=255 ) description = models.TextField(max_length=300) class Quiz(models.Model): name = models.CharField(max_length=225,blank=False ) quiz_type =models.IntegerField(choices=QUIZ_TYPE,default=0) questions = models.ManyToManyField( Question, through='QuestionQuiz', related_name="quiz_question") categories= models.ManyToManyField(Category,through='CategoryQuiz',related_name='quiz_category') class QuestionQuiz(models.Model): quiz = models.ForeignKey(Quiz,on_delete=models.CASCADE) question = models.ForeignKey(Question,on_delete=models.CASCADE) correct =models.DecimalField(max_digits=4, decimal_places=3) incorrect= models.DecimalField(max_digits=4, decimal_places=3) class Meta: unique_together = ('quiz','question') In this the questions are added to the quiz using model Question Quiz. Here , QuizQuestion has foreign key relationship with the question. I need to fetch all from question JOIN and records from QuestionQuiz with a particular quiz_id. Suppose quiz_id =3 Then I will fetch all questions with correct and incorrect. if that quiz id is added to the question then it will display correct incorrect else these would be blank. question_id | title|description|correct|incorrect|quesquizid 1 | Q1 |Q1desc |2 | -2 | 1 2 | Q2 |Q2desc | | | ques_id =1 added to quiz_id=3 .ques_id=2 not added to quiz_id=3.So, correct incorrect are blank. I tried following but it fetches all question and related quizes scores irrespective of their occurrence in current quiz : Question.objects.prefetch_related('questionquiz_set').all() The result should be similar to following query Select * … -
how to send data in GET request header using react and axios to Django rest framework?
i am new to react and axios and i want to know how to send data in my headers using get request i tried this but it didn't work ** i observed that the request type changed to options in django terminal window ** export const getUserOrders=(userID)=>{ return dispatch=>{ dispatch(getUserOrdersStart()) axios.defaults.headers={ 'Content-Type':'application/json', id:userID } axios.get('http://127.0.0.1:8000/admindashboard/userorders/') .then(res=>{ const order=res.data dispatch(getUserOrdersSuccess(order)) }).catch(err=>{ getUserOrdersFail(err) }) } } -
ERD Diagram for a school management system automatically generated using postgresql as my dbms
I'm currently building a school management system with modules that include: admin, students, parents, teachers and fees management. I am using django for my back-end development for my app. I've already created these models on my models.py file in my app and configured my postgresql into my settings.py file. How can i generate an automatic ERD Diagram without having to draw it myself? -
Can I use NGINX to proxy_pass to Django project's WSGI server
I have deployed the Django on Amazon AWS EC2 services. It is woking fine when I use proxy_pass except it does not return errors and message which are being returned on Postman. I am getting only following error. Access to XMLHttpRequest at 'http://ec2-18-191-33-108.us-east-2.compute.amazonaws.com/api/token/' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. How to retreive all 4** and 5** errors and messages from NGINX which is serving as reverse proxy. my nginx.conf location / { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PATCH, PUT, DELETE'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PATCH, PUT, DELETE'; # # Custom headers and headers various browsers *should* be OK with but aren't # add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; # # Tell client that this pre-flight info is valid for 20 days # add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } proxy_pass http://app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } -
Create virtual wallet in Django
I have a plan to develop betting app in Django , I haven't an idea how to make virtual wallet , like on Upwork or Freelancer.com , Can I make it with Stripe ? Is there any solutions ? -
Can I use JWTAuthentication twice for a login authentication?
In my login First place I wanted to send OTP and second place I wanted to verify the OTP and then return the token. I am using rest_framework_simplejwt JWTAuthentication. First place I just verifying the user and sending OTP, not returning the token and second place I am verifying the OTP and returning the token. Let me know I this is the correct way to use? If not how can I implement this using JWTAuthentication. -
Do I need to know Postgres if I want to use it in Django?
I have been developing backend for like 8 months and have done quite a few big projects, but in all of them I used sqlite database. I understand that using sqlite at production level is a bad idea. hence I want to use a Postgres database since I deploy my apps at heroku and it uses Postgres database. But if I do start using Postgres do I need to be able to use it, or would everything work just as the ORM would work with the sqlite database? I just know the basics of database, their relations and some basic SQL. Do I really need to learn more? Or should I just plug n play a database? -
how can i use different bootstrap version in template inheritance? - Django
base.html '''' <head> {% block csslink %}<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">{% endblock csslink %} {% block cssfile %} {% endblock cssfile %} <title>{% block title %} Base {% endblock title %}</title> </head> <body> {% include 'navbar.html' %} <br> {% block content %} {% endblock %} </body> Contact.html '''' {% extends 'base.html' %} {% load static %} {% block csslink %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> {% endblock csslink %} {% block cssfile %}<link rel="stylesheet" type="text/css" href="{% static 'css/contactstyle.css' %}"> {% endblock cssfile %} {% block title %}Contact {% endblock title %} {% block content %} Any one suggest how can add this versions without changing styles? -
This field cannot be blank django Testing
In my models (Home), there are fields as follows. class Home(TitleSlugDescriptionModel): seller= models.ForeignKey("data.seller", null=True, on_delete=models.SET_NULL) date = models.DateField() picture = models.ImageField(upload_to="images") data.seller Different model Home. I have models.py (Data) class Data(models.Model): name = models.CharField(max_length=255) images = models.ImageField() class Seller(models.Model): name = models.CharField(max_length=255) data= models.ForeignKey(Data, on_delete=models.SET_NULL, null=True) In my test.py class HomeTestCase(TestCase): def test_random(self): with open("img/no-image.jpg", "rb") as f: for home in range(10): G(Home, picture=ImageFile(f), seller=F(name="test1"), I have a problem when I test. It alerts that: django_dynamic_fixture.ddf.InvalidConfigurationError: ('homes.models.Home.seller', BadDataError('data.models.Seller', ValidationError({'data': ['This field cannot be blank.']}))) I don't know how to fix it. Can someone recommend me? Thank you very much -
Angle Brackets in JSON
I am following the solution posted on: Sum database on location and time However, when I do a print(locations.values()) this is returned: ('Liberty City', <Location: 07:00 116 Liberty City 08:00 120 Liberty City ...>)]) models.py class Location: def __init__(self, name): self.name = name self.times = list() def __str__(self): s = ['{}\t{}\t{}'.format(k, t[k], self.name) for t in self.times for k in t.keys()] return '\n'.join(s) def add_time(self, hour, people): existing_people_for_hour = None for t in self.times: # loop existing times, looking for the hour existing_people_for_hour = t.get(hour) if existing_people_for_hour is not None: t[hour] += people break # found the hour to update, so break the loop if existing_people_for_hour is None: # if the hour was never found, add to the times list self.times.append({hour : people}) Things I've tried: print(repr(locations.values())) However, this still gives me angle brackets. What does the angle brackets (<>) means? And how can I access the values? -
Unable to setup celery-progress in Django
I'm trying to setup a celery-progress as per an answer to an old stackoverflow question. I'm following the documentation of enter link description here. I also tried to configure the sample project linked in documentation. But failed, as it requires Redis server setup, which is again a new thing for me. Can anybody help me find a simple working example? And please, don't close this question as a duplicate, as the existing questions are older and didn't resolve my problem. -
When I edit a single record into a template by use django form it is not edited
I have two models child and academy by which these two models have relationship to each other here is child models from django.db import models class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) Tribe = models.CharField(max_length = 50) def __str__(self): return self.Firstname Here is academy model from django.db import models from child.models import Child_detail class Academic(models.Model): Student_name = models.ForeignKey(Child_detail,on_delete = models.CASCADE) Class = models.CharField(max_length = 50) Average_grade = models.CharField(max_length = 10) def __str__(self): return str(self.Student_name) Here is my views.py file that contain edit functionality,into the template it does not show the fields to edit so i have to write those fields again and even that it does not edit anything def edit(request,pk): child=get_object_or_404(Child_detail,pk=pk) form=ChildForm(request.POST or None,instance=child) if form.is_valid(): form.save() return redirect('child') context={ 'form':form, 'child':child } return render(request,'functionality/edit.html',context)