Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to group child as a nested list for each parent?
This is a survey system The question is "How to properly serialize data to get nested answers under every question" (group answers as a nested list for each question)? Models class Survey(models.Model): name = models.CharField(max_length=150) start_at = models.DateTimeField(db_index=True) finish_at = models.DateTimeField(db_index=True) class Question(models.Model): QUESTION_TYPE = ( ("text", "Text answer"), ("choice", "Choose one option"), ("choice_multiple", "Choose many options") ) text = models.TextField(max_length=300) type = models.CharField(max_length=15, choices=QUESTION_TYPE) order_num = models.IntegerField() survey = models.ForeignKey(Survey, related_name="questions", on_delete=models.CASCADE) class Choice(models.Model): text = models.CharField(max_length=300) question = models.ForeignKey(Question, related_name="choices", on_delete=models.CASCADE) class SurveyResult(models.Model): survey = models.ForeignKey(Survey, related_name="results", on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, blank=True, related_name="surveys", on_delete=models.DO_NOTHING) class Answer(models.Model): survey_result = models.ForeignKey(SurveyResult, related_name="answers", on_delete=models.CASCADE) question = models.ForeignKey(Question, related_name="answers", on_delete=models.DO_NOTHING) choice = models.ForeignKey(Choice, related_name="answer_choices", null=True, blank=True, on_delete=models.DO_NOTHING, default=None) text = models.CharField(max_length=300, null=True, blank=True, default=None) Serializers class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ["id", "type", "order_num", "text", "choices"] class AnswerListSerializer(serializers.ModelSerializer): question = QuestionSerializer(read_only=True) class Meta: model = Answer fields = ["id", "question", "choice", "text", ] class SurveyListSerializer(serializers.ModelSerializer): answers = AnswerListSerializer(many=True) class Meta: model = SurveyResult fields = ["id", "survey", "user", "created_at", "answers", ] View class SurveyViewSet(CreateModelMixin, ListModelMixin, RetrieveModelMixin, GenericViewSet): queryset = SurveyResult.objects.all().prefetch_related( "answers", "answers__question", "answers__question__choices") pagination_class = PageNumberPagination permission_classes = [AllowAny] Result "id": 2, "survey": 1, "user": 18, "answers": [ … -
How to Enable iterative calculation in openpyxl?
is this way to enable iterative calculation Programmatically? -
Can't get data from ManyToMany relat in Django
I have two models like this: class Book(models.Model): name = models.CharField(blank=True, max_length=128) description = models.TextField(blank=True) count = models.IntegerField(default=10) authors = models.ManyToManyField(Author, related_name='books') and class Author(models.Model): name = models.CharField(blank=True, max_length=20) surname = models.CharField(blank=True, max_length=20) patronymic = models.CharField(blank=True, max_length=20) Now, question - how can I print name and surname of author of the certain book? -
Unable to communicate with postgres using docker and django
I don't achieve to communicate with my database postgres using Docker and Django. Here is my docker-compose.yml : version: '3' services: web: container_name: web build: context: ./web dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 volumes: - ./web/:/usr/src/web/ ports: - 8000:8000 - 3000:3000 - 35729:35729 env_file: - database.env stdin_open: true depends_on: - database database: container_name: database image: postgres volumes: - database-data:/var/lib/postgresql/data/ ports: - 5432:5432 volumes: database-data: Here is my database.env : # database.env POSTGRES_USERNAME=admin POSTGRES_PASSWORD=pass POSTGRES_DBNAME=db POSTGRES_HOST=database POSTGRES_PORT=5432 PGUSER=admin PGPASSWORD=pass PGDATABASE=db PGHOST=database PGPORT=5432 DATABASE=db SQL_HOST=database SQL_PORT=5432 And here is my Dockerfile : # pull official base image FROM python:3.8.3-alpine # set work directory WORKDIR /usr/src/web # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev RUN apk add zlib-dev jpeg-dev gcc musl-dev # install nodejs RUN apk add --update nodejs nodejs-npm # copy project ADD . . # install dependencies RUN pip install --upgrade pip RUN pip install -r requirements.txt # run entrypoint.sh ENTRYPOINT ["sh", "/usr/src/web/entrypoint.sh"] And there my entrypoint.sh : #!/bin/sh if [ "$DATABASE" = "db" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 10 done echo "PostgreSQL started" … -
when a user give information than it comes in admin how i can do this in django
When a user give a information in my site suppose user give when he needs a appointment, which doctor he need to appointment . So how i can see the data. -
How to delete a record through a button in django
I have created a model Announcement in models.py file class Announcement(models.Model): title = models.CharField(max_length=30) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) def __str__(self): return self.title And for deleting a record of Announcement I have created the following view def AnnouncementDelete(request, pk): announcement = get_object_or_404(Announcement, pk=pk) if request.method=='POST': announcement.delete() return redirect('/') return render(request, 'classroom/announcement_confirm_delete.html', {'announcement': announcement}) The delete view of announcement (that is AnnouncementDelete) has the following url path("delete/<int:pk>/", view=views.AnnouncementDelete, name="AnnouncementDelete"), If i enter http://127.0.0.1:8000/classroom/delete/3 on browser it is deleting the Announcement having pk = 3 Now I want a button to directly delete my record without the need of typing http://127.0.0.1:8000/classroom/delete/3 on browser I have tried the following methods in my allannouncement.html file {% extends "classroom/base.html" %} {% block content %} <h1>Announcements</h1> {% for announcement in announcements %} <!-- starting loop (posts is keyword from view) --> <div style="border-style: solid;"> {% if announcement.teacher.user == request.user %} <div> <a href="{% url 'classroom:AnnouncementDelete' %}">Delete</a> </div> {% endif %} {{ announcement.pk }} <a class="mr-2">Posted by: {{ announcement.teacher }}</a> <h2><a class="article-title">{{ announcement.title }}</a></h2> <p class="article-content">{{ announcement.content}}</p> </div> {% endfor %} {% endblock content %} but it is giving the following error NoReverseMatch at /classroom/allannouncement/ Reverse for 'AnnouncementDelete' with no arguments not … -
check if POST request exist in database and return custom response in django rest framework
i am creating basic Coupon verification Django Rest framework APP, i just want to pass json parameter through Postman and get custom response if coupon code is valid or invalid. Here is my models.py File: from django.db import models # Create your models here. class Coupon(models.Model): code = models.CharField(primary_key=True, max_length=50, unique=True) def __str__(self): return self.code Here is my Serializers.py file: from rest_framework import serializers from .models import Coupon class CouponSerializer(serializers.ModelSerializer): class Meta: model = Coupon fields = '__all__' I like to write views for given serializer and get custom message as mentioned above. -
Datatable not working with filtered results from views?
Here datatable pagination doesnot work with the view SortResults. It filters the table but the pagination doesnot work. Initially results are sent to the main-template from another view like this MyModel.objects.all() in this case the pagination works. But applying filter and ajax, pagination doesnot work . ajax <script> $('#sort').on('change', function(e) { e.preventDefault(); $.ajax({ type: "GET", url: "{% url 'sort-results' %}", data: { 'query' : $('#id').val(), }, success: sortSuccess, dataType: 'html' }); }); function sortSuccess(data, textStatus, jqXHR) { $('#results').html(data) } </script> views class SortResults(View): def get(self, request, *args, **kwargs): query = request.GET.get('query', '') if query == 'recent': results =MyModel.objects.all().order_by('-date') return render(request, 'results.html', {'results': results}) results.html {% for res in results %} some data {% endfor %} main-template <table id="results"> <thead> <tr> <th></th> </tr> </thead> <tbody> {% include 'results.html' %} </tbody> </table> -
How to check user email address valid or not in django can anyone have idea to check user interring email address is valid or not
How we can know user email address is valid or not without sending a link is there any method to do this in django , i just try to check the user their email address is valid or not . -
Django : attribute not defined in the "models.py" file
My "models.py" file has the following code: from django.db import models # Create your models here. class Questions(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice (models.Model): choice_text = models.CharField(max_length=200) votes = models.IntegerFeild(default = 0 ) question = models.ForeignKey(Question, on_delete=models.CASCADE) The error I am getting while running the code is: votes = models.IntegerFeild(default = 0 ) AttributeError: module 'django.db.models' has no attribute 'IntegerFeild' -
how to display registered values in profile page - django
I have a member table, I want to fetch and display some of the fields like fullname , email and phone number in the profile page. this is my member table class Member(models.Model): fullname=models.CharField(max_length=30) companyname=models.CharField(max_length=30) Email=models.CharField(max_length=50) password=models.CharField(max_length=12) contactno = models.CharField(max_length=30,default='anything') this is my profile table class Profile(models.Model): fullname=models.CharField(max_length=60) contactno=models.CharField(max_length=10) worknumber=models.CharField(max_length=10) email=models.CharField(max_length=30) company=models.CharField(max_length=20) i want to display fullname email and phone number from member table.. -
how to connect one field value to sencond field value in django?
i amnot understanding how to one session to another session users that why i did table in one user sending mail in that he will get some link he register again that is second session statred i am understand how to connect both see in that table if some in same name then its showing status one .. but i want if some select one first user skale9173@gmail second user kale.sandhya07@gma enter image description here -
How to use variable in for loop using DJango
I can do this in regular python, but can't seem to do this in the template. So here are my variables: PropertyID = ['A1','A2','A3'] filePaths = {A1:'['file1.jpg','file2.jpg','file3.jpg',]', A2:'['file1.jpg','file2.jpg','file3.jpg']'} My template: {% for properties in PropertyID %} {% for filePaths in imageFiles %} {% for singleFiles in filePaths %} {% endfor %} {% endfor %} {% endfor %} I want to be able to iterate through filePaths dynamically, but when I try: {% for singleFiles in filePaths.{{properties}} %} I get an error: Could not parse the remainder: '{{properties}}' from 'filePaths.{{properties}}' I have tried filePaths['properties'] and filePaths[properties] and pretty much every combination. I just can't figure out why this isn't working. If I do filePaths.A1 it works fine, but I can't iterate over the rest of the paths this way. Any help would be much appreciated, probably something really dumb I missed. -
Unable to create a django project with 2 apps in it
When I run the server it shows this error: and my code link https://github.com/ARGAMERX/django-problem -
My CSS Navigation Bar's Background color property isn't working,please help me
I am trying to create a navigation bar with a search box. When I insert the elements in the navbar and set the display to inline-block in css, the navigation bar's background color is not being displayed, I am trying to get around this problem for a while now, please help me. My HTML navbar, *{ box-sizing: border-box; font-family: 'Lato', sans-serif; font-weight: normal; color: white; background-color: rgba(0,0,0); margin:0; } .main_nav{ background-color: rgba(255,255,255.1); } .main_nav li{ display: inline-block; padding: 0 10px; } {%load static%} <!DOCTYPE html> <html> <head> <title></title> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Lato&display=swap" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="{%static 'css/styles.css'%}"> </head> <body> <header> <nav class="main_nav"> <ul> <li><img width="80" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/IMDB_Logo_2016.svg/1200px-IMDB_Logo_2016.svg.png"></li> <li>Menu</li> <li> <form method="GET" action="{%url 'search-view'%}"> <input type="search" name="query" id="query" placeholder="search movie"> <button type="submit">Search</button> </form> </li> </ul> </nav> </header> <section> {%block content%} {%endblock%} </section> <footer></footer> </body> </html> the .main_nav background color doesn't seem to be working. If you have a better way to give the same output with the background color, please do tell me that also. Excuse the bad code, I'm kinda new to this! Thanks in advance! -
I have this Error - jquery.min.js: 2 Uncaught TypeError: Illegal invocation django
I am trying to save the order details data, however I get this error. jquery.min.js: 2 Uncaught TypeError: Illegal invocation I am still in the process of sending that data to the database, I just want to see if it is working correctly with this line of code: vents = request.POST['ventas'] JS $('form').on('submit', function (e) { e.preventDefault(); var parametros = new FormData(); parametros.append('action', $('input[name="action"]').val()); parametros.append('ventas', JSON.stringify(ventas.items)); submit(window.location.pathname, parametros, function(){ location.href = "{% url 'Venta' %}"; }); }); VIEWS def post(self, request, *args, **kwargs): data = {} try: action = request.POST['action'] if action == 'autocomplete': productos = Producto.objects.filter(nombre__icontains=request.POST['term'])[0:10] for i in productos: data = [] item = i.toJSON() item['value'] = i.nombre data.append(item) elif action == 'add': vents = request.POST['ventas'] else: data['error'] = 'No ha ingresado a ninguna opción' except Exception as e: data['error'] = str(e) return JsonResponse(data,safe=False) -
How to display registered person details in profile page - Django
i have a member table, I want to display some of the fields like fullname , email and phone number in the profile page. this is my member table class Member(models.Model): fullname=models.CharField(max_length=30) companyname=models.CharField(max_length=30) Email=models.CharField(max_length=50) password=models.CharField(max_length=12) contactno = models.CharField(max_length=30,default='anything') this is my profile table class Profile(models.Model): fullname=models.CharField(max_length=60) contactno=models.CharField(max_length=10) worknumber=models.CharField(max_length=10) email=models.CharField(max_length=30) company=models.CharField(max_length=20) i want to display fullname contactno email automatically from member table -
why this error is showing [Errno 61] Connection refused in django
why i'm getting this [Errno 61] Connection refused error after doing and adding required things in django can anyone fEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' settings.py ACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_HOAT='smtp.gmail.com' EMAIL_HOST_USER= 'xyz@gmail.com' EMAIL_HOST_PASSWORD ='*****' EMAIL_PORT = 587 EMAIL_USE_TLS = True views.py i also have on less secure app in gmail account def signup(request): if not request.user.is_authenticated: fm=signUpForm() if request.method == 'POST': fm = signUpForm(request.POST) if fm.is_valid(): fm.save() from_email = settings.EMAIL_HOST_USER em = fm.cleaned_data['email'] to_list = [em] send_mail('Subject here','Here is the message.',from_email,to_list,fail_silently=False,) print(send_mail) return redirect('home') else: fm = signUpForm() return render(request,"signup.html" ,{'signupforms':fm}) -
Sorting with 'Date' Django template filter
I use date_value|date:'d M, Y' date filters when presenting my data in a jQuery datatable. However, the table is unable to sort the rows correctly. eg. 28 DEC is indeed an older date than 30 DEC but it is considered older than 29 NOV as well since the sorting does not compare the time but the literal strings instead. -
I am having a problem with Reverse method on comment section for a blog post
I am having a problem with Reverse method on comment section for a blog post. Posting part works fine but its the redirect view which is not working. It greets me with the message: Not Found: /article/17/ [18/Jan/2021 03:38:33] "POST /article/17/ HTTP/1.1" 404 1747 May be it has something to do with the id or i am redirecting in a wrong way .. Here's what i've done: views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import messages from django.urls import reverse from django.http import HttpResponseRedirect from .models import Article from comments.models import ArticleComment from comments.forms import ArticleCommentForm from django.views.generic import ( ListView, DetailView ) class ArticleListView(ListView): model = Article template_name = 'articles/home.html' context_object_name = 'articles' ordering = ['-date_published'] paginate_by = 5 class ArticleDetailView(DetailView): model = Article form_class = ArticleCommentForm template_name = 'articles/article_detail.html' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) comments = ArticleComment.objects.filter( article =self.get_object() ).order_by('created_on') data['comments'] = comments if self.request.user.is_authenticated: data['comment_form'] = ArticleCommentForm(instance=self.request.user) return data def post(self, request, pk, **kwargs): article = get_object_or_404(Article, id=request.POST.get('object_id')) if request.method == 'POST': form = ArticleCommentForm(request.POST) if form.is_valid: new_comment = form.save(commit=False) new_comment = ArticleComment(comment= request.POST.get('comment'), user = self.request.user, article = self.get_object()) new_comment.save() messages.success(request, f'Your comment has been posted') return reverse(request, 'article-detail', kwargs={id: self.id}) else: context … -
Django models AutoFeild countinuously incrementing. Not starting from last deleted record number
I am working on a project in Django and using Autofield as primary key in models. Here in Django when I delete any record it is deleted successfully and then when I enter a new record using Django forms the primary key of the new record is next value of the previous record. **Example: ** Suppose I have a table and I've set its primary key as AutoField in Django models and then I enter records so the primary key will be " 1 " and " 2 " respectively, And now suppose I have deleted the second record from the database and then insert the new record then the database sets its Primary key "3" but I want that after deleting a record the database starts incrementing from previous value like if i deleted the record which has primary key "2" and then I insert a new record its Primary Key should be " 2 ". Is it possible ? If the above situation is possible please guide me how to do it. My model is something like given below: models.py class Product(models.Model): prod_ID = models.AutoField("Product ID", primary_key=True) prod_Name = models.CharField("Product Name", max_length=30, null=False) prod_Desc = models.CharField("Product Description", max_length=2000, … -
Reverse for '<QuerySet [<ShortURL: https://google.com>]>' not found
I'm trying to create a url shortener and I'm creating the redirect part of it. I have a view that triggers when a user searches the short url that they generated. # views.py def page_redirect(request, url): get_url = ShortURL.objects.filter(short_url=url)[:1] return redirect(get_url) get_url returns <QuerySet [<ShortURL: https://google.com>]>. Does anyone know how I would filter https://google.com so I can put that url into redirect() to redirect the user to the original long url? Other Code: # models.py class ShortURL(models.Model): long_url = models.URLField(max_length=700) short_url = models.CharField(max_length=100) time_date_created = models.DateTimeField() def __str__(self): return self.long_url # urls.py urlpatterns = [ path('<str:url>', page_redirect, name='redirect'), ] -
how serve css on djago sub domain (on cpanel)
I would like to know how to run django in a sub domain in cpanel currently I did it using cpanel like this url 'www.domail / test / app' the application loads fine but the css and js points to the source as for example (www.domail.com/statics ..) in turn the admin panel does not load any css or js U_U If anyone has an idea or doc that can give me some insight, I would be very grateful -
Django: Cannot save data from Form in Database (MySql)
I've been following a tutorial for Django, but making small changes, doesn't allow me to save the form in Database. views.py: def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] contact = Contact(email=email, subject=subject, message=message).save() return render(request, 'contact.html', {'form': form}) else: form = ContactForm() return render(request, 'contact.html', {'form': form}) models.py class Contact(models.Model): email = models.EmailField(max_length=200) subject = models.CharField(max_length=200) message = models.TextField(max_length=500) forms.py class ContactForm(forms.Form): email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) -
why CSRF verification failed. Request aborted. becuae i added {% csrf_token %} in my template
i have added {% csrf_token %} inside form but it is still showing csrf verification fail can anyone help me to find whats going wrong in my code my signup.py file {% extends 'home.html' %} {% load static %} {% block body %} <div class="container-fluid mt-5 mb-4 col-lg-8 text-center text-secondary"> <h4 class="text-secondary"><b>Login using your credentials </b></h4> </div> <div class="container-fluid p-3 mt-1 mb-5 col-lg-8 signupf"> <form action="" autocomplete="on" method="POST" novalidate> {% csrf_token %} {% for fm in signupforms %} <div class="form-group mt-0 m-0"> {{fm.label_tag}} {{fm}} <small class="text-danger">{{fm.errors|striptags}}</small><br /> </div> {% endfor %} <input class="btn btn-primary mb-4" type="submit" value="Submit" /> </form> </div> {% endblock body %} views.py file and also showing errno 61] connection refused def signup(request): if not request.user.is_authenticated: fm=signUpForm() if request.method == 'POST': fm = signUpForm(request.POST) if fm.is_valid(): fm.save() from_email = settings.EMAIL_HOST_USER em = fm.cleaned_data['email'] to_list = [em] send_mail('Subject here','Here is the message.',from_email,to_list,fail_silently=False,) print(send_mail) return redirect('home') else: fm = signUpForm() return render(request,"signup.html" ,{'signupforms':fm})