Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
403 error when using daphne , nginx and gunicorn
im new to nginx , have been facing issues for the past few days trying to implement it in my project and will really need your help here. Before anyone downvotes this , i would like to say that i have tried several of the methods other people have and it does not seem to help. I am able to access port 8001 to my website , but not 8000 as it will throw me a 403 error. The following error was extracted from home/user/proj/venv/logs/nginx-error.log : 2020/03/06 14:04:38 [error] 965#965: *1 "/usr/share/nginx/html/login/index.html" is not found (2: No such file or directory), client: 192.168.8.30, server: 192.168.8.31, request: "GET /login/?next=/ HTTP/1.1", host: "192.168.8.31:8000" 2020/03/06 14:05:46 [error] 1608#1608: *1 "/usr/share/nginx/html/login/index.html" is not found (2: No such file or directory), client: 192.168.8.30, server: 192.168.8.31, request: "GET /login/?next=/ HTTP/1.1", host: "192.168.8.31:8000" Here is some of my configurations: Inside my nginx config file /etc/nginx/sites-available/project.conf: upstream app_server { server unix:/home/user/project/venv/run/gunicorn.sock fail_timeout=0; } server { listen 8000; # add here the ip address of your server # or a domain pointing to that ip (like example.com or www.example.com) server_name 192.168.8.31; keepalive_timeout 5; client_max_body_size 4G; access_log /home/user/project/venv/logs/nginx-access.log; error_log /home/user/project/venv/logs/nginx-error.log; location /static/ { alias /home/opsadmin1/project/project/staticfiles/; } # checks for static … -
Problem with Django form wizard while creating a user
I am trying to create a two step user creation form with the help of django wizard form, I have a image filed which goes to profile model and all the other data goes to the default user model is this the right way of doing it or i should create a single model for everything. Don't exactly know what i did wrong. I suspect my second form do not know for which user it should save the data. I am a noob so guys please help me out. models.py from django.db import models from django.contrib.auth.models import User from PIL import Image # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, default=None, null=True, on_delete=models.CASCADE) profilePic = models.ImageField(default='default.png', upload_to='profilePics') def __str__(self): return self.user.username def save(self): super().save() img = Image.open(self.profilePic.path) if img.height > 500 or img.width > 500: outputSize = (500,500) img.thumbnail(outputSize) img.save(self.profilePic.path) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from formtools.wizard.views import SessionWizardView from .models import Profile class UserRegisterForm(UserCreationForm): email= forms.EmailField(required=True ,max_length=100,widget= forms.TextInput(attrs={'placeholder':'jane@example.com'})) class Meta: model = User fields = ['username', 'email', 'password1' ] widgets = { 'username': forms.fields.TextInput(attrs={'placeholder': 'the_jane'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self.fields['password2'] class UserDetialsForm(forms.ModelForm): firstName = forms.CharField(required=True, … -
Extra field is not showing in registration form in django
Fullname input is not showing in registration page.And also theplaceholder other than username doesnt appear User is supposed to enter full name while registration.Talking about other fields user can enter it later models.py:- class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=30,blank=False,null=False) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10,blank=True) def __str__(self): return self.fullname Forms.py:- class SignUpForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ['username','password1','password2','email'] widgets = { 'username' : forms.TextInput(attrs = {'placeholder': 'Username'}), 'email' : forms.TextInput(attrs = {'placeholder': 'E-Mail'}), 'password1':forms.TextInput(attrs = {'placeholder': 'Password'}), 'password2':forms.TextInput(attrs = {'placeholder': 'Re-Enter Password'}) } class ExtraField(forms.ModelForm): fullname = forms.CharField(max_length=40) class Meta: model = Profile fields = ['fullname'] views.py:- def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) profile_form=ExtraField(request.POST) if form.is_valid() and profile_form.is_valid(): user = form.save() profile = profile_form.save(commit=False) profile.user=user profile.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user =authenticate(username=username,password=password) login(request,user) return redirect('home') else: form = SignUpForm() profile_form=ExtraField() context = {'form':form,'profile_form':profile_form} return render(request, 'users/register.html', {'form': form}) -
Direct assignment to the reverse side issue with multiple nested serializer
I have this issue while running some test on my django project: TypeError: Direct assignment to the reverse side of a related set is prohibited. Use files.set() instead. Here is what I try to post { "daily_hash": "w54c6w546w5v46w5v4", "modules": [ { "module": "main", "commits": [ { "commit_hash": "11feb543f016114c700046d42b912910321230da", "author": "Test name 1", "subject": "[TICKET] Subject of the issue", "files": [] }, { "commit_hash": "093b19f710c6d2358b0812434dfcf1549c9c6fbb", "author": "Test name 1", "subject": "[TICKET] Subject of the issue", "files": [] } ] }, { "module": "submodule", "commits": [ { "commit_hash": "dce22dea52a6a4b7160034d3f84a7af7b389ee96", "author": "Test name 3", "subject": "[TICKET] Subject of the issue", "files": [ { "name": "my_file_1.c" }, { "name": "my_file_2.c" } ] }, { "commit_hash": "cee433fc4ab46464afb96d6ecae2839409fe0313", "author": "Test name 4", "subject": "[TICKET] Subject of the issue", "files": [] }, { "commit_hash": "4534f511b2a6a8c1632a1ab97b598d8e4dedada7", "author": "Test name 1", "subject": "[TICKET] Subject of the issue", "files": [] } ] } ] } You can find below my models.py: from django.db import models from status.models import Daily class Component(models.Model): """ Component model """ module = models.CharField(max_length=40) daily = models.ForeignKey(Daily, on_delete=models.CASCADE) class Meta: db_table = 'gds_component' class Commit(models.Model): """ Commits model """ commit_hash = models.CharField(max_length=40) author = models.CharField(max_length=60) subject = models.CharField(max_length=250) component = models.ForeignKey( Component, related_name='commits', on_delete=models.CASCADE) class Meta: … -
Can't assign field in form_valid method, Not null constraint Error
I'm getting the error: IntegrityError at /projects/1/issues/new/ NOT NULL constraint failed: issues_issue.project_id Request Method: POST Request URL: http://127.0.0.1:8000/projects/1/issues/new/ Django Version: 3.0.3 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: issues_issue.project_id Issues have a Foreign key to project, and I assign it in the form_valid method, I do the same with the user and that works fine CreateView in views.py: class IssueCreateView(LoginRequiredMixin, CreateView): model = Issue fields = ['title', 'details', 'priority', 'status', 'estimated_work_hours', 'loaded_work_hours'] def form_valid(self, form): form.instance.project = get_object_or_404(Project, pk=self.kwargs['project_id']) print(form.instance.project) form.instance.creator = self.request.user return super().form_valid(form) The line print(form.instance.project) prints the correct project, so that's working. models.py: class Issue(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) creator = models.ForeignKey(User, related_name="%(class)ss_created", on_delete=models.CASCADE) ... ... Why can I assign the creator field to an user in the form_valid method but when I do the same thing for the Project field it doesn't work, I don't understand it. Does anyone know what could be the problem? Thanks -
Error while trying to redirect 404 requests to home page in django
I would like to redirect all 404 errors to the index page of my django project. I am trying to do this by creating a view to handle all 404 requests and then adding the references to my urls.py. This is what I have in my views.py: def view_404(request, exception=None): return redirect('/') and my urls.py: handler404 = 'classroom.classroom.view_404' However I get the error message ERRORS: ?: (urls.E008) The custom handler404 view 'classroom.classroom.view_404' could not be imported. HINT: Could not import 'classroom.classroom.view_404'. Parent module classroom.classroom does not exist. Which I assume has more to do with how I am referencing the my views.py file. Here is the structure of my project multipleusers -->django_project ---->templates ---->views classroom.py students.py mentors.py -
How can i transfer my python program on a website
I got a program, written in python, and my mission is to implement this on a website, so other can have access to it. I already tried Django and Flask, but they want me to translate my python code into html. I'm searching for the possibility to Paste my python program into a file which implements the program on a website. PS: My program includes a user interface and File implements. -
When I submit this form, neither data is saved onto database nor giving any error in my django project
models.py here is my model class Load_post(models.Model): user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE) pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) sender_name = models.CharField(max_length=150) phone_number = PhoneNumberField(null=False , blank=False , unique=True) receiver_name = models.CharField(max_length=150) sending_item = models.CharField(max_length=150) weight = models.CharField(max_length=150) metric_unit = models.CharField(max_length=30, default='SOME STRING') quantity = models.PositiveIntegerField(default=1) requested_shiiping_price = models.PositiveIntegerField() pick_up_time = models.DateField() drop_time = models.DateField() paid_by = models.CharField(max_length=150) created_at = models.DateTimeField(auto_now=True) published_date = models.DateField(blank=True, null=True) def __str__(self): return self.user.username def save(self, *args, **kwargs): super().save(*args, **kwargs) def publish(self): self.published_date = timezone.now() self.save() def get_absolute_url(self): return reverse('local') class Meta: ordering = ["-created_at"] unique_together = ["sender_name", "receiver_name"] please check the phone number forms.py this is form.py class Loader_post_form(forms.ModelForm): phone_number = PhoneNumberField() metric_unit = forms.ChoiceField(choices=UNIT, required=True) class Meta: model = Load_post fields = ("pick_up_station", "destination_station", "sender_name", "phone_number", "receiver_name", "sending_item","image_of_load","weight","metric_unit", "quantity","requested_shiiping_price","pick_up_time", "drop_time","paid_by") views.py This is my views.py absolute URL used in models already class Loader_post_view(CreateView, LoginRequiredMixin): login_url = 'Driver/login/' form_class = forms.Loader_post_form model = Loader_Signup template_name = "Driver/post.html" def form_valid(self,form): form.instance.user = self.request.user form.save() return super(Loader_post_view,self).form_valid(form) post.html this is html page (template) {% extends "Driver/base.html" %} {% block content %} <h1>create a post</h1> {% csrf_token %} {{form}} <button type="submit">submit</button> {% endblock content %} this is html code how to add it to the database and I cannot see … -
How to nest json in python?
I'm working on django app and need to pass data from django sql as json to javascript. I'm struggling with nesting one thing. I was able to nest one level but I can't nest second level. While nesting second level, json replaces the value according to itteration instead of appending it. My goal it to obtain the the following effect: date > [time1 > [1,2,3], time2 > [1,2,3]], date2 > [time1 > [1,2,3]] etc.. At this moment i can't nest more than one time :( Appreciate for help ! reserved = Reservation.objects.get(customer=user_info) for x in reserved.reservations.all(): title = x.movie.title image = x.movie.image date = str(x.date) time = str(x.time) dates = {date:{}} times = {time:{}} if title in dic: pass else: dic[title] = {"image":str(image), "dates":{}} for y in x.seats.all(): seats = {y.row:y.number} times[time].update(seats) dates[date].update(times) dic[title]["dates"].update(dates) enter image description here -
Running python function asynchronously without blocking caller function (and without needing the result)
I need to do a lengthy preprocessing step on POST requests to a given route (I'm using Django). This will read a dataset, change some thing, and re-write it to disk (it can take a couple minutes). I don't need the result of this function, I just want to execute it asynchronously and send an HTTP response immediately without waiting for it to end. Currently like this it says the subroutine "preprocess_dataset_async" is never awaited on and it doesn't execute it fully. @require_POST def preprocess_dataset(request, f_path=''): # ... preprocess_dataset_async(f_path, data) return HttpResponse('Request is being handled in the background', status=200) async def preprocess_dataset_async(f_path, preprocess_args): # ... await stuff # ... What would be the best way to execute this task in the background without blocking the caller function ? -
I want to custom serializer field, how can I do this?
I am using model translations for Django rest framework and right now I have in database 3 fields title_en title_ru title_ro and in my serializer I have fields: ("title_en, title_ro, title_ru"). But I want in my response to give something like this data: { title: { ro: 'something here', ru: 'something here', en: 'something here' } } how can I achieve this? Can someone help me? -
how to desrialize json to object in python or django
I am new to python and django. i must consume a web service and the response of web service is json like this: [{'name': 'gfile1.txt', 'length': 448, 'createdDate': '1582229671352'}, {'name': 'gfile2.txt', 'length': 86, 'createdDate': '1582229671474'}, {'name': 'soc-LiveJournal1.txt', 'length': 1080598042, 'createdDate': '1582229715227'}] also i have a class according to this json result: the below is class definition: class DataParameter: def __init__(self, name, size, _createdDate): self.filename = name self.filesize = size self.createdDate = _createdDate what should i do is: i must convert the above json to list of DataParameter class. Can you help me to do this? Thanks -
Django multi-tenancy with Maria DB, separate databases
We are building a new system that requires multi-tenancy, and we also intend to use Maria DB for that. I have already gone through a well-known multi-tenancy solution django-tenant-schemas that offers multi-tenancy with single PostgreSQL DB and multiple schemas - but that doesn't address our problem. What is the best approach for me if I want to use multiple DB multi-tenancy with Maria DB? -
Hooking Django model intstance's save method to celery
I am using S3 as a media storage in Django. The thing is, If the video is uploaded it takes too long to return the response in a view. I know there should be a way to make it async. snippet of view.py with transaction.atomic(): media = Media( med_user_id=account, med_path=file, med_thumbnail=thumbnail, med_assoc_data=data, ) save_async.delay(media) variable file is a video with this class<class 'django.core.files.uploadedfile.TemporaryUploadedFile'> when I am saving this by media.save() it takes 12-20 seconds to complete. I thought to create a celery task that could handle it. @app.task(bind=True) def save_async(self, instance): instance.save() I know this doesn't make any sense because it throws a serialization error. Object of type Media is not JSON serializable so the question is. how should I make model.save() function async with celery? Thank you in advance. -
How to rename file before saving it to database in django rest_framework
class GenericAPIView(generics.GenericAPIView, mixins.ListModelMixin,mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin ): serializer_class = userdataSerializer queryset = UserData.objects.all() lookup_field = 'id' def get(self, request, id=None): if id: return self.retrieve(request) else: return self.list(request) def post(self, request): return self.create(request) def put(self, request, id=None): return self.update(request, id) -
Updating HTML field filled with a Django value real-time
Say I have two form fields and another HTML paragraph that is basically just a Django value. Number A: <input ...> Number B: <input ...> <p>{{ sum }}</p> I want sum to update "real time" (i.e. after both numbers were input, the sum will be computed and input automatically by the system. I have no idea where to start, I think it has something to do with some sort of javascript, but I have no idea how to link anything JS to Django and vice-versa. -
Django Detail view query - filter by foreign key objects textchoices field
i have the following 2 models - ToDoList and Tasks. Tasks has a Foreignkey to the model ToDoList. In my Detailview I only want to show Tasks, which are published (status="published"). I tried to override the get context data of the view. This worked. But it doesnt show any tasks instances in the Detailview at all, even though I have for example 1 task set as "published". I also tried to do the filter criteria in the template. I guess this isnt possible? Iam more or less sure the filter criteria must appear in the queryset. class ToDoList(TimeStamp): class STATUS(models.TextChoices): PUBLISHED = "published", "Published" TRASH = "trash", "Trash" WORKINGDRAFT = "workingdraft", "Workingdraft" headline = models.CharField(max_length=200) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) status = models.CharField("Status", max_length=20, choices=STATUS.choices, default=STATUS.PUBLISHED) def __str__(self): return self.headline def get_absolute_url(self): return reverse('notepad:todo_detail', args=[str(self.id)]) class Tasks(TimeStamp): class STATUS(models.TextChoices): PUBLISHED = "published", "Published" TRASH = "trash", "Trash" WORKINGDRAFT = "workingdraft", "Workingdraft" todos = models.CharField(max_length=250) todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE, related_name='tasks') status = models.CharField("Status", max_length=20, choices=STATUS.choices, default=STATUS.PUBLISHED) def __str__(self): return self.todos views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponseRedirect from django.forms.models import inlineformset_factory from django.views.generic import ListView, DetailView, TemplateView from django.views.generic.edit import CreateView from django.urls import reverse … -
How to check if the form data starts with some value?
Here I want to validate my question title. For example If the user asks question without starting with the words like why or what or how etc. at first then I don't want to save the data . For this how can I do it ? I think it is better to check in the forms rather than views since it will be easy to display field error to the user or is it better to do in views? And how can I validate my question title like this? views.py class CreateQuestion(SuccessMessageMixin, generic.CreateView): model = Question template_name = 'question/create_ques.html' form_class = CreateQuestionForm success_message = 'Your Question Posted Successfully.' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def get_success_url(self): return reverse_lazy('question:question_detail', kwargs={'pk': self.object.pk}) forms class CreateQuestionForm(forms.ModelForm): class Meta: model = Question fields = ['category', 'title', 'body'] def clean_title(self): title = self.cleaned_data.get('title') #if title doesnot start with words like 'why', 'how' or 'when': return forms.ValidationError('..') -
Django POST Request nested object primary key
I have a question regarding POST request with nested objects in Django with serializers: I have checked this: Stackoverflow 1 Django Doc Stackoverflow 2 I've created some serializers in my Django project following the architecture below: EP_project │ │ └───ep_python │ db.sqlite3 │ manage.py │ __init__.py │ ├───ep │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ __init__.py │ │ │ ├───migrations │ │ │ ├───models │ │ │ model_aa.py │ │ │ model_ap.py │ │ │ model_apr.py │ │ │ model_as.py │ │ │ model_at.py │ │ │ model_b.py │ │ │ model_be.py │ │ │ model_se.py │ │ │ model_s.py │ │ │ model_user.py │ │ │ __init__.py │ │ │ ├───serializers │ │ │ serializers_ap.py │ │ │ serializers_user.py │ │ │ __init__.py │ │ │ ├───views │ │ views_a.py │ │ views_user.py │ ├───ep_python │ asgi.py │ settings.py │ urls.py │ wsgi.py │ __init__.py Here are my serializers files: serializers_user.py: from rest_framework import serializers from ..models.model_user import User class UserIndexSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'first_name', 'last_name' ] class UserDetailsSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' I tried to create a custom create … -
Is there any built-in method of channel_layer that returns the 'list of groups' in Django Channels?
I want to show the user the list of chatrooms opened in a real-time chat app built with Django-Channels. To do that a method which returns the list of groups made is needed, I think. Is there any built-in method of chanel_layer that returns the list of groups? If not, is there another way to show the user the list of chatrooms opened? -
Netlify + Cactus: failed during stage 'building site': Build script returned non-zero exit code: 1
Im following this guide on how to deploy a django app using cactus on netlify: https://www.netlify.com/blog/2016/04/08/a-step-by-step-guide-cactus-on-netlify/#building-your-site I created a new private github repo and pushed the cactus stuff to it as per the docs. However, when I try to deploy it on netlify, I get this error: 12:31:56 PM: [feature enabled]: Nitro deploys enabled. Buckle up! ⚡️ 12:31:56 PM: Build ready to start 12:32:03 PM: build-image version: blablabla 12:32:03 PM: build-image tag: v3.3.6 12:32:03 PM: buildbot version: blablabla 12:32:03 PM: Fetching cached dependencies 12:32:04 PM: Failed to fetch cache, continuing with build 12:32:04 PM: Starting to prepare the repo for build 12:32:04 PM: No cached dependencies found. Cloning fresh repo 12:32:04 PM: git clone https://github.com/blablabla/blablabla 12:32:05 PM: Preparing Git Reference refs/heads/master 12:32:05 PM: Starting build script 12:32:05 PM: Installing dependencies 12:32:06 PM: v10.19.0 is already installed. 12:32:07 PM: Now using node v10.19.0 (npm v6.13.4) 12:32:07 PM: Attempting ruby version 2.6.2, read from environment 12:32:08 PM: Using ruby version 2.6.2 12:32:08 PM: Using PHP version 5.6 12:32:08 PM: Installing pip dependencies 12:32:08 PM: Started restoring cached pip cache 12:32:09 PM: Finished restoring cached pip cache 12:32:09 PM: DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please … -
Django post request data outputs as none
I am trying to get the value of bally and ballx to output with my post request (without using any forms as a project requirement), I have managed to get post requests going through without the use of a form, however the info out puts as none bally: None ballx: None, I feel like im quite close very new to python. Where am I going wrong here is the views.py from django.shortcuts import render from django.http import HttpResponse from django.http import JsonResponse from pong.models import SimpleBot def home(request, template='index.html'): axis = HttpResponse(play(request)) return render(request, template, {}) def bot(request): ballx = request.GET.get('ballx') bally = request.GET.get('bally') paddley = request.GET.get('paddley') court = {'ballx': ballx, 'bally': bally, 'paddley': paddley} data = { 'up': SimpleBot.simple_bot(court), } return JsonResponse(data) def play(request): ballx = request.POST.get('ballx') bally = request.POST.get('bally') court = {'ballx ': ballx, 'bally ': bally } print(court) return HttpResponse(court) -
Select a valid choice. 2.6 is not one of the available choices
I have a model with a field having choices in it as given below. I am messing with the DecimalField somehow. And i cannot pass values like 1.7 or 2.6. But it is accepting 1.0 and 2.0 . Please let me know what am I doing wrong. class Trip(models.Model): ACE = 1.00 Dosth = 1.70 TEN = 2.00 FORTEEN = 2.30 SEVENTEEN = 2.60 NINETEEN = 2.90 TWENTY = 3.10 TWENTYTWO = 3.10 VEH_CHOICES = ( (ACE, 'ACE'), (Dosth, 'Dosth'), (TEN, '10.5FT'), (FORTEEN, '14FT'), (SEVENTEEN, '17FT'), (NINETEEN, '19FT'), (TWENTY, '20FT'), (TWENTYTWO, '22FT'), ) ftype = models.DecimalField(null = True, blank = True, verbose_name = "Vehicle Type", decimal_places = 2, max_digits = 5, choices = VEH_CHOICES) -
Customize DRF Browsable API detail template
I'm using Django Rest Framework 3.11.0 and I want to use the BrowsableAPIRenderer with a customized template for rendering the details of an instance. I only want to override the rendering of the dict/json, marked red in the image below, and I want to keep all the rest. By overwriting restframework/api.html I only managed to change the title, heading and some fields, but I did not find a way to render the details of an instance e.g. in a table. Is there a way to do this? -
File descriptor costumes to upload file if exist else save URL in the file field
I have to get data from API and save it in the database and then maybe i have to edit this data by app there is images so image filed i cant put it URLField because of editing case i cant put it ImageField because of save data from API i tried to edit in Image file descriptor