Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MultiValueDictKeyError at /update 'date'
I'm trying to update my database but I encountered MultiValueDictKeyError. The problem is triggered by 'date' as: t.date = request.POST.get('date') I tried print(request.POST) with the result: <QueryDict: {'csrfmiddlewaretoken': ['9mgfDaQRsH4Pv5rvglufS3wC61QDL5i9tcOqmBQwNFAKFpzE79h9wBY8St9CwBsB'], 'ID_number': ['4'], 'date_month': ['1'], 'date_day': ['1'], 'date_year': ['2020'], 'first_name': ['Gedo'], 'last_name': ['Prasad'], 'Membership_Start_date_month': ['1'], 'Membership_Start_date_day': ['1'], 'Membership_Start_date_year': ['2020'], 'Membership_End_date_month': ['4'], 'Membership_End_date_day': ['1'], 'Membership_End_date_year': ['2020'], 'member_type': ['Gym&Sauna'], 'payment_type': ['3 Month'], 'rate': ['23'], 'paid': ['20'], 'due': ['3'], 'Contact_number': ['1121212129'], 'Email': ['gedo@pzrasad.com'], 'Remarks': ['gsa']}> Notice that the date field gives 'date_month', 'date_day', 'date_year' separately. Maybe that's the problem. But I don't know the answer. Any suggestions would be very helpful as I am a student and a beginner. Here is my models.py: class Member(models.Model): ID_number = models.IntegerField() date = models.DateField(verbose_name='date') first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) member_type = models.CharField( max_length=30, choices=MEMBERSHIP_CHOICES, ) payment_type = models.CharField( max_length=30, choices=PAYMENT_TYPE_CHOICES, ) Membership_Start_date = models.DateField(verbose_name='Membership_Start_date') Membership_End_date = models.DateField(verbose_name='Membership_End_date') rate = models.IntegerField() paid = models.IntegerField() due = models.IntegerField() Contact_number = models.CharField(max_length=14) Email = models.EmailField() Remarks = models.CharField(max_length=255, blank = True, null = True) def __str__(self): return str(self.ID_number) + " " + self.first_name + " " + self.last_name -
ImportError: cannt import name Httpresponse in django
demo.py from django.http import Httpresponse def index(request) : return Httpresponse("Hello") I am checking HttpResponse, HTTPResponse instead of Httpresponse.. but couldn't slove the problem..i am new in python so please tell me what's wrong in that.. Thank You in advance! -
TabError inconsistent use of tabs and spaces in indentation
views.py from django.shortcuts import render from django.http import HttpResponse from .models import * def home(request): return render(request, 'dashboard.html') def products(request): products=product.objects.all() return render(request,'products.html', {'products':products}) def customer(request): return render(request, 'customer.html') The error: from . import views File "/Users/dileepkumar/Desktop/dj/accounts/views.py", line 12 return render(request,'products.html', {'products':products}) ^ TabError: inconsistent use of tabs and spaces in indentation -
ModuleNotFoundError: No module named 'MyProject'
I'm collaborating with a group for an assignment we decided to use Django for, however, it seems that if one individual used upercase characters instead of lowercase characters (MyProject vs myproject) for example and therefore I often times get an error indicating ModuleNotFoundError: No module named 'MyProject' I've changed it before & resolved it and then pushed it up to GitHub.. but every so often we encounter the same issue. How can I fix this permanently so that it's no longer an issue? -
How to use CSS on the Django ModelForms?
I'm developing a small app and using Django ModelForms. I'm unable to provide any kind of styling to the form. Can someone tell me if there is a way to customize this form? My current form display My current template {% extends 'base.html' %} {% block content %} <!--begin::Portlet--> <div class="kt-portlet"> <div class="kt-portlet__head"> <div class="kt-portlet__head-label"> <h3 class="kt-portlet__head-title"> New Customer </h3> </div> </div> <!--begin::Form--> <form class="kt-form"> <div class="kt-portlet__body"> <div class="form-group"> {{ form }} </div> </div> <div class="kt-portlet__foot"> <div class="kt-form__actions"> <button type="submit" class="btn btn-primary">Submit</button> <button type="reset" class="btn btn-secondary">Cancel</button> </div> </div> </form> <!--end::Form--> </div> <!--end::Portlet--> <h2>New Customer</h2> <form method="POST" class="kt-form">{% csrf_token %} {{ form }} <button type="submit" class="save btn btn-default">Add Customer</button> </form> {% endblock %} -
OperationalError at /admin/accounts/userstripe/ no such table: accounts_userstripe, why is it throwing an error even after migrations?
I'm trying to develop a website for an online store, and after creating and registering models, I don't know why, this error is thrown. What can I do? And also after running the migrate command, it is saying no migrations to apply. Can anyone please help me with this? My models.py: from django.db import models import stripe from django.conf import settings from django.contrib.auth.signals import user_logged_in stripe.api_key = settings.STRIPE_SECRET_KEY class UserStripe(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_id = models.CharField(max_length=120) def __unicode__(self): return str(self.stripe_id) def get_or_create_stripe(sender, user, *args, **kwargs): try: user.userstripe.stripe_id except UserStripe.DoesNotExist: customer = stripe.Customer.create( email = str(user.email) ) new_user_stripe = UserStripe.objects.create( user = user, stripe_id = customer.id ) except: pass user_logged_in.connect(get_or_create_stripe) -
FlowRuntimeError viewflow django
Really need you guys help here! Im currently using viewflow to construct my workflow on a django project. I wish to integrate django-jsignature3 with django-viewflow , however i have met with extreme difficulty in doing so. The documentations for viewflow is really confusing and the demo projects dont really have explanations so please be patient with me if what im asking is a dumb question. The error code is as shown below FlowRuntimeError Here is the error trace back on my cmd: raise FlowRuntimeError('Activation metadata is broken {}'.format(self.management_form.errors)) viewflow.exceptions.FlowRuntimeError: Activation metadata is broken <ul class="errorlist"><li>started<ul class="errorlist"><li>This field is required.</li></ul></li></ul> [04/Apr/2020 20:24:48] "POST /pipeline/20/approve1/57/ HTTP/1.1" 500 103532 Here is my code: flows.py class Pipeline(Flow): process_class = PaymentVoucherProcess start = flow.Start( CreateProcessView ).Permission( auto_create=True ).Next(this.approve1) approve1 = flow.View( PreparerSignature, ).Next(this.check_approve1) check_approve1 = flow.If( cond=lambda act: act.process.approved_preparer ).Then(this.approve2).Else(this.end) approve2 = flow.View( VerifierSignature, ).Next(this.check_approve2) check_approve2 = flow.If( cond=lambda act: act.process.approved_verifier ).Then(this.delivery).Else(this.end) delivery = flow.View( UpdateProcessView, form_class=DropStatusForm ).Permission( auto_create=True ).Next(this.report) report = flow.View( UpdateProcessView, fields=["remarks"] ).Next(this.end) end = flow.End() views.py @flow_view def PreparerSignature(request, **kwargs): #this prepare statement might be the cause of the error request.activation.prepare(request.POST or None, user=request.user) form = PreparerSignatureForm(request.POST or None) if form.is_valid(): esig = form.save(commit=False) signature = form.cleaned_data.get('signature') if signature: signature_picture = … -
Django: How to generate weeks of month (starting from first day of month to next friday), then from saturday to next friday till the month ends?
I am working on a Django Project, which consists of forecasting the coming Accounts Payable (AP) and Accounts Receivable (AR). However, I stumbled across a problem as I do not know how to generate the weeks of a particular month. For example, for the month of April, I would like the dates to be split into: 01/04/20 - 10/04/20 (next friday), 11/04/20 - 17/04/20 (the friday after that) and so on and so forth. Within each week, a field 'amount' would be added up to show the total amount expected to pay/receive during that week. Here is my code thus far, and I managed to group the query sets by months, and the 'amount' field by months. However, I am not too sure how to group it by weeks of a month, as Django's ExtractWeek function works on a per-year basis. views.py class APView(LoginRequiredMixin,CreateView): model = AP form_class = APForm template_name = 'cash/ap.html' def get_context_data(self, **kwargs): context = super(APView, self).get_context_data(**kwargs) time_range = [] done = False time = self.kwargs['time'] start = int(self.kwargs['start']) end = int(self.kwargs['end']) context['bp'] = BusinessPartners.objects.prefetch_related('ap_set').all() context['ap'] = BusinessPartners.objects.annotate(timeline=Extract('ap__due_date', time)).values('timeline').annotate(total=Sum('ap__amount')).values('timeline','total', 'bp_name') while not done: time_range.append(start) if start == end: done = True break start += 1 context['timeline'] = … -
Is there any other better method for Overriding Model Serializer Update Method
I am created a model Serializer and overriding the methods .But in this case I need to save each serializer object one by one .... I am checking is there any other methods class PetSerializer(ModelSerializer): class Meta: model = Pet exclude = ['name', 'categoty','color','food'] def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.categoty = validated_data.get('categoty', instance.categoty) instance.color = validated_data.get('color', instance.color) instance.food = validated_data.get('food', instance.food) instance.save() In this case If I am having 10 fields I need to save one by one right ? Is there any other better way to handle this ? -
why i get error when i want to load html file in js in django project?
I want to load HTML file in Js file in django,but i get this error: Not Found: /login.html there is this file in templates folder! $(document).ready(function () { $('#load_').load('login.html') }); -
NameError at /register/ name 'cleaned_data' is not defined
I am developing a register form for my site and when I fill in the form I receive the error "NameError at /register/ name 'cleaned_data' is not defined" this is what I have: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'password1', 'password2' ) def save(self, commit=True): user = super(UserRegisterForm, self).save(commit=False) user.first_name = cleaned_data['first_name'] user.last_name = cleaned_data['last_name'] user.email = cleaned_data['email'] if commit: user.save() return user class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] -
Not sure how to execute complex Query with Django
I'm stuck on a query I'm trying to execute. I have attached an image of the datamodel below. Essentally, I got 6 tables with various relations. Here's a quick summary: One User can have many Projects, and each Expense is tied to a specific project Each project can have many users, and each user can have many projects, put together through a joined table - UserProject To indicate the level of access a user has to a specific project, a field called role is added to the UserProject table - a user can either be a member or an admin of a project The query I wish to construct is to fetch all expenses that are created by the logged in user (request.user) and all expenses of all projects where the user has the role of admin from the UserProject table. See image of data model below: Any idea how I would proceed with that query? -
Is it possible in Django to call custom `QuerySet` method on reverse related object lookup?
E.g. there are next models and custom QuerySet: from django.db import models class ActiveQuerySet(models.QuerySet): def active(self): '''returns only active objects''' '''supposing here would be a lot of more complicated code that would be great to reuse ''' return self.filter(is_active=True) class Category(models.Model): name = models.CharField(max_length=128, blank=True, null=True, default=None) class Product(models.Model): name = models.CharField(max_length=128, blank=True, null=True) is_active = models.BooleanField(default=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, related_name='products', related_query_name="product", blank=True, null=True, default=None) objects = ActiveQuerySet.as_manager() Could you tell me if there is a way to call the active() method like this: category = Category.objects.first() category.products.active() instead of doing like this: category.products.filter(is_active=True) Or how to implement appropriately such behavior? -
How to fetch total selected radio buttons in Django?
{% csrf_token %} {% for field in all %} {{field.ques}}<br> <input type="radio" name="field{{field.id}}">{{field.option1}}<br> <input type="radio" name="field{{field.id}}">{{field.option2}}<br> <input type="radio" name="field{{field.id}}">{{field.option3}}<br> <input type="radio" name="field{{field.id}}">{{field.option4}}<br> <br> {% endfor %} Here is my views.py if request.method=='POST': for field in range(len(correctOption)): selected.append(request.POST.get(????)) I am storing all selected options in a list, what should i write in request.POST.get() -
How do i implement a movie Recommender?
First of all I apologize if posting such thing is against the rules here, but I did a Google research, and actually did lots of it, however couldn't get the answer I wanted and wouldn't know where to post it. I want to create a recommender system in the form of an online application, similar to this, I even bought the Practical Recommender Systems book by Kim Falk which goes along the GitHub repo. however, I just couldn't get it working. I tried implementing my own solution using Django, however even the slightest computationally intensive tasks slowed the web application to a crawl! To be honest I am confused, and I want someone to steer me in the right direction. Is Django a good option for the application framework?Which Movie Dataset should I use? MovieLens 100K? Or MovieTweetings 100K? I currently structure my app in the following way: project_name (My top level project directory) movies_app (An app that handles the Movie model, and views for homepage + movies catalog + movie details page) accounts_app (An app that handles the custom User model, and views for profile management + register + login) recommender_app (An app that handles all of the recommendation … -
Hello everybody, how can I easily remove an information from a url
my users will be redirected to my site with some information like this http://127.0.0.1:8000/accounts/dasbboard/?trxref=621538940cbc9865e63ec43857ed0f&reference=621538940cbc9865e63ec43857ed0f using urllib will get give me query='trxref=621538940cbc9865e63ec43857ed0f&reference=621538940cbc9865e63ec43857ed0f' But I'm no okay with that, I want to be able to get the number after the reference(621538940cbc9865e63ec43857ed0f), what is the best way to do it in my view? thank you in advance. -
Docker and POSTGRESQL
I create new project using Docker on Django. when I write settings to connect to Postgres it has some Error - (conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "db" to address: nodename nor servname provided, or not known) Thats my code in project : settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432 } } docker-compose.yml version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 environment: POSTGRES_DB: "db" POSTGRES_HOST_AUTH_METHOD: "trust" and Dockerfile: # Pull base image FROM python:3.7 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ RUN pip install psycopg2-binary Please help to decide this problem.I read a lot information on stackoverflow about it.Changed code.But nothing to help me in this situation. -
I work on class,subject,chapter and question templating in django . now I have to get data in template foreign key in question to chapter to subject
My model is : class classes(models.Model): name = models.CharField(max_length=100) image = models.FileField(upload_to="class/",blank= True) class subject(models.Model): name = models.CharField(max_length=100) image = models.FileField(upload_to="subject/",blank= True) class classsubject(models.Model): name = models.CharField(max_length=100,blank= True) subject = models.ForeignKey(subject, on_delete=models.CASCADE) classes = models.ForeignKey(classes, on_delete=models.CASCADE) class chapter(models.Model): name = models.CharField(max_length=100,blank= True) class subjectchapter(models.Model): name = models.CharField(max_length=200,blank= True) chapter = models.ForeignKey(chapter, on_delete=models.CASCADE) classsubject = models.ForeignKey(classsubject, on_delete=models.CASCADE) class question(models.Model): subjectchapter = models.ForeignKey(subjectchapter, on_delete=models.CASCADE) here have template code of subject: <div class="owl-item language_item"> <a href="#"> <div class="flag"><img src="images/bangla.svg" alt=""></div> <div class="lang_name">***{{subject.name}}***</div> </a> </div> here will be the chapter from releted subject and question from releted chapter <div class="teacher d-flex flex-row align-items-center justify-content-start"> <div class="teacher_content"> <div class="teacher_name">***{chapter.name}***</div> <div class="teacher_title"><a href="instructors.html">***{question.name}***</a></div> <div class="teacher_title"><a href="instructors.html">আমরা পড়ার সময় কি করি?</a></div> <div class="teacher_title"><a href="instructors.html">আমরা খেলার সময় কি করি?</a></div> <div class="teacher_title"><a href="instructors.html">অ দিয়ে শব্দ কোনটি?</a></div> </div> </div> so now how i get the data of subject and chapter name in template in one view and in one page in html I need subject in releted class with releted chapter in a subject please give me the view and template code NB: here will be the data -
Django blocktrans problems with rendered variables
I have already translated in this project in the same way a number of similar templates in the same directory, which are nearly equal to this one. But this template makes me helpless. Without a translation tag {% blocktrans %} it properly works and renders the variable. c_filter_size.html {% load i18n %} {% if ffilter %} <div class="badge badge-success text-wrap" style="width: 12rem;"">{% trans "Filter sizing check" %}</div> <h6><small><p class="p-1 mb-2 bg-info text-white">{% trans "The filter sizing is successfully performed." %} </p></small></h6> {% if ffilter1 and ffilter.wfsubtype != ffilter1.wfsubtype %} <div class="badge badge-success text-wrap" style="width: 12rem;"">{% trans "Filter sizing check" %}</div> <h6><small><p class="p-1 mb-2 bg-info text-white"> If you insist on the fineness, but allow to reduce flow rate up to {{ffilter1.flowrate}} m3/hr the filter size and therefore filter price can be reduced. </p></small></h6> {% endif %} with a translation tag {% blocktrans %} it works neither in English nor in the translated language for the rendered variable. Other similar templates smoothely work. c_filter_size.html {% load i18n %} {% if ffilter %} <div class="badge badge-success text-wrap" style="width: 12rem;"">{% trans "Filter sizing check" %}</div> <h6><small><p class="p-1 mb-2 bg-info text-white">{% trans "The filter sizing is successfully performed." %} </p></small></h6> {% if ffilter1 and ffilter.wfsubtype … -
How to use django-taggit with custom html forms?
Many of you might have thinking that it is replication but believe me it is not. Nothing has answered my query. My major issue is I have nothing to do with "Forms.py". I have my own html templates and I am not getting how to successfully deploy django-taggit with it. My relevant code so far for you to look at: (models.py) from taggit.managers import TaggableManager class data(models.Model): user_id = models.IntegerField(null=False) title = models.CharField(max_length=200) description = models.CharField(max_length=200, null=True) tags = TaggableManager() (views.py) from taggit.models import Tag def add_data(request): if request.method == 'POST': id = request.user.id tags = request.POST["tags"] dress = Dress.objects.create(user_id = id, title = request.POST.get('title'), description = request.POST.get('description')) dress.save() for tag in tags: dress.tags.add() Everything is quite clear. I have observer that taggit has created two tables in db named, "taggit_tag" and "taggit_taggeditem". When I run the system, tags gets save in "taggit_tag" but nothing comes in "taggit_taggeditem". So for the reason when I try to show tags associated to certain data, I gets nothing. (views.py) def view_data(request, id): data= Data.objects.get(id = id) tags = Dress.tags.all() print("------content-------") print (tags) data = {"data": data, "tags":tags} return render(request, 'view.html', data) Empty query set appears when I print it. I believe my understanding … -
how to check for valid input django admin
I have models arranged like this, ModelA(models.Model): quantity = PositiveIntegerField(default=0, validators=[MinValueValidator(0)]) ModelB(models.Model): quantity = models.PositiveIntegerField() modela = models.ForeignKey(ModelA) And I have a signal that updates the quantity of ModelA every time modelB is updated. @receiver(post_save, sender=ModelB) update_quantity(instance, sender, **kwargs) When I do something like qty = instance.modela.quantity qty -= instance.quantity In a case the value becomes negative number, example in ModelA the quantity was 5 and I removed 6 from ModelA using ModelB quantity field ModelA raises a Validation error which is fine, My problem is how to parse that into the form of ModelB without the Error page. Being shown. I'm using the django admin for adding and editing. -
Is there a way in Django to test if a Cookie sent in request.META or request.COOKIES is httpOnly?
As the title suggests, I don’t think this is possible in Django:latest as of the time if writing, but is it possible to detect if a Cookie sent up in the request.HEADERS is httpOnly? -
Unable to remove callbacks in Bokeh Server (ValueError: callback already ran or was already removed, cannot be removed again)
I'm using Bokeh Server with Django to animate some charts that shows multiple series changing over time. I'm currently trying to automate the slider to progress the time series. Unfortunately I am experiencing two issues (that are probably related). The first is that the although the animation starts (the slider moves and 'play' changes to 'pause' on the button), the chart is not updated. The second is that any attempt to stop the slider (clicking on the 'pause' button) raise the error: ValueError: callback already ran or was already removed, cannot be removed again The slider continues to move. Django is making a request to the server for a server_document, passing 'pk' as an argument: views.py from django.shortcuts import render from django.http import HttpResponse from bokeh.embed import server_document def getchart(request, pk): key = pk script = server_document(url="http://localhost:5006/bokeh_server", arguments={"pk": pk, }, ) return render(request, 'testserver.html', {'script':script}) The bokeh server receives the request, finds the data associated with 'pk' then builds a chart with animation. main.py from bokeh.io import curdoc from copy import deepcopy from bokeh.plotting import figure from bokeh.embed import components from bokeh.models import ColumnDataSource, Slider, Button from bokeh.models.widgets import TableColumn from bokeh.layouts import column, row """ Get arguments from request … -
Separate Containers for Django, nginx and Postgres deployment
I want to deploy a website in completely isolated containers environment. Here are my requirements: A separate container for nginx and Let's encrypt certificate A separate container for PostgreSQL or MySql A separate container for Python/Django files Please guide me how can I achieve it. I searched over the web and I found most of the guys deploying nginx and Django files in same container which I don't need. Also, when I deploy nginx and Django in separate containers, how can I server the Static files? Thank you very much to everyone who contributes to it. Regards, Sharon -
Cart Item and Cart are not updadting properly
Here I created two models first one CartItem for the products that will be added to the CartItem and and if that product exists in the CartItem the quantity of the existing product will be updated. And the second model Cart that will store all the CartItem in that Cart Now the first issue that I am getting is - When the first product is added to the CartItem it is saved as 1 of test_product1. Now when I add the same product again its quantity is updated as 2 of test_product1. Its fine till here. I have 2 of those product. Now when I add the same product again, it's saved as 2 of test_product1. A new CartItem is created after I try to add more than 2 of the same prduct, it just keeps on creating new ones and saves it as 2 of test_product1 The second issue is when I add products to the CartItem the Cart is updated and saves all the CartItem. But when I change the product quantity, say removed or added 1 one. The total of the Cart doesn't change. Let me explain little better. a) I click Add to Cart -> the …