Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
POST http://localhost:8000/api/posts/action/ 400 (Bad Request) when working with React and Django
I am trying to build a full-stack app with React and Django. I am sending an API request from the Django server to React. This is my code how I do it: posts/component.js: import React, {useEffect, useState} from 'react' import { apiPostAction, apiPostCreate, apiPostList} from './lookup' export function PostsComponent(props) { const textAreaRef = React.createRef() const [newPosts, setNewPosts] = useState([]) const handleBackendUpdate = (response, status) =>{ // backend api response handler let tempNewPosts = [...newPosts] if (status === 201){ tempNewPosts.unshift(response) setNewPosts(tempNewPosts) } else { console.log(response) alert("An error occured please try again") } } const handleSubmit = (event) => { event.preventDefault() const newVal = textAreaRef.current.value // backend api request apiPostCreate(newVal, handleBackendUpdate) textAreaRef.current.value = '' } return <div className={props.className}> <div className='col-12 mb-3'> <form onSubmit={handleSubmit}> <textarea ref={textAreaRef} required={true} className='form-control' name='post'> </textarea> <button type='submit' className='btn btn-primary my-3'>Post</button> </form> </div> <PostsList newPosts={newPosts} /> </div> } export function PostsList(props) { const [postsInit, setPostsInit] = useState([]) const [posts, setPosts] = useState([]) const [postsDidSet, setPostsDidSet] = useState(false) useEffect(()=>{ const final = [...props.newPosts].concat(postsInit) if (final.length !== posts.length) { setPosts(final) } }, [props.newPosts, posts, postsInit]) useEffect(() => { if (postsDidSet === false){ const handlePostListLookup = (response, status) => { if (status === 200){ setPostsInit(response) setPostsDidSet(true) } else { alert("There was an … -
NoReverseMatch error . Reverse for '...' not found
I was trying to implement dynamic urls in Django when this occured In my template.py, I added this line <a href="{% url 'Index' %}" role="button">Go to Index</a> My urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("", include("moviez.urls")) ] My moviez.urls.py from django.urls import path from .views import IndexView app_name = "moviez" urlpatterns = [ path("", IndexView, name="Index") ] I think this should definitely should have work but it returned this error NoReverseMatch at / Reverse for 'Index' not found. 'Index' is not a valid view function or pattern name. Can you please help me debug this? Any help will be appreciated! -
Django: changes made to settings.py are ignored - Production - Gunicorn (with supervisor)
I have my Django application running on an Ubuntu server and I am using gunicorn and supervisor. From when I pulled the first version of the project from GitHub, all the changes made to the Settigs.py file are being ignored and the application is running with the first version of the settings file even after numerous pulls from GitHub. If I cd in my project directory and I view the settings.py file I can see that it is up to date, but all the changes it has got from the first upload are being ignored. I tried to restart supervisor with supervisorctl restart app_name but that doesn't resolve the issue. The app is still running with the first version of the settings.py file. I also made some research for a way to restart gunicorn and foun these commands: sudo systemctl daemon-reload sudo systemctl restart gunicorn sudo nginx -t && sudo systemctl restart nginx but when I run the second command I get this error Failed to restart gunicorn.service: Unit gunicorn.service not found. Any ideas to why all my changes to the settings.py file are being ignored? Thanks in advance. -
Customize Django login without creating custom user?
I am trying to create a Django login that will accept both email or username. I know that it is possible to do this by creating a custom user, but we have multiple applications already that reference the Django base user, so I would prefer to avoid having to go through and change all of those. I have a model that is strictly for the user profile, and includes a required, unique email field. Is there any way to customize the Django login to validate email against that user profile model so that I don't have to create a custom user? -
How to use parameter__contains with SearchRank at Django?
I want to use rank for ordering but also I need search with __contains for wide quering. How I can use contains with SearchRank ? vectors = SearchVector('title', weight='A') + SearchVector('title_english', weight='A') + SearchVector('content', weight='B') + SearchVector('content_english', weight='B') query = SearchQuery(value) articles = Article.objects.annotate( rank = SearchRank(vectors, query) ).filter(search__contains = 'rank', category=category).order_by('rank') -
How to get a list of cities in a country from database?
I have 2 models, City and Country. I want to show cities in the country on a page based on the country selected. I tried to query the Country model passing it to the City model to find all cities related to the country but currently, pages show all cities no matter what is the country. How I can show cities in one country when the user selects the country from the page? Any help or suggestions are highly appreciated. models.py class City(models.Model): country = models.ForeignKey('Country', on_delete=models.CASCADE, related_name='country') name = models.CharField(max_length=90, verbose_name='City name') slug = models.SlugField(null=True, unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('city:cities', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) return super().save(*args, **kwargs) class Country(models.Model): country_name = models.CharField(max_length=50, verbose_name='Country name',unique=True) slug = models.SlugField(null=True, unique=True) def __str__(self): return self.country_name def get_absolute_url(self): return reverse('city:cities', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.country_name) return super().save(*args, **kwargs) views.py class CountriesListView(ListView): template_name = "countries.html" model = Country context_object_name = "countries" class CitiesListView(ListView): template_name = "cities_list.html" model = City context_object_name = "cities" def get_context_data(self, *args, **kwargs): context = super(CitiesListView, self).get_context_data(*args,**kwargs) countries = Country.objects.all() cities = City.objects.filter(country__in=countries) context['cities'] = cities return context templates # countries.html <h1>Countries</h1> … -
Return ListView after post django
couldnt correct this issue after looking into for a longtime, Can anyone pls help me how to return exact same listview after the post class NewsletterList(FormMixin, generic.ListView): queryset = newsletter.objects.filter(status=1).order_by('-created_on') template_name = 'newsletterlist.html' form_class = SubscriberForm def post(self, request, *args, **kwargs): form = SubscriberForm(request.POST) if form.is_valid(): sub = Subscriber(email=request.POST['email'], conf_num=random_digits()) sub.save() return NewsletterList.as_view()(request, queryset=newsletter.objects.filter(status=1).order_by('-created_on'), template_name='newsletterlist.html', form_class = SubscriberForm) I am getting an error IntegrityError Exception Value: UNIQUE constraint failed: home_subscriber.email Thanks in advance -
Django property and function
If I have to use same property multiple time, what should be the alternative? As example, I need to use image property in product model as well as customer model. @property def imageURL(self): try: url=self.image.url except: url='' return url how can I do this without repeating the same property in multiple class? -
' No migrations to apply' after Django migration
I made a new app called 'contact' which I added to installed_apps, but I can't create a table in the SQLite database! Django version = 3.1 python manage.py makemigrations contact No changes detected in app 'contact' then for : python manage.py migrate contact Operations to perform: Apply all migrations: (none) Running migrations: No migrations to apply. I have tried many solutions proposed by members here but None worked like checking "init" file existed in migrations folder and it's empty or commands like these : python manage.py migrate --fake contact zero Operations to perform: Unapply all migrations: contact Running migrations: No migrations to apply. python manage.py migrate contact --fake-initial Operations to perform: Apply all migrations: (none) Running migrations: No migrations to apply. -
Django-Rest-Framework error: Field name 'product_name' is not valid for model 'Store'
In my Django Rest Framework API app, I am trying to add a field "product_name" in Product model, "product_name" field is not related to Store model as shown below: Models.py from django.db import models # Create your models here. class Store(models.Model): company_name=models.CharField(max_length=50) company_gst_no=models.CharField(max_length=200) class Product(models.Model): company_name=models.ForeignKey(Store, on_delete=models.CASCADE) product_name=models.CharField(max_length=200, null=True) class Purchase(models.Model): company_name=models.ForeignKey(Store, on_delete=models.CASCADE) p_n=models.ForeignKey(Product, on_delete=models.CASCADE) purchase_rate=models.IntegerField(null=False) purchase_quantity=models.IntegerField(null=False) serializers.py # api/serializers.py from rest_framework import serializers from .models import * class StoreSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Store fields = ['url','id','company_name', 'company_gst_no'] class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Store fields = ['url','id', 'product_name'] class PurchaseSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Store fields = ['url','id','company_name'] views.py from django.shortcuts import render from rest_framework import generics, viewsets from .models import * from .serializers import * # Create your views here. class StoreList(viewsets.ModelViewSet): queryset = Store.objects.all() serializer_class = StoreSerializer class Product(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer class Purchase(viewsets.ModelViewSet): queryset = Purchase.objects.all() serializer_class = PurchaseSerializer Error is "ImproperlyConfigured at /product/" "Field name product_name is not valid for model Store." -
Django Celery cannot query postgres db inside task
In my celery task I try to query my postgres db. But I always get following error: task.py @shared_task(bind=True) def ImportFiles(self, activity_file_list, user_id_list,activityfile_id,file_type_list): print('Task ImportFiles started') myuser = User.objects.get(pk=user_id_list[0]) print("USER:") print(myuser) settings.py INSTALLED_APPS = [ ... 'celery', ... ] ... DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'geodjango', 'USER': 'postgres', 'PASSWORD': 'postgres', }, } ... CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379' celery.py # Default settings from celery tutorial: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'geodjango.settings') app = Celery('geodjango', broker='redis://localhost') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) Following easy scenario works: If I change my task.py and execute just a simple for loop. task.py @shared_task(bind=True) def ImportFiles(self, activity_file_list, user_id_list,activityfile_id,file_type_list): print('Task ImportFiles started') progress_recorder = ProgressRecorder(self) result = 0 seconds = 10 for i in range(seconds): print("for: " + str(i)) time.sleep(1) result += i progress_recorder.set_progress(i + 1, seconds, description="Downloading") print("FOR LOOP FINISHED") return 'Task Complete' Celery output: So it looks like celery is working, but somehow I cannot make querys to my postgres db. I'm devolping currently on a windows machine... Can someone please help me? -
How to filter django rest framework serializers's drowp down items?
I want to assign Tasks to only the staffs. Therefore, I want my dorpdown list should only show the users that have a role of is_staff = True. But my drop down list now shows all the users (Superuser, Authority, General_user) that are available in the database. How to modify this to only show staffs in the drop down list which should only show two users since I've assigned two users with staff role...? My Model Classes: Custom-User Model: class User(AbstractBaseUser, PermissionsMixin): """ Responsible for handleing App user's data """ email = models.EmailField(max_length=255, unique=True) nid = models.CharField(max_length=30, unique=True) username = models.CharField(max_length=20, blank=True, null=True) date_of_birth = models.DateTimeField(blank=True, null=True) first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) image = models.FileField( upload_to=FileManager.photo_path, null=True, blank=True) is_active = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_authority = models.BooleanField(default=False) is_specialist = models.BooleanField(default=False) is_general_user = models.BooleanField(default=False) timestamps = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) objects = user_manager.UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['nid'] Tasks Model class Task(BaseAbstractModel): ''' Responsible for Storing and Providing Tasks data ''' assignment = models.ForeignKey(Assignment, on_delete=models.DO_NOTHING, related_name='+') assigne_to = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='+') task_name = models.CharField(max_length=300) is_done = models.BooleanField(default=False) created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='created_by') Serializer: class TaskListSerializer(serializers.ModelSerializer): ''' Will be serializing Task's data ''' … -
How to access static files in subfolders?
fellows! I have problems with static files. I still don't understand how this really works. Problem is that when I try to keep files in subfolder of the app folder, Django returns 404. Folders structure: /static/ product/ images/ img.png I am trying to access img.png in html template like this: <img src="{% static "product/images/img.png" %}"> But 404 error is returned. If I move img.png to the parent folder: /static/ product/ img.png images/ And use this root: <img src="{% static "product/img.png" %}"> All works fine. This is my Settings.py: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'review', 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'review', 'static') STATIC_URL = '/static/' STATICFILES_FINDERS = ['compressor.finders.CompressorFinder'] COMPRESS_PRECOMPILERS = (('text/x-scss', 'django_libsass.SassCompiler'),) COMPRESS_URL = STATIC_URL COMPRESS_ROOT = STATIC_ROOT What I should change so I can access static in the subfolders? -
what is super in this in this method?
class PublisherDetail(DetailView): model = Publisher def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books context['book_list'] = Book.objects.all() return context -
Is it possible to use ionic Capacitor with a Django application?
I have a Django application that loads a React app on a child page. Is it possible to use the ionic Capacitor with this setup? -
AWS_STORAGE_BUCKET_NAME is not read using django-environ
I was having troubles with enviroment variables, so decided to use django-environ. I've 3 settings files: base, development and production. Now I'm testing development, using our Amazon S3 storage settings. I've a base.py, from where the dev.py file copies everything. from .base import * In wsgi.py I've set my DJANGO_SETTINGS_MODULE to: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings.dev") Is this variable set everytime I run manage.py runserver? Trying to print this variable from console gives KeyError: print(os.environ['DJANGO_SETTINGS_MODULE']) Then when running: manage.py runserver I get: ImproperlyConfigured: Set the AWS_STORAGE_BUCKET_NAME environment variable base.py: import environ env = environ.Env() env.read_env(env.str('ENV_PATH', '.env')) AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME') Why? .env file has the bucket name (which is made up), just don't know why it won't read it: AWS_STORAGE_BUCKET_NAME = 'made-up-bucket-name' -
Exibir apenas segundo campo do field choises
Na minha model possuo uma lista de opção e quando exibo ela no template aparece assim: "("D", "Devagar",)" e gostaria que fosse exibido apenas "("Devagar")". Como é atualmente enter image description here Como deve ficar enter image description here Model.py from django.db import models from django.contrib.auth.models import User class Perfil(models.Model): vel = ( ("D", "Devagar",), ("N", "Normal"), ("R", "Rápido "), ("S", "Super Rapido (Cuidado!)"), ) velocidade = models.CharField(max_length=1, choices=vel, null=True, blank=True, verbose_name='Velocidade') views.py from django.shortcuts import render from .models import Perfil def account(request): user_id = request.user.id perfil = Perfil.objects.get(usuario_id=user_id) return render(request, 'core/account.html', {'nome': user_id, 'dados':perfil }) home.html <select class="form-control select2 select2-hidden-accessible" style="width: 100%;" data-select2-id="1" tabindex="-1" aria-hidden="true"> {% for opcao in dados.vel %} <option data-select2-id="{{opcao}}">{{ opcao }}</option> {% endfor %} </select> -
Is there are a way to handle multiple forms in Django?
I am trying to create a quiz application and can not figure out how do I store the answers to multiple questions? -
creating a folder automatically in Django for each user
So I am trying to create a folder automatically for each user in Django. What I tried: #Creating a folder automatically for each user def folder_path(instance, filename): return "user_{0}/MyFolder/{1}".format(instance.user.id, filename) # Create your models here. class MyModel(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, default= None) user_folder = models.FileField(upload_to= folder_path, default= None) views.py myfolder = MyModel(user_folder= '/path/to/folder/') I also tried: #Creating a folder automatically for each user def folder_path(instance, filename): user = instance.user.username basename, file_extension = filename.split(".") new_filename = "%s-%s.%s" %(user, instance.id, file_extension) return "MyFolder/%s/%s" %(user, new_filename) # Create your models here. class SLRModel(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, default= None) my_folder = models.FileField(upload_to= folder_path, default= None) views.py myfolder = MyModel(user_folder= '/path/to/folder/') I want to know why its not working. Thanks. -
Limiting one vote per user django
I have an Article model that has a votes IntegerField, I want to make so each time the user clicks the button, there is an ajax request to the vote view which increases the vote field by one. here is my Vote model: class Vote(models.Model): user = models.ForeignKey(Account,on_delete=models.DO_NOTHING) article = models.ForeignKey(Article,on_delete=models.DO_NOTHING) Vote function in views.py: @login_required def vote(request, article_id): article = get_object_or_404(Article, pk=article_id) vote, created = Vote.objects.get_or_create(article=article, user=request.user) if created: article.votes += 1 article.save() return JsonResponse(data = {"vote": "Voted! Thank you for the vote."}) return JsonResponse(data = {"vote": "You already voted for this article."}) The vote button: <button id="vote" class="button">vote</button> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script> $("#vote").click(function (e) { e.preventDefault() var upvotes = $("#total_votes").html() var updatedUpVotes = parseInt(upvotes) + 1 $("#total_votes").html(updatedUpVotes) $.ajax({ url: 'vote/', method: "GET", data: {}, success: function (data) { console.log(data) }, error: function (error) { console.log(error) } }) }) </script> I tried to change it to POST, it doesnt matter. I took the code from here: Limiting voting per user django but it doesnt work. Thank you in advance😀 -
Django IntegrityError while Connecting two models
I am trying to build a bug reporting application. The application enables visitors to register and then select a project and then they can report a bug. Bud Report app's files: Models.py class Bug(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) bug_title = models.CharField(max_length=150) bug_description = models.TextField() screenshot = models.ImageField(blank=True, null=True, upload_to='Bug_Reports') date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return 'Project: {}\nBug: {}'.format(self.project.title, self.bug_title) Forms.py from django import forms from .models import Bug class BugReportForm(forms.ModelForm): class Meta: model = Bug fields = ['bug_title', 'bug_description', 'screenshot'] Views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import BugReportForm def bug_register(request): if request.method == 'POST': form = BugReportForm(request.POST, instance=request.) if form.is_valid(): form.save() messages.success(request, f'Thankyou for Reporting! We will review your issue and revert back soon,') return redirect('home') else: messages.warning(request, f'Please fill all the mandatory fields!') else: form = BugReportForm() return render(request, 'bug_report/report.html', {'form': form}) I am able to render form. Everything works fine till I submit the form. I am kind of understanding the problem but unable to think of a solution as a beginner. Error:- django.db.utils.IntegrityError: NOT NULL constraint failed: bug_report_bug.project_id I understand that I am not passing the projec_id as I connected my Bug model to my Project model but I am unable … -
Django - Set initial selected value for formd.MultipleChoiceField
I want to display initial values as selected on a MultipleChoice form field in Django when the form loads. I populate a formset with different forms. Each form has only one field 'answer', which is initialized based on a custom parameter passed to the form's init() method. class AnswerForm(forms.Form): def __init__(self, *args, **kwargs): """ Initialize label & field :returns None: """ question = kwargs.pop('question') # A Question object super(AnswerForm, self).__init__(*args, **kwargs) if question.type == Types.RADIO: choices_ = [(op.id, op) for op in question.option_set.all()] self.fields['answer'] = forms.ChoiceField(label=question.statement, initial=1, widget=forms.RadioSelect, choices=choices_) elif question.type == Types.CHECKBOX: choices_ = [(op.id, op) for op in question.option_set.all()] self.fields['answer'] = forms.MultipleChoiceField(label=question.statement, initial=[1,3], widget=forms.CheckboxSelectMultiple, choices=choices_) This renders the following HTML: But it doesn't get into the form's cleaned_data. When I submit formset, the request.POST data goes into this view: def post(self, request, form_id): """ Process & save the responses obtained from a form into DB :param request: An HTTPRequest object :param form_id: form id whose responses arrive :returns HttpResponse object with a results template """ formset = FormHandler.AnswerFormSet(request.POST, request.FILES, form_kwargs={'questions': FormHandler.qs}) if formset.is_valid(): for form in formset: cd = form.cleaned_data # Access cd['answer'] here but cd appears to be empty dict {} # with no key named 'answer' … -
Why am I getting NoReverseMatch error with no arguments found?
Error: NoReverseMatch at /leachers/11/donate/ Reverse for 'donate' with no arguments not found. 1 pattern(s) tried: ['leachers/(?P[0-9]+)/donate/$'] Error here views.py @login_required def donate(request,pk): if request.method == 'POST': form = forms.UserDonateForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.donator = request.user user.save() return redirect('leacher_list') else: form = forms.UserDonateForm() return render(request,'my_app/donation_form.html',{'form':form}) urls.py from django.urls import path from . import views from .views import donate urlpatterns = [ path('',views.HomePageView.as_view(),name='home_page'), path('about/',views.AboutView.as_view(),name='about'), path('leachers/',views.LeacherListView.as_view(),name='leacher_list'), path('leachers/<int:pk>/donate/',donate,name='donate'), ] here I am assigning pk to link: {% for member in leacher_list %} <h4>Name : {{ member.name }}</h4> <h5>Address : {{ member.address }}</h5> <h5>Location : {{ member.location }}</h5> <!--original href="donate" --> <a class="btn btn-primary" href="{% url 'donate' pk=member.pk %}" role="button">Donate</a> I am new to django,kindly help me,I am stuck with this for a long. -
Can I deploy my Django application only using nginx or Gunicorn?
I knew that for deploying a Django application we have to use a combination of uWSGI + Nginx or Nginx + Gunicorn server. Is that necessary? I have a small doubt here. Can we deploy the entire application only in Nginx or only in Gunicorn? Will, it not work? Just for an example(leaving production) can't I do that? -
Why do I get an error when running production server in django
The this kinda problem I face, in django Thing is finished making django site and wanna deploy to heroku But there is a catch testing production server locally, at browser load time it gives me the error Bad Request I really wanna deploy it to heroku but I don't know how to solve the error This error doesn't show in the development version of the site Answer will be appreciated