Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I customize Rest Auth Registration view
I'm working on small project using Django / Rest Framework with rest_auth. and i would like to customize the registration view by asking for other fields like first_name and last_name also i would like to call some function after the registration. how can i customize the rest_auth registration -
Cannot assign "<JobImages: Logo Logo>": "JobImages.job" must be a "Job" instance
Here is my code: class JobImagesCreateView(CreateView): template_name = 'jobs/job_images.html' form_class = JobImageCreateForm success_url = reverse_lazy("dashboard") def form_valid(self, form): job = form.save() images = self.request.FILES.getlist("more_images") for i in images: JobImages.objects.create(job=job, image=i) return super().form_valid(form) -
Form fields are empty when created using instance = instance
I have two models prodcut_prices and WrongPrice. In WrongPrice the user can correct report wrong prices - when the price is reported it should also be updated in product_price. My problem is, even though I instantiate product_price at the very beginning as instance_productprice, all of its required fields returns the "this field has to be filled out" error. How come those field are not set when im using the instance instance_productprice = product_prices.objects.filter(id=pk)[0] ? Note, that all fields in product_prices are always non-empty since they are being pulled from the product_price model, which is handled in another view, thus that is not the issue. def wrong_price(request,pk): #Get the current price object instance_productprice = product_prices.objects.filter(id=pk)[0] #Get different values wrong_link = instance_productprice.link img_url = instance_productprice.image_url wrong_price = instance_productprice.last_price domain = instance_productprice.domain # Create instances instance_wrongprice = WrongPrice( link=wrong_link, correct_price=wrong_price, domain = domain) if request.method == "POST": form_wrong_price = wrong_price_form(request.POST,instance=instance_wrongprice) # Update values in product_prices form_product_price = product_prices_form(request.POST,instance=instance_productprice) form_product_price.instance.start_price = form_wrong_price.instance.correct_price form_product_price.instance.last_price = form_wrong_price.instance.correct_price if form_wrong_price.is_valid() & form_product_price.is_valid(): form_wrong_price.save() form_product_price.save() messages.success(request, "Thanks") return redirect("my_page") else: messages.error(request, form_product_price.errors) # Throws empty-field errors, messages.error(request, form_wrong_price.errors) return redirect("wrong-price", pk=pk) else: form_wrong_price = wrong_price_form(instance=instance_wrongprice) return render(request, "my_app/wrong_price.html",context={"form":form_wrong_price,"info":{"image_url":img_url}}) -
Cannot set a field value in Django form in views
I am making a todo website in which different users can sign in and have their separate todo lists, but when a user signs in and adds a task to the list that task does not get assigned to any user, so despite being present on the database it does not show up on the user's list. I am trying to assign the form object(task_form) a user after the form submission, I think that is the issue but I have no idea what else to try. views.py @login_required(login_url='todo:login') def task_add(request): if(request.method == "POST"): task_form = AddTask(request.POST) if(task_form.is_valid()): task_form.cleaned_data['user'] = request.user #trying to assign a user after all the data has been populated task_form.save() return redirect('todo:index') return render(request,'todo/task_add.html') template(task_add.html) {% block body %} <form method="POST"> {% csrf_token %} <p><label for="title">Title</label> <input type="text" name="title"></p> <p><label for="desc">Description</label> <input type="text" name="desc"></p> <p><label for="start_time">Time</label> <input type="datetime-local" name="start_time"></p> <p><label for="completed">Complete</label> <input type="radio" name="completed"></p> <input type="submit" value="Add" name="submit" class="btn btn-success"> </form> {% endblock %} models.py class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,null=True,blank=True) title = models.CharField(max_length=50) desc = models.CharField(max_length=100,null=True,blank=True) start_time = models.DateTimeField(auto_now=False,auto_now_add=False,null=True,blank=True) completed = models.BooleanField(default=False) def __str__(self): return self.title forms.py class AddTask(forms.ModelForm): class Meta: model = Task fields = '__all__' -
Create user registration and login authentication with Django CRUD
I have to create a user registration and login authentication without using Django's built-in user model. In creating a new user, the supplied username should not be existing yet and will be redirected to the login page. In logging in, the credentials must be valid to be redirected to home.html. I registered a user but when I try to log in, I get the error "too many values to unpack (expected 2)" views.py from django.shortcuts import render, redirect from .models import * def register(request): if(request.method=="POST"): username = request.POST.get('un') password = request.POST.get('pw') account = Account.objects.filter(username) if username == account.username: Account.objects.create(username=username, password=password) return render(request, 'app1/register.html') else: return render(request, 'app1/register.html') else: return render(request, 'app1/register.html') def login(request): if(request.method=="POST"): username = request.POST.get('un') password = request.POST.get('pw') account = Account.objects.filter(username) if password == account.password: return render(request, 'app1/home.html') else: return render(request, 'app1/login.html') else: return render(request, 'app1/login.html') def view_home(request): return render(request, 'app1/home.html') Is there something wrong with the views.py? -
Cannot find JavaScript script file from HTML file script
In the following Image of code, I am trying to reference the javascript file "doggies.js" that is currently in the basket folder. This happens on the click of a button on my website, but every time it says it cannot find the file. I have tried ../doggies.js as well but this does not work, is there any reason as to why this might be happening? <script type="text/javascript"> $(document).on('click', '.checkout-button', function () { var script = document.createElement("script"); script.type = "text/javascript"; script.src = "doggies.js"; document.getElementsByTagName("head")[0].appendChild(script); return false; console.log("yo") }) </script> Here is the error Not Found: /basket/doggies.js [13/May/2021 18:50:22] "GET /basket/doggies.js HTTP/1.1" 404 3322 -
Is there any proper way to send a POST request through React using fetch()?
I am getting url as None on the API server side and the API is working fine when tested with POSTMAN and other scripts but the problem happens when sending the request in React. const imgLoad = { method: 'POST', headers: { "Content-Type":"application/json" }, body: JSON.stringify({ image_url: imageurl //image url stored in a variable & I tried using a string but the problem is still there }) } fetch("http://127.0.0.1:7000/emotion_detection/detect/", imgLoad) .then(response => response.json()) .then(data => this.setState({emotion: data})); -
Django media URL serving behind the scene through
I understand the difference between MEDAI_URL and MEDIA_ROOT that root is used for upload and URL is used to access it through HTTP but there's one thing that I don't understand as per this answer Django - MEDIA_ROOT and MEDIA_URL the webserver e.g Nginx handles the static files, not python but how does the webserver know the path to the images without python even though that it only sees the e.g 127.0.0.1/images/product11.png and the images actually stores in the path 127.0.0.1/static/images/product1.png -
How to check if geo loocation are in radius?
Help me please, I have 2 cords, cords of my base and base of my car. I have to check if my car is in 50 miles radius of my base. Cords are in lat,lng -
Cannot seem to access multiple Images after upload Django
So been at it on and off for about a week so thought I might as well throw it out there and see if anyone can help. complete newbie to django and web development so apologies if I'm being completely thick here. I'm trying to setup a page requiring no authentification that end users will upload images to (and nothing else), which will then have various things done to them before being returned to them in the same page. If possible, I'd rather not have to store them but that's another query all together. (you'll see i'm saving them at the moment as most tutorials seem to run with Models) What I'm struggling to do at the minute is get Django to return all the files from the POST request in a single template, I always seem to just get the last one. Would appreciate any advice. views.py: def uploadfiles(request): if request.method == 'POST': form = ImageUploaderForm(request.POST, request.FILES) files = request.FILES.getlist('image') if form.is_valid(): handle_uploaded_file(request.FILES['image']) output = form.save() print("form validated") return render(request, 'home/imageuploader_detail.html', {'form': output, 'files': output.image}) else: print("form isn't valid") else: print("Form Generated") form = ImageUploaderForm() return render(request, "home/imageuploader_form.html", {'form': form}) models.py class ImageUploader(models.Model): image = models.ImageField(upload_to='images/') forms.py class ImageUploaderForm(forms.ModelForm): … -
How to transform QuerySet to another type?
Say you've got these models: class NetworkMember(models.Model): network = models.ForeignKey(Network, related_name='members', on_delete=models.CASCADE, db_column='network_id_id') user = models.ForeignKey(User, on_delete=models.CASCADE, db_column='user_id_id') class Network(models.Model): created_at = models.DateTimeField(auto_now_add=True, db_index=True) And you have filtered NetworkMember: user_networks = NetworkMember.objects.filter(user=self.user) Now user_networks is QuerySet of NetworkMember, how can I transform it to QuerySet of Network? Doing .values('network') and .values_list('network') doesn't change the type of QuerySet to Network. -
Embedding password protected pdf's?
I have some pdf files which I would like to publish on my websites. I don't want them to be downloaded. Is there any way that I can publish those files as password protected such that they are automatically opened on the website but when someone downloads it they can't open unless they have the password? -
Page rendering with model.py but not working after data is added in the models through admin portal
I am working on MDN Django tutorial on LocalLibrary. I am using get_absolute_url to render generic ListView and DetailView page. App is rendering page with else statement i.e. There are no books in the library. But when I add books in the library through admin portal in my models. Same pages are not rendering and reflecting below error NoReverseMatch at /catalog/books/ Reverse for 'book-detail' not found. 'book-detail' is not a valid view function or pattern name. Please find the models.py as follows import uuid # Required for unique book instances from django.db import models # Create your models here. # Used to generate URLs by reversing the URL patterns from django.urls import reverse class Genre(models.Model): """Model representing a book genre.""" name = models.CharField( max_length=200, help_text='Enter a book genre (e.g. Science Fiction)') def __str__(self): """String for representing the Model object.""" return self.name class Language(models.Model): name = models.CharField(max_length=200, help_text='Enter a book language(e.g. English)') def __str__(self): return self.name class Book(models.Model): """Model representing a book (but not a specific copy of a book).""" title = models.CharField(max_length=200) # Foreign Key used because book can only have one author, but authors can have multiple books # Author as a string rather than object because it hasn't … -
Laravel or Django which is best to carry on
I am new to web development. I am learning laravel with vue . I have also started to learn django. To which should have focus more? Which of these 2 framework have more usability? -
Getting JSONDecodeError when hosting on heroku but not locally
This is the heroku logs - File "/app/CovidSlots/urls.py", line 18, in <module> 2021-05-13T15:28:34.921279+00:00 app[web.1]: from SlotBooking import views 2021-05-13T15:28:34.921280+00:00 app[web.1]: File "/app/SlotBooking/views.py", line 14, in <module> 2021-05-13T15:28:34.921280+00:00 app[web.1]: states = logic.print_states() 2021-05-13T15:28:34.921281+00:00 app[web.1]: File "/app/SlotBooking/logic.py", line 30, in print_states 2021-05-13T15:28:34.921281+00:00 app[web.1]: res_info = res.json() 2021-05-13T15:28:34.921282+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/requests/models.py", line 897, in json 2021-05-13T15:28:34.921282+00:00 app[web.1]: return complexjson.loads(self.text, **kwargs) 2021-05-13T15:28:34.921282+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/json/__init__.py", line 346, in loads 2021-05-13T15:28:34.921283+00:00 app[web.1]: return _default_decoder.decode(s) 2021-05-13T15:28:34.921283+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/json/decoder.py", line 337, in decode 2021-05-13T15:28:34.921283+00:00 app[web.1]: obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 2021-05-13T15:28:34.921284+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/json/decoder.py", line 355, in raw_decode 2021-05-13T15:28:34.921284+00:00 app[web.1]: raise JSONDecodeError("Expecting value", s, err.value) from None 2021-05-13T15:28:34.921285+00:00 app[web.1]: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) This is the snippet of the view which is being called (the error is produced in while calling logic.print_states() - from time import strftime from django.http.request import validate_host from django.shortcuts import redirect, render import requests from . import logic from django.core.mail import send_mail from CovidSlots import urls states = [] states = logic.print_states() districts = [] email_id = '' def homepage(request): context = {"states":states} if request.method == 'POST': email_id = request.POST.get('email_id') state_name = request.POST.get('state_name') state_id = logic.find_state_id(state_name) return redirect ('districtpage', state_id = state_id, email_id = email_id) return … -
Getting an signaturedoesntmatch error when I tried to access a image that I uploaded to aws s3 bucket
enter image description here This is the error I'm getting. I'm new to aws and I don't know how things works here. I referred many documentations but noting worked for me. Please give a solution for this. Thanks. -
Using CDN for local development
I am looking into CDN for storing and displaying images, and below are my questions related to developing for CDN. I use Python + Django + jQuery + Apache Airflow + Postgresql + Docker for the development using a local linux machine. With regards to CDN: Is the use of CDN configuration based where changing the configuration will store the files on CDN instead of local storage? In this case, on my model class, I continue to use ImageField, and when I change the configuration, it will internally use CDN to store I am planning to use Cloudflare, Azure, or AWS for CDN in production. Does the code change depending on the CDN provider? When I display images on the web page, I usually refer to the local URL. In the case of CDN, I will have to point to the CDN URL, do I have to keep that in mind when I develop? Appreciate it if you can answer, and also point to some information page. Thanks in advance. -
Why is RichText not working in wagtail admin for posts? This is the type of thing that happens: <h2>Trying post.content|richtext</h2>
Wagtail implemented on an existing Django site. I have included the parts of code most likely to contain the error. If you would like anything else please do not hesitate to request it. Code as follows: models.py from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.utils.text import slugify from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel class Subject(models.Model): subject = models.CharField(max_length=200) subject_slug = models.SlugField(editable=True, max_length=200, null=False, unique=True) def get_absolute_url(self): kwargs = { 'slug': self.slug } return reverse('subject', kwargs=kwargs) def save(self, *args, **kwargs): value = self.subject self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) panels = [ FieldPanel('subject'), FieldPanel('subject_slug') ] class Meta: # Gives the proper plural name for class called subject verbose_name_plural = "Subjects" def __str__(self): return self.subject class Post(models.Model): author = models.ForeignKey(User, default=1, on_delete=models.SET_DEFAULT, related_name='blog_posts') date_added = models.DateTimeField(auto_now_add=True) subject = models.ForeignKey(Subject, verbose_name='Subject', default=1, on_delete=models.SET_DEFAULT) title = models.CharField(max_length=200, unique=True) slug = models.SlugField(editable=True, max_length=200, null=False, unique=True) content = RichTextField() def get_absolute_url(self): kwargs = { 'slug': self.slug } return reverse('post_detail', kwargs=kwargs) def save(self, *args, **kwargs): value = self.title self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) content_panels = Page.content_panels + [ FieldPanel('author'), FieldPanel('subject'), FieldPanel('title'), FieldPanel('slug'), FieldPanel('content') ] class Meta: … -
video controls like seek dragging video prograss bar is not working in html?
video control like seek 10 sec video progress bar dragging is not working in HTML <video controls width=100% height=100% preload="auto" preload="metadata" autoplay="autoplay" ><source src={{objs.video.url}} type="video/mp4"></video> note : i am using Django -
How to guarantee atomicity of nested objects while saving model instance?
Here's my code: from django.db import models class Car(models.Model): is_crawler = models.BooleanField() class Wheel(models.Model): car = models.ForeignKey(A, related_name='wheels', on_delete=models.CASCADE) radius = models.IntegerField() class WheelSerializer(serializer.ModelSerializer): class Meta: model = Wheel fields = '__all__' class CarSerializer(serializers.ModelSerializer): wheels = WheelSerializer(many=True) class Meta: model = Car fields = '__all__' def validate(self, attrs): is_crawler = attrs.get('is_crawler') wheels_data = attrs.get('wheels') if wheels_data and is_crawler: raise ValidationError("Crawler can't have wheels") def create(self, validated_data): is_crawler = attrs.get('is_crawler') wheels_data = attrs.get('wheels') car = Car.objects.create(**validated_data) for wheel_data in wheels_data: wheel_serializer = WheelSerializer(**wheel_data) if wheel_serializer.is_valid(): wheel_serializer.save() return car So, when I'm trying to send something like {"is_crawler": true, "wheels": [{"radius": 5}]} to CarSerializer it raises ValidationError that causes 400 response from the view. But it doesn't prohibit creating wheels for crawlers in admin for example. Is there a way to transfer validation from serializer to model's clean or save method to prohibit creating crawler cars with wheels or add wheels to crawler cars in any part of code? And if there is, will it raise the same ValidationError in DRF and return HTTP_400 from DRF? -
django.core.exceptions.AppRegistryNotReady error in my django app
i'm trying to add the django-ads module to my web app but i have few problems. to install django ads i need to add code in my settings.py but there is the module gettext wich is needed and there is some "_" who generate me error. so i imported the following things in my settings.py. from ads.conf import gettext from django.utils.translation import gettext as _ after that when i try to runserver that's show me this error : django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time. don't know how to fix that, i've seen some post about de wsgi.py files but he's good. wsgi.py : import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yufindRe.settings') application = get_wsgi_application() -
Error : render() got an unexpected keyword argument 'renderer'
I am building a BlogApp and I am stuck on an Error. I made a multiple upload feature using class based views for handling form BUT when i open page then it is keep showing me render() got an unexpected keyword argument 'renderer' views.py from django.views.generic.edit import FormView from .forms import UploadForm from .models import Gallery class UploadView(FormView): template_name = 'form.html' form_class = UploadForm def form_valid(self,form): for each in form.cleaned_data['gallerys']: Gallery.objects.create(file=each) return super(UploadView,self).form_valid(form) File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\forms.py", line 277, in as_table errors_on_separate_row=False, File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\forms.py", line 236, in _html_output 'field_name': bf.html_name, File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\html.py", line 376, in <lambda> klass.__str__ = lambda self: mark_safe(klass_str(self)) File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\boundfield.py", line 34, in __str__ return self.as_widget() File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\boundfield.py", line 97, in as_widget renderer=self.form.renderer, Exception Type: TypeError at /lists/ Exception Value: render() got an unexpected keyword argument 'renderer' I have seen many answers BUT they seems little different from my error. I have no idea, what am i doing wrong in this. Any help would be Appreciated. Thank you in Advance, -
Reverse for 'post_detail' with arguments '('chempion',)' not found. 1 pattern(s) tried: ['(?P<category_slug>
Reverse for 'post_detail' with arguments '('chempion',)' not found. 1 pattern(s) tried: ['(?P<category_slug>[-a-zA-Z0-9_]+)/(?P[-a-zA-Z0-9_]+)/$'] as soon as I add function and view to templates I catch this error view.py def post_detail(request, category_slug, slug): post = get_object_or_404(Post, slug=slug) try: next_post = post.get_next_by_date_added() except Post.DoesNotExist: next_post = None try: previous_post = post.get_previous_by_date_added() except Post.DoesNotExist: previous_post = None context = { 'post': post, 'next_post': next_post, 'previous_post': previous_post } return render(request, 'post_detail.html', context) urls.py path('<slug:category_slug>/<slug:slug>/', post_detail, name='post_detail'), path('<slug:slug>/', category_detail, name='category_detail'), post detail.html {% if next_post %} <a href="{% url 'post_detail' next_post.slug %}">Next</a> {% else %} This is the last post! {% endif %} -
How to access forgin key value in react from django api
I have django api in which i have post model which is linked to comments and categories table by forgin key now i am feching data for post detail and when i try to access category of that post it return s id and i want to access name of category this is my post list view { "id": 4, "title": "BLOG PAGE", "body": "testing", "owner": "ankit", "comments": [], "categories": [ 2 ], "created_at": "2021-05-07T17:22:32.989706Z" }, { "id": 5, "title": "Test Post", "body": "This is a test Post", "owner": "ankit", "comments": [], "categories": [ 2 ], and this is my categories [ { "id": 2, "name": "Python", "owner": "ankit", "posts": [ 4, 5, 6, 8 ] } ] and this is my post detail component export class PostDetail extends React.Component { constructor(props) { super(props); const ID = this.props.match.params.id this.state = { data: [], loaded: false, placeholder: "Loading" }; } formatDate(dateString){ const options = { year: "numeric", month: "long", day: "numeric" } return new Date(dateString).toLocaleDateString(undefined, options) } componentDidMount() { fetch(`${Url}posts/${this.props.match.params.id}`) .then(response => { if (response.status > 400) { return this.setState(() => { return { placeholder: "Something went wrong!" }; }); } return response.json(); }) .then(data => { this.setState(() => { return … -
Get brackets with a value in html displayed, example {{test}} output in html {{test}} [duplicate]
I am trying to get {{test}} displayed as text in the html webpage within the django server. But it disseapear because the framework is handeling it as a tag. Is there a work around ? thnx !