Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best approach to deploy nextjs project to google app engine standard environment?
I have created nextjs project with Isomorphic admin theme -
Python Inheritance with unique attribute in master class
I'm with a little problem. class Person(models.Model): cpf = BRCPFField(unique=true) class Student(Person): new_field = .... class Teacher(Student): another_field = ... class BoardMember(Person): class Meta: proxy = True CPF = USA SSN. A person can be a student, a board member and a student can be a teacher in future. When I register a person with a cpf, it's ok. But when I try to register the same person as a student, python show me a error because of the unique field. How can I solve this? -
How to post a Pandas DataFrame using API in Django
Currently I send one post request per DataFrame's row, which means that I read the row, convert it to Json data and send it using request.post. Is there any better way to send the entire data frame in one post request? Thanks, -
django saving two model in a one to many relationship
I trying to save two model in a one to many relationships but I am getting the error NOT NULL constraint failed:domestic_banks_naturalperson.domesticbank_id model # Create your models here class DomesticBank(models.Model): bank_name = models.CharField(max_length=100, null=True) subsidiary_or_branch = models.CharField(max_length=100, null=True) home_country = models.TextField(max_length=500, null=True) publish_date = models.DateField('Date Published', null=True) def __str__(self): return self.bank_name class NaturalPerson(models.Model): domesticbank = models.ForeignKey(DomesticBank, on_delete=models.CASCADE) natural_person_name = models.CharField(max_length=100, null=True) country = models.CharField(max_length=100, null=True) upload_passport_copy = models.FileField(upload_to='Passport/PDF', null=True) upload_additional_ID = models.FileField(upload_to='Other_ID/PDF', null=True) def __str__(self): return self.natural_person_name def add_bank_form(request): if request.method == 'POST': form = BankForm(request.POST) natural_person_form = NaturalPpersonPform(request.POST,request.FILES) OwnShares = OwnSharesInOtherCompanyForm(request.POST, request.FILES) if form.is_valid() and natural_person_form.is_valid(): form = form.save() naturalperson = natural_person_form.save(commit=False) naturalperson.form = form naturalperson.save() return HttpResponseRedirect('/DisplayBankRisk') else: form = BankForm() natural_person_form = NaturalPpersonPform() return render(request, 'add_domestic_bank.html', locals()) -
Django and hvad - deep query on translatable field
I have two models: Diet Product Diet has a foreign key that references Product. Product has a translatable field called name. I'd like to perform this query: Diet.objects.language().get(product__name='Some name') However, the following error occurs: WrongManager at /alimentazione-vie-urinarie Accessing translated fields like product.name from an regular model requires a translation-aware queryset, obtained with the .language() method. For regular, non-translatable models, you can get one using hvad.utils.get_translation_aware_manager I found an old similar question, however the answer hasn't worked for me. -
Adding Context to Django View Causing My Highcharts Map to Disappear
This is my first Django project, and I am working on a Django html template that should contain a Chart.JS bar graph (https://www.chartjs.org/docs/latest/charts/bar.html) alongside a Highcharts drilldown map of the US (https://www.highcharts.com/demo/maps/map-drilldown). I've successfully implemented my Chart.JS bar graph and passed data to it from our AWS RDS. But now when I try to implement even just the stock Highcharts code from their website, the chart fails to render at all. After trying to isolate the problem, I've found that the map does render if I delete "context" from the return statement in my view (i.e. delete "context" from the final line in my first block of code below). But this obviously then inhibits my bar graph from rendering, and I've been unable to fix it such that both graphs render. Any help would be greatly appreciated! My Django View: def index(request): mydb = mysql.connector.connect( host=xxxx, user=xxxx, password=xxxx, database=xxxx ) mycursor = mydb.cursor() mycursor.execute("WITH CS1 AS (SELECT cts.Name, cts.State, m.Frequently, m.Always FROM Masks m JOIN Counties cts ON (m.FIPS = cts.FIPS)) SELECT CS1.State, AVG((CS1.Frequently+CS1.Always)*100) AS Perc_High_Frequency FROM CS1 WHERE CS1.State<>'Puerto Rico' GROUP BY CS1.State ORDER BY Perc_High_Frequency DESC") tempList = mycursor.fetchall() statesMaskName = [item[0] for item in tempList] statesMaskPerc = … -
Django: Is there any performance differences when using ajax?
I'm working on refactoring project in the middle of the work. There are a lot of context when view return render. I want to change it to get response when dom rendered using ajax. I know it makes more request, but I wondered if there are any performance differences. If not, I want to do that. -
AttributeError: 'NoneType' object has no attribute 'distinct'
I have the below table view CREATE VIEW vStaff AS SELECT ContactInfo .*, Staff.position FROM ContactInfo LEFT JOIN Staff ON Staff.name = ContactInfo.name that selects information from these two models class ContactInfo(models.Model): name = models.CharField(max_length=30) email = models.EmailField(max_length=30) address = models.CharField(max_length=30) class Staff(models.Model): name = models.CharField(max_length=30) position = models.CharField(max_length=30) However, when I try to select from the vStaff like below in modelAdmin I get the above error Staff.objects.annotate(val=RawSQL("select * vStaff", ())) AttributeError: 'NoneType' object has no attribute 'distinct' -
How can I show a div or html element after submitting a form and retrieve some information from a view in Django
Currently when the user introduces a string in an input field and clicks the submit button, this invokes a view that returns through return render(request, 'index.html', context) a context that it basically contains data that is displayed in a table. I would like said table to be visible only after submitting the form and not before and that when it is visible it shows the information obtained from the view. The problem is that if through inline styling I make this table not visible, for example in the following way: <div class="row" id="searchVariantTable" style="display: none;"> <!-- SOME TABLE HERE--> </div> And then I use the onsubmit event for form or onclick for button, it doesn't work. (It works partially, I can see the tbody but thead is missing, so basically I can't display the retrieved data from the database). Similarly, if I try something like this: $('document').ready(function() { $('#searchVariantTable').hide(); $('form').submit(function(e) { $('#searchVariantTable').show(); e.preventDefault(); }); }); It doesn't work either. I think the last option, if I'm not mistaken, is AJAX, but I'm not quite sure how to do something like that with Django (it's my first time using Django) What am I doing wrong? Is there an option that I … -
Page Not Found (404) using Django (first app)
I'm working on my first django app, and i'm a rookie at coding, sometimes i really dont get where is the error and the tutorials and documentation dont help me either. The error is this one: Error Now, the code i have for the views: def update(request, id): cliente = get_object_or_404(Cliente, id=id) if request.method == 'GET': form = clienteForm(instance=cliente) return redirect("/clientepag/", id=id) else: form = clienteForm(request.POST, instance=cliente) if form.is_valid(): form.save() return redirect("/clientepag/", id=id) else: form = clienteForm() return redirect("/clientepag/", id=id) def clientepag(request, id): cliente = Cliente.objects.get(id=id) return render(request, 'clientepag.html', {'cliente': cliente}) I'm trying to make my update function to redirect me to clientepag/id, but i dont get why my clientepag function isnt getting the id i'm sending from the update, the db is being updated, i validated that, but the clientepag isnt getting the id i'm trying to send from the update, and i dont know if its the update that isnt sending the id, or the clientepag that isnt getting it, or is rejecting it. I already validated that the update function still have the id after the form.save() line My path list: from django.contrib import admin from django.urls import path from clientesapp import views urlpatterns = [ path('admin/', … -
Exporting and Importing a foreign key field that has a many-to-many relationship in Django
I've got a complicated relationship between my Django models and I'm trying to get django-import-export to play nicely. class Person(models.Model): name = models.CharField(max_length=64) class Team(models.Model): rep = models.ManyToManyField(Person, related_name="rep") def get_reps(self): return "/".join(sorted([p.name for p in self.reps.all()])) class Account(models.Model): tid = models.IntegerField("Territory ID", primary_key=True) name = models.CharField("Territory Name", max_length=64) sales_team = models.ForeignKey(Team, related_name="sales_team") I'm trying to export (and hopefully later import) the territories with the names of the reps as rendered by the get_reps method. class TerritoryResource(resources.ModelResource): tid = fields.Field(attribute='tid', column_name="Territory ID") name = fields.Field(attribute='name', column_name="Territory Name") sales_team = fields.Field( column_name="Sales Team", widget=widgets.ForeignKeyWidget(Team, "get_reps") ) The export is giving me a blank field. If I don't use the widget I get the Team ID as I'd expect. Is it possible to get my custom name in the export? -
An error in my relation, violates unique constraint
I'm working on a small project using Django, A task can be only in one status, The Error i get : duplicate key value violates unique constraint "task_task_status_id_de4e8cac_uniq" DETAIL: Key (status_id)=(1) already exists. What kind of relationship must I do between the two models? This is my models : class Task(models.Model): status = models.ForeignKey(Status, related_name="tasks", on_delete=models.CASCADE) title = models.CharField(max_length=60, blank=False, null=False) class Status(models.Model): title = models.CharField(blank=False, null=False, max_length=255) slug = models.CharField(blank=False, null=False, max_length=255) order = models.SmallIntegerField(default=0) def __str__(self): return self.title -
Django and Apache Server Configuration
I implemented a Django project with MySQL backend. It runs well using "Python manage.py runserver." Apache seems installed well with no errors. I can access the default apache server. However, I couldn't make the apache web server and Django work together. I followed the link below. https://studygyaan.com/django/how-to-setup-django-applications-with-apache-and-mod-wsgi-on-ubuntu I edited 000-default.conf and djangoproject.conf on the server. Could you give me some advice where I should look into? Version information. Python: 3.8.5 Django: 3.0 Ubnutu: 20.04 When I run "sudo systemctl status apache2" ● apache2.service - The Apache HTTP Server Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2021-04-14 17:18:03 UTC; 6 days ago Docs: https://httpd.apache.org/docs/2.4/ Main PID: ****(apache2) Tasks: ** (limit: **) Memory: M CGroup: /system.slice/apache2.service ├─ **** /usr/sbin/apache2 -k start ├─ /usr/sbin/apache2 -k start └─ /usr/sbin/apache2 -k start -
Dynamically added form fields in Django are not added to the form's cleaned_data
Values from fields that are added to an instance of a Django form - but which are not present in the class definition - do not seem to be added to the form's cleaned_data. (There are other threads on this topic, but they do not seem to provide a satisfying answer or solution.) In Django 3.8 there is comment in the __init__ function of the class BaseForm, on line 82 in the script django/forms/forms.py, which reads # The base_fields class attribute is the *class-wide* definition of # fields. Because a particular *instance* of the class might want to # alter self.fields, we create self.fields here by copying base_fields. # Instances should always modify self.fields; they should not modify # self.base_fields. The comment implies that it is indeed intended that the dictionary self.fields be modified with fields that are constructed for a given instance rather than for the whole class. But since the values of these dynamically added fields are not delivered to the self.cleaned_data, it seems as if the forms can not be used for anything. So why do they allow and encourage the use of this possibility? It seems completely pointless if they can not be used. I wrote … -
Foreignkey issue, Key (status_id)=(1) already exists
I'm working on a small project ( Kanban Board ) using Django / Rest Framework, I have two models Status(columns) and Task model, A task can be only in one column since we drag the task from column to column, which means a task can be only in one column. I did an OneToMany relationship by making a Foreign key, but I'm not sure if it's the correct choice because I'm getting an error when I try to add a new task. The Error i get : duplicate key value violates unique constraint "task_task_status_id_de4e8cac_uniq" DETAIL: Key (status_id)=(1) already exists. What kind of relationship must I do between the two models? This is my models : class Task(models.Model): status = models.ForeignKey(Status, related_name="tasks", on_delete=models.CASCADE) title = models.CharField(max_length=60, blank=False, null=False) class Status(models.Model): title = models.CharField(blank=False, null=False, max_length=255) slug = models.CharField(blank=False, null=False, max_length=255) order = models.SmallIntegerField(default=0) def __str__(self): return self.title -
Unique=True in Form not throwing any error
I'm entering a duplicate value (already saved in another instance of the same model) in my form to test the unique=True attribute. form.is_valid() returns 'False', as expected, but I don't receive any prompt in the template. Shouldn't I get prompted something like "obj with this value already exists"? The page simply reloads... What am I missing? forms.py def update_route(request, pk): instance = Route.objects.get(id=pk) if request.method == "POST": form = RouteForm(request.POST) if form.is_valid(): data = form.cleaned_data instance.name = data['name'] instance.priority = data['priority'] instance.url = data['url'] return redirect('campaigns:routes_list') form = RouteForm(instance=instance) context= { 'form': form, } return render(request, "campaigns/route_form.html", context) models.py class Route(models.Model): name = models.CharField(max_length=48) priority = models.SmallIntegerField(choices=PRIORITY_LEVEL, default=0, unique=True) url = models.URLField() Template <form method="post" action=""> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> -
Docker error using pipenv with django app
I'm encountering this error when trying to dockerize a django app as part of a tutorial I'm following. --system is intended to be used for pre-existing Pipfile installation, not installation of specific packages my directory looks like this C:. │ db.sqlite3 │ Dockerfile │ manage.py │ Pipfile │ Pipfile.lock │ ├───config │ asgi.py │ settings.py │ urls.py │ wsgi.py │ __init__.py │ └───pages │ admin.py │ apps.py │ models.py │ tests.py │ urls.py │ views.py │ __init__.py │ └───migrations __init__.py and the contents of my pipfile [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "~=3.2.0" [dev-packages] [requires] python_version = "3.9" and dockerfile # Pull base image FROM python:3.9 #set environment vars ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # set work directory WORKDIR /hello # install dependancies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv RUN pipenv install --system # copy project COPY . /hello/ the full error message is \hello>docker build . [+] Building 1.8s (9/10) => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 32B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => [internal] load metadata for docker.io/library/python:3.9.4 0.7s => [1/6] FROM docker.io/library/python:3.9.4@sha256:07c51c65ab9c1a156a1fb51eff3ec04feff7b85b2acb7d6cc65148b218d67402 0.0s => [internal] … -
Django REST: Set Object Filter to URL Parameter
I'm a noob when it comes to Django and REST, so please bear with me. I am trying to set a filter variable to equal a url paramater. The URL parameter is simple: foo.com/api/physicians/2 The way I'd like it work work is to set the URL parameter to the lookup field, like so: class DepartmentsAndPhysiciansViewset(viewsets.ModelViewSet): lookup_field = 'department_id' serializer_class = DepartmentsAndPhysiciansSerializer queryset = Physicians.objects.filter(department_id=lookup_field) But that returns: ValueError: Field 'id' expected a number but got 'department id'. So I set the department id manually like so: class DepartmentsAndPhysiciansViewset(viewsets.ModelViewSet): lookup_field = 'department_id' serializer_class = DepartmentsAndPhysiciansSerializer queryset = Physicians.objects.filter(department_id=5) And it works. Obviously I can't hardcode the department id, it needs to come from a URL parameter. Is there any way to set the URL parameter to be equal to the lookup field (department id)? Thanks! -
How to use annotate to Count items from a Django QuerySet
I am modeling Applications and the ways they are installed on user's devices as follows: class WindowsUserApplications(models.Model): application_name = models.CharField(max_length=60, null=False, unique=True) category = models.ForeignKey('ApplicationCategory', null=False, default=10, on_delete=models.SET_DEFAULT) class WindowsUserInstalls(models.Model): device_name = models.CharField(max_length=15, null=False) version = models.CharField(max_length=30, null=False) application = models.ForeignKey('WindowsUserApplications', related_name='windows_user_applications', null=False, on_delete=models.CASCADE) And then, on the view I want to get a list of the installed applications like this: def user_inventory(request, *args, **kwargs): user_applications = WindowsUserInstalls.objects.annotate(Count('application')) template = 'webapp/user_inventory.html' context = { 'user_applications' : user_applications, } return render(request, template, context) However, I keep getting repeated lines for the installed apps and all of them with an install count of 1, instead of getting them summarized. I have tried other approaches such as adding .values('application') to the query, with no luck. Thanks in advance for any hints. -
django grandparent parent child relationship
I have Django rest frame work with below model class Grandparent(models.Model): grandparent_name = CharField(max_length=20) class Parent(models.Model): grandparent = ForeignKey(Grandparent) parent_name = CharField(max_length=20) class Child(models.Model): parent = ForeignKey(Parent) grandparent = ForeignKey(Grandparent) child_name = CharField(max_length=20) All 3 models are registered in admin.py. When adding a entry into child model from django admin site, dropdowns for parent and grandparent are independent. In other words, I could select a grandparent and parent, that aren't bound as in "Parent" table. Here is what I want to achieve: When a grandparent is selected, parent field should show only a dropdown list that have the selected grandparent per "Parent" model. How could I achieve this? -
how to use Django template if condition inside Django Template?
{% if len(verifiedJobs) > 0 %} {% for v in verifiedJobs %} companyname:::{{v.companyname}}<br> jobDescription::::{{v.jobDescription}}<br> salary:::{{v.salary}}<br> {% endfor %} {% endif %} this is my code and it is not working it is giving errors about my if condition. -
Output Dates in Celery Crontab Schedule to Django Template
I'm using Celery for my Django project and I've scheduled some crontab tasks to send emails out to users at certain times. I need to output a schedule in an HTML/Django template that shows the dates that users can expect the emails to go out on. My crontab schedule looks like this for Celery: import os from celery import Celery from celery.schedules import crontab app = Celery("myapp") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) first_monday_april_to_july = crontab( minute=15, hour=6, day_of_week="monday", day_of_month="1-7", month_of_year="4,5,6,7" ) august_every_monday_first_two_weeks = crontab( minute=15, hour=6, day_of_week="monday", day_of_month="1-14", month_of_year="8" ) august_weekdays_second_two_weeks = crontab( minute=15, hour=6, day_of_week="mon-fri", day_of_month="15-31", month_of_year="8" ) app.conf.beat_schedule = { "report1": { "task": "email_report", "schedule": first_monday_april_to_july, }, "report2": { "task": "email_report", "schedule": august_every_monday_first_two_weeks, }, "report3": { "task": "email_report", "schedule": august_weekdays_second_two_weeks, } I was hoping to be able to grab all of the dates that the emails will be sent on from these tasks and save them into a list in the view and then send it to the template to be displayed in a table. Is something like this possible? I'm not having any luck finding a way to do this so far. -
Django - Button that will change a field in a model
I am building a scrum application where there are Sprint and User Story objects. I want the user to be able to click a button on the Sprint detail template and for a BooleanField in the model to be changed from False to True, marking the Sprint as complete. I have tried to think but not sure how I can about this? Here is my models.py: from django.db import models from django.contrib.auth.models import User, Group class Sprint(models.Model): LENGTH_CHOICES = (('1_week', '1 Week'), ('2_weeks', '2 Weeks'), ('3_weeks', '3 Weeks')) name = models.CharField(max_length=200) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sprints", null=True) project = models.ForeignKey(Group, on_delete=models.CASCADE, related_name="sprints", null=True) start_date = models.DateField(auto_now = False, auto_now_add = False) end_date = models.DateField(auto_now = False, auto_now_add = False) duration = models.CharField(max_length = 10, choices = LENGTH_CHOICES) complete = models.BooleanField(null = True, default = False) retrospective = models.CharField(max_length=10000, null=True) def __str__(self): return self.name class UserStory(models.Model): STATUS_CHOICES = (('To Do', 'To Do'),('In Progress', 'In Progress'), ('In Review', 'In Review'), ('Complete', 'Complete')) STORY_POINTS = ((0, 0), (1, 1), (2, 2), (3, 3), (5, 5), (8, 8), (13, 13), (20, 20), (40, 40), (100, 100)) name = models.CharField(max_length=300) sprint = models.ForeignKey(Sprint, on_delete=models.CASCADE, related_name="userstories", null=True) description = models.CharField(max_length=300) status = models.CharField(max_length = 11, choices … -
Backend subscribe system
Hello my dear great programmers. I am new to this case, and I have one question. I wrote an online registration system for the course, and came out a few problems. like thisPlease help a beginner programmer. I have created a multi-page html website, and it has sections like my courses, available courses, available courses page has different courses, and there is a subscribe button, I want when I click on subscribe button, it will show up on my courses website. Can you please help me to solve this problem -
How do I make each individual a user from a model?
This is probably simple but for me it has proved to be a headache. I'd like to make each teacher from TeacherData model to be a user using the first_name as the username and email as the password. Here are my models. School model class School(models.Model): name = models.CharField(max_length=100,null=True,blank=True) User model class User(AbstractUser): school = models.ForeignKey(School, on_delete=models.DO_NOTHING, null=True, blank=True) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) Teacher's model class TeacherData(models.Model): school = models.ForeignKey(School,on_delete=models.CASCADE) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField() If there's anything else required let me know and I'll add it.