Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I filter django queryset with the gap between different date field?
Say there's a table to collect spend value: class AccountsInsightsHourly(models.Model): account_id = models.CharField(max_length=32, blank=True, null=True) account_name = models.CharField(max_length=255, blank=True, null=True) account_create_time = models.DateTimeField(blank=True, null=True) account_status = models.IntegerField(blank=True, null=True) spend_cap = models.BigIntegerField(blank=True, null=True) balance = models.BigIntegerField(blank=True, null=True) spend = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) vertical = models.CharField(max_length=32, blank=True, null=True) date = models.IntegerField(blank=True, null=True) hour = models.IntegerField(blank=True, null=True) created_time = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'accounts_insights_hourly' unique_together = (('account_id', 'date', 'hour'),) ordering = ["account_id", "-hour"] The data saved as id account_id spend ... hour date 1 1233222 1000 10 20200819 2 1233222 2000 18 20200819 3 1233222 3000 10 20200820 4 1233222 4000 18 20200820 ... My question is how can I filter all data whose spend is more than yesterday (the final spend for yesterday should be same with lastest hour 18) # for account 1233222 # the lastest spend for yesterday is 2000 # Then if the spend for today (3000) is over 2000 , then this account 1233222 should be filtered. How can I use a queryset filter condition to get the expected result. Great Thanks. -
Save formset in Django returns None model
I've a problem with my formset. When I submit the formset, the models are not saved and displayed as None. I don't understand why, can somebody light me ? There is no problem in the template nor the urls.py. I get this within my log console: See image Here is my code: // views.py def classroom_call_the_roll(request, class_id): classroom = Classroom.objects.get(pk=class_id) students = classroom.students.all() queryset = Attendance.objects.none() AttendanceFormset = modelformset_factory( model=Attendance, form=AttendanceForm, can_delete=False, extra=len(students) ) if request.method == 'POST': formset = AttendanceFormset( request.POST, queryset=queryset, initial=[{'student': student} for student in students] ) for form in formset.forms: instance = form.save(commit=False) print(instance) else: formset = AttendanceFormset( queryset=queryset, initial=[{'student': student} for student in students] ) return render( request, 'highschool/attendance/classroom_attendance_create.html', { 'formset': formset } ) -
Django update GenericForeignKey after object creation
Even if I am an experienced developper, I am pretty new in Python/Django, I probably missed to do something or perhaps I am trying to make something impossible... I'm using Django 3 with Python 3.7 Summary: I have a model A with a GenericForeignKey to a model B or a model C. When I set the link, the object A might already exist in the database, so I call a "get_or_create" method to reatreive the object if it is already exist or create a new one if it doesn't existe yet. Just after the "get_or_create", I set the link to an another object. I tried to set the link with many ways from instance of object A to an instance of object B but every time I have an error, I looked for some examples to know how to set the GenericForeignKey link when the model is already instanciate but I didn't found it. What I tried: The last version of my code : For class A : from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class A(models.Model): # ... number = models.IntegerField( 'Number', editable=False, default='-1' ) content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True) object_id = models.PositiveIntegerField(null=True) object_srce … -
How do I use the existing tables in Postgre DB and use them in Django
I'm new to Django and i'm trying to build a web console for the users who can view, insert/update/delete data to PostgreSQL DB. I have couple of tables already created which i want to use. I have used below command to inspect the tables and use them in Django models $ python manage.py inspectdb bkp_fulfilment_product_provider > models.py When I run the above command I get a error as below: Error: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each `ForeignKey` and `OneToOneField` has `on_delete` set to the desired behaviour # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from `django.db` import models # Unable to inspect table bkp_fulfilment_product_provider # The error was: syntax error at or near `WITH ORDINALITY` LINE 6: FROM `unnest(c.conkey)` WITH ORDINALITY co... Thanks Kiran Thota -
Connect data (collected before user is logged in) to user account (after user logs in) - Django
I am working on a Django project where a quiz is taken when someone visits the website. The visitor answers all the questions and then the result is generated. But the user needs to log-in/signup to see the result. When the user submits the quiz, data is stored in the quiz table which has a foreign key of the user model. My question is how can I link that quiz table object to the user account when they log in or register to see the result? """ quiz model class Quiz(models.Model): ques2 = models.CharField(max_length=1000, choices=choices, default="", verbose_name = "I've always dreamed of") ques3 = models.CharField(max_length=1000, choices=choices, default="", verbose_name = "I prefer to") ques4 = models.CharField(max_length=1000, default="", verbose_name = "I want to earn") ques9 = models.CharField(max_length=1000, default="", blank=True, verbose_name = "How would you describe your personality?") ques10 = models.CharField(max_length=1000, default="", blank=True, verbose_name = "What are your goals?") result = models.ForeignKey(Moneymaker, on_delete= models.CASCADE, blank=True, null=True, default="", related_name='result') user = models.ForeignKey(User, on_delete= models.CASCADE, blank=True, null=True) """ -
How to list all users to the template in Django?
I want to display all users nicknames to the template, but i am not sure, how to work with django build-in views. Can someone help me to figure out. views.py class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post class UsersView(TemplateView): template_name = 'blog/user_search.html' def get_context_data(self,**kwargs): context = super(UsersView,self).get_context_data(**kwargs) context['object_list'] = User.objects.all() return context template {% extends "blog/base.html" %} {% block content %} <h1>Search page</h1> {% for user in object_list %} <li class="user">{{ user }}</li> {% endfor %} {% endblock content %} models.py class Post(models.Model): #users = [str(user) for user in User.objects.all()] field_choices=(('art','art'), ('producing','producing')) title = models.CharField(max_length=100) content = models.TextField() field=models.CharField(max_length=100, choices=field_choices, default='general') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) Code works but it does not show anything to the template, I supposed that i should combine Templateview with ListView but i am not sure how to do it correctly. Tahnk you in advance! -
unable solve this installation error in django?
How to solve this error while installing Django in a virtual environment? enter image description here -
Python- Django (def was_published_recently(self):) [closed]
n How can I check it's true or not? def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) -
Unable to launch Jupyter Note from Anaconda Navigator(Windows)
I launch anaconda from the command prompt using this code anaconda-navigator However, when I try to launch Jupyter Notebook from Anaconda, I receive this error code. Could someone help, please? C:\Users\mxixq\anaconda3\lib\site-packages\setuptools\distutils_patch.py:25: UserWarning: Distutils was imported before Setuptools. This usage is discouraged and may exhibit undesirable behaviors or errors. Please use Setuptools' objects directly or at least import Setuptools first. warnings.warn( Traceback (most recent call last): File "C:\Users\mxixq\anaconda3\Scripts\jupyter-notebook-script.py", line 6, in from notebook.notebookapp import main File "C:\Users\mxixq\anaconda3\lib\site-packages\notebook\notebookapp.py", line 49, in from zmq.eventloop import ioloop File "C:\Users\mxixq\AppData\Roaming\Python\Python38\site-packages\zmq_init_.py", line 50, in from zmq import backend File "C:\Users\mxixq\AppData\Roaming\Python\Python38\site-packages\zmq\backend_init_.py", line 40, in reraise(*exc_info) File "C:\Users\mxixq\AppData\Roaming\Python\Python38\site-packages\zmq\utils\sixcerpt.py", line 34, in reraise raise value File "C:\Users\mxixq\AppData\Roaming\Python\Python38\site-packages\zmq\backend_init_.py", line 27, in ns = select_backend(first) File "C:\Users\mxixq\AppData\Roaming\Python\Python38\site-packages\zmq\backend\select.py", line 28, in select_backend mod = import(name, fromlist=public_api) File "C:\Users\mxixq\AppData\Roaming\Python\Python38\site-packages\zmq\backend\cython_init.py", line 6, in from . import (constants, error, message, context, ImportError: cannot import name 'constants' from partially initialized module 'zmq.backend.cython' (most likely due to a circular import) (C:\Users\mxixq\AppData\Roaming\Python\Python38\site-packages\zmq\backend\cython_init_.py) -
Django admin default autocomplete filter not working
Django 2.* admin default autocomplete field not working with filter. Is there are any temporary fix until django fix this issue? Thanks -
How to add tinymce to django form
I want to add tinymce to a user form and not the admin site, how can I make it? here is a variable of my model that shows tinymce only in the admin page: text = HTMLField('body',max_length=4000) -
TypeError: User() got an unexpected keyword argument 'confirm_password'
I want to add password field and confirm_password field to my UserSerializer. I wrote a function called create to create a hashes password for my password field but before it can create the hashes password I want it to make sure that confirm_password and password are matched. The code works fine if I remove the confirm_password field. What is the problem? My serializers.py # serializer define the API representation class UserSerializer(serializers.HyperlinkedModelSerializer): # password field password = serializers.CharField( write_only = True, required = True, help_text = 'Enter password', style = {'input_type': 'password'} ) # confirm password field confirm_password = serializers.CharField( write_only = True, required = True, help_text = 'Enter confirm password', style = {'input_type': 'password'} ) class Meta: model = User fields = [ 'url', 'first_name', 'last_name', 'email', 'password', 'confirm_password', 'is_staff' ] def create(self, validated_data): if validated_data.get('password') != validated_data.get('confirm_password'): raise serializers.ValidationError("Those password don't match") elif validated_data.get('password') == validated_data.get('confirm_password'): validated_data['password'] = make_password( validated_data.get('password') ) return super(UserSerializer, self).create(validated_data) error I got TypeError: User() got an unexpected keyword argument 'confirm_password' [20/Aug/2020 16:15:44] "POST /users/ HTTP/1.1" 500 168152 I can edit the question if you need more detail. Ty! -
Django - How to do scoring in a quiz app with multiple attempts
I am making a quiz app in Django and struggling with the scoring. This is my model setup: class Quiz(models.Model): song = models.ForeignKey(Song, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=15) slug = models.SlugField(unique=True, max_length=250) questions_count = models.IntegerField(default=0) class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) label = models.CharField(max_length=1000, help_text="Enter the question text that you want displayed") class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.CharField(max_length=100) is_correct = models.BooleanField('Correct answer', default=False) class QuizTaker(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) correct_answers = models.IntegerField(default=0) completed = models.BooleanField(default=False) attempt_number = models.AutoField(primary_key=True) In my html, the quiz is displayed as follows: {% for q in question_list %} {{q}} <br> {% for choice in q.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.answer }}"> <label for="choice{{ forloop.counter }}">{{ choice.answer }}</label><br> {% endfor %} <a class='btn btn-warning save_ans' href="#">Save answer</a> The answer to every question is handled via an ajax call and sent to the following view: ans_given = [] def save_ans(request): ans = request.GET['ans'] ans_given.append(ans) return HttpResponse(ans) I've approached the scoring as follows: ans_correct = [] answers = models.Choice.objects.filter(is_correct=True) for i in answers: scoring['ans_correct'].append(i.answer) def quiz_results(request, pk): score = 0 quiz = models.Quiz.objects.get(song__pk=pk) count = quiz.questions_count questions = models.Question.objects.filter(quiz=quiz) for i in range(len(questions)): if ans_given[i] == ans_correct[i]: … -
Django rss media content parsing
Need help please. I am trying to build an rss-based feed in django. But I am finding media:content (url, medium, height and width) to be tricky. I have looked and looked, and ended up with this: class CustomFeed(Rss201rev2Feed): def add_item_elements(self, handler, item): super().add_item_elements(handler, item) handler.addQuickElement("image", item["image"]) class Rss(Feed): feed_type = CustomFeed title = "#Title to the item" link = "/feeds/" description = "#Description to the item" def item_extra_kwargs(self, item): img_url = item.image.medium.url request_url = self.request.build_absolute_uri('/')[:-1] image_url_abs = f"{request_url}{img_url}" return { 'image': image_url_abs } But this gives me the image as standalone in the rss feed: <image>https://www.url.com/image.jpg</image> i badly need the code to return this: <media:content url="https://www.url.com/image.jpg" medium="image" height="640" width="362"/> please help. -
Django When conditional expression with Exists subquery in django 2 raise: TypeError: cannot unpack non-iterable Exists object
models.py class PersonPhoneQuerySet(models.QuerySet): def with_bill_sums(self, bill_date_from: datetime.date, bill_date_till: datetime.date): return self.annotate( sum_all=Coalesce( Sum('telephone__bill__value', filter=Q( telephone__bill__dt__gte=bill_date_from, telephone__bill__dt__lte=bill_date_till, )), Value(0) ), sum_service=Coalesce( Sum( Case( When( Q( Q(Exists(Telephone.objects.filter(num=OuterRef('telephone__bill__call_to')))) | Q(telephone__bill__bill_type=BillType.INTERNET) | Q(telephone__bill__bill_type=BillType.PAYMENT) | Q(telephone__bill__call_to=BILL_IN_ROAMING_AON_TEXT), telephone__bill__dt__gte=bill_date_from, telephone__bill__dt__lte=bill_date_till, ), then='telephone__bill__value'), default=0, output_field=models.DecimalField() )), Value(0) ), ) class Telephone(models.Model): num = models.CharField('Номер', max_length=50, unique=True) sim = models.CharField('SIM карта', max_length=50, blank=True) class Person(models.Model): fio = models.CharField('ФИО', max_length=50) email = models.EmailField('Email', null=True, blank=True) class PersonPhone(models.Model): BIG_DATE = datetime.date(3333, 1, 1) objects = PersonPhoneQuerySet.as_manager() telephone = models.ForeignKey(Telephone, models.CASCADE, verbose_name='Телефон') person = models.ForeignKey(Person, models.CASCADE, verbose_name='Сотрудник') date_from = models.DateField('Начало периода привязки') date_till = models.DateField('Конец периода привязки', default=BIG_DATE) limit = models.IntegerField('Лимит', default=0) tariff = models.CharField('Тариф', max_length=20, blank=True, default='') class Bill(models.Model): telephone = models.ForeignKey(Telephone, models.CASCADE, verbose_name='Телефон') bill_type = models.DecimalField('Тип соединения', choices=BillType.choices, db_index=True, max_digits=1, decimal_places=0) dt = models.DateTimeField('Дата и время звонка') value = models.DecimalField('Стоимость', max_digits=10, decimal_places=4, default=0) call_to = models.CharField('Вызываемый абонент', max_length=32, blank=True, default='', db_index=True) duration = models.DecimalField('Продолжительность, сек', max_digits=8, decimal_places=0, null=True, blank=True) call_direction = models.CharField('Направление соединения', choices=CallDirection.choices, max_length=1, default=CallDirection.UNDEFINED) Run: from apps.mobile import models, consts from common_tools.date import last_day_of_month date_from = datetime.datetime(2020, 5, 1) date_till = last_day_of_month(date_from) qs = models.PersonPhone.objects.filter( person__fio__icontains='SomeMan', telephone__num__icontains='+79655171234', date_from__lte=date_from, date_till__gte=date_till, ).with_bill_sums(date_from, date_till) for i in qs: print( i, '\n sum_all: {}'.format(i.sum_all), '\n sum_service: {}'.format(i.sum_service), ) It works on django … -
Figuring out problematic brackets
Hi I have the following scenario: import queryString from 'query-string'; data = {key: ['a', 'b']} axios.get('url', { params: data, paramsSerializer: function(params) { return queryString.stringyfy(params, {arrayFormat: 'brackets'}) }, headers: headers } On my django end when i get this: request.GET = <QueryDict: {'key[]': ['a', 'b']} > I am not sure how the mysterious '[]' came about and when i followed online solutions to use queryString, it does not seem to work. Thanks -
COPY .tar.gz needed in Dockefile or not?
Docker newbie here, quick question about the COPY command while dockerizing Django. I thought the COPY command is used to copy over a local file into the Docker container/context or else, as far as Docker is concerned, during the build the file does not exist. The development Dockerfile from the tutorial I'm following had this section: # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt So I understood that without that COPY command during the build the second RUN command would fail because it has no idea what requirements.txt is. Therefore, since I wanted to install my django-polls app tarball, I added a COPY and tacked on the phrase to the second RUN: # install dependencies COPY ./requirements.txt . COPY ./django-polls-0.1.tar.gz . RUN pip install --upgrade pip && pip install -r requirements.txt && pip install django-polls-0.1.tar.gz As you can see, I combined the two RUN commands, added the COPY .tar.gz line, and tacked the .tar.gz installation on to the end of the RUN command. So I have 2 questions, the second one being more of the focus of this post: Was it necessary to move the pip install --upgrade pip into the final … -
Django keeps recreating foreign key field for legacy database with migrations command
I,m quite new to Django development. I,m working with a legacy database created with MySQL. Now I,m facing a problems with Django migrations. I have few tables that are using foreign keys for the reference to another table. Now if I allow Django to manage those tables with foreign keys, then Django tries to recreate the foreign key fields during make-migrations and migrate command. Even when the fields are already there. Besides this Django is working perfectly with the database if I don't allow Django to manage those table. My Code is for table facing error Models.py from django.db import models from django.utils.translation import gettext_lazy as _ from django.db.models.signals import pre_save from chooseright.utils import unique_slug_generator class StoreTable(models.Model): store_id = models.AutoField(primary_key=True) name = models.CharField(max_length=45, blank=True, null=True) slug = models.SlugField(max_length=45, blank=True, null=True) catagory = models.ForeignKey(CatagoryTable, on_delete=models.CASCADE, blank=True, null=True) brand = models.ForeignKey(BrandTable, models.DO_NOTHING, blank=True, null=True) class Meta: managed = True db_table = 'store_table' verbose_name = _("Store") verbose_name_plural = _("Stores") def __str__(self): return self.name Migration Code from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0009_auto_20200820_1258'), ] operations = [ migrations.RenameField( model_name='storetable', old_name='store_name', new_name='name', ), migrations.AddField( model_name='storetable', name='brand', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='core.BrandTable'), ), migrations.AddField( model_name='storetable', name='catagory', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='core.CatagoryTable'), … -
Pagination in Django GraphQL API
I am trying to build an api using using django+graphene, I am confused about pagination what is standard way of implementing pagination? I have heard of first and skip parameter but how to get different data in second request. -
My form gets Submitted but no data is being added in database django
I am trying to make a website's contact page using django where client enters data and it gets submitted in database, the form gets submitted the project runs without errors and yet no data gets added in the db. Here's my views.py file from datetime import datetime from firstapp.models import Contact # Create your views here. def index(request): return render(request,'index.html',) def apply(request): return render(request,'apply.html') def about(request): return render(request,'about.html') def socials(request): return render(request,'social.html') def contact(request): if request.method == "POST": name = request.POST.get("name") email = request.POST.get("email") subject = request.POST.get("subject") message= request.POST.get("message") contact=Contact(name=name,email=email,subject=subject,message=message,date=datetime.today()) contact.save return render(request,'contact.html') here is my contact.html {% block title %}Contact {% endblock title %} {% block body %} <h2 align="center">CONTACT US </h2> <div class="container-md"> <form method="POST" action="/contact/"> {% csrf_token %} <div class="form-group"> <label for="exampleFormControlInput1">Name</label> <input type="text" class="form-control" id="exampleFormControlInput1" name="name" placeholder="John Smith"> </div> <div class="form-group"> <label for="exampleFormControlInput1">Email address</label> <input type="email" class="form-control" id="exampleFormControlInput1" name="email" placeholder="name@example.com"> </div> <div class="form-group"> <label for="exampleFormControlInput1">Subject</label> <input type="text" class="form-control" id="exampleFormControlInput1" name="subject" placeholder="Business | Suggestions | Query | Complaint | Other"> </div> <div class="form-group"> <label for="exampleFormControlTextarea1">Message</label> <textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="3"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> {% endblock body%} And here's my models.py from django.db import models # Create your models here. class Contact(models.Model): name = … -
Django not displaying Validationerror
I have problem with error in coding django not displaying validation error I dont know why django is not displaying the validationerror . Can you please help . Here is my form.py file this my form file where I have form and validation . django import forms from django.core import validators from new_app.models import Names`` from django.shortcuts import render from django.http import HttpResponse class Forms(forms.ModelForm): FirstName = forms.CharField(label='FirstName',widget=forms.TextInput(attrs={"placeholder":"your Name","rows":20,"column":100})) class Meta(): model = Names fields = '__all__' def clean(self): all_data = super().clean() firstname= all_data['FirstName'] lastname = all_data['LastName'] a = 1 if firstname in lastname: raise forms.ValidationError("amazing") return all_data Here is my view.py file this is my view file from django.shortcuts import render from new_app.models import Names from new_app import formss from django import forms # Create your views here. def index(request): a = Names.objects.all() dict = {'write':a} return render(request , 'index.html', context = dict) def register(request): second = formss.Forms() if request.method == 'POST': form = formss.Forms(request.POST) if form.is_valid(): form.save(commit=True) return index(request) else: second = formss.Forms() return render (request , 'forms.html', context = {'form':second} ) Here is my form.html template file ... <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <title>Login or Sign up</title> </head> <body> <div class="container"> … -
function querysets in django
i am trying to display 'searched item',which is watch in this case, but instead of that i am getting display screenshot my views.py file is as under from django.views.generic import ListView from django.shortcuts import render from shop.models import product # Create your views here. def searchproductview(request): allproducts= product.objects.filter(title__icontains = 'watch') #allproduct is a variable ,kuch bhi likh lo yaha,aage jo product likha hai ye model hai apna context= {'allproducts': allproducts} #variable pass hua hai bas return render(request, 'search/view.html', context) class searchproductview(ListView): template_name = 'shop/listview.html' def get_queryset(self,*args, **kwargs): request = self.request return product.objects.all() ''' -
Is possible to make django translations from a db?
I'm new with Django, and i know that with i18 you can translate from a file. But I want to edit this file later, and add content as a normal user. Is possible to make translations from a Database? -
How to dynamicly connect to the database from shell in Django
I have a django application instance running in pod. Now I need to test the connection to the different database, which is not included in settings.DATABASES Can I do this somehow using shell? -
Can i loop around a javascript code using Django for loops
Example of what i wanted to the javascript accomplish: torsos=document.querySelectorAll("#torsolavender, #torsogreen, #torsoblue, #torsoviolet"); how i tried to do the above: torsos=document.querySelectorAll("{% for color in colors %}#torso{{color.name}},{% endfor%}")