Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the most elegant or Pythonic way to initialise a Django object?
I am new to Python and Django but feel like there must be a neater way of accomplishing this than I have found. I have a Django model that has a date attribute with a non-trivial default value, meaning that I need a little bit of logic to set it up. I have tried several ways of doing this, but unfortunately this is the only one that has worked for me so far (in models.py within a weeks app): def first_day_of_next_week(): return timezone.now().date() - datetime.timedelta(days=timezone.now().date().weekday() + datetime.timedelta(days=7) class Week(models.model): start_of_week = models.Datefield('Date of the first day of the week', unique=True, default=first_day_of_next_week()) I strongly dislike having a function floating outside of any class like that (but don't have the experience to know whether it is actually bad). I have tried incorporating it into a static or class method, or within an __init__ process within Week, but can't get any of those approaches to work properly (in particular, Django seems to complicate hijacking __init__). Now that I have the Week model working, I want to instantiate weeks with Week.objects.get_or_create() from views.py, but here I hit the problem that I need the same first_day_of_next_week() logic to be accessible within views.py. (This is what … -
csrf verification failed even after using the token
{% extends 'base.html' %} {% block content %} <form action="add" method="POST"> {% csrf_token %} Enter a number : <input type="number" name="num1" required/><br /> Enter another number : <input type="number" name="num2" required/> <input type="submit" /> </form> {{result}} {{res}} {% endblock %}`` i have just started learning django. why i still get csrf verification failed when i have included the token in the form? -
Unble to use the working Django modles for index.html page ( Modles data entried in admin page but not visible in index.html page)
I have created modles in modles.py as below: class Title(models.Model): title = models.CharField(max_length=100) def __str__(self): return self.title , migrate successfully, later on, registered the moodle in admin.py as admin.site.register(Title), But the issue is I can see in admin pannel that modles created and upadted the data but in index.html page, I used as {{Title.title}} which seems not working. Need help ????? Do i need to create views and what I should types in views.py -
Not able to register through frontend. Keeps saying Bad Request
I am trying to build a basic authentication website using DJANGO and REACT. But there seems to be a problem in communication between frontend and backend. I have built a Rest API using DJANGO REST FRAMEWORK and authentication using KNOX whose code is as follows: # api.py from rest_framework import generics, permissions from rest_framework.response import Response from knox.models import AuthToken from .serializers import UserSerializer, RegisterSerializer, LoginSerializer # Register API class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) # Login API class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) # Get User API class UserAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserSerializer def get_object(self): return self.request.user # serializers.py from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth import authenticate # User serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') # Register serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user( validated_data['username'], validated_data['email'], validated_data['password'] ) … -
How to let Django automatically provoke Celery's beat?
Currently, whenever I need to run my Django + Celery, I would need to do the following two commands: python manage.py runserver celery -A celery beat -l INFO This is a bit annoying. If my Django app cannot automatically run Celery beat, then what is the point of these two lines in the __init__.py ? from __future__ import absolute_import from .celery import app as celery_app Sorry, I just start learning Celery. Some of its aspect was not very clear to me. -
django rest framework know if view is class or function
I was implementing my custom permission where I had to check if view is function or class. I have done the following def has_permission(self, request, view): print("request ===", view, inspect.isfunction(view), inspect.isclass(view)) Here both inspect.isfunction(view), inspect.isclass(view) gives me false. How can I determine if a view is functin or class ?? -
getting error no such column: mains_profile_friends.user_id
I am going through a Django tutorial and getting this error when trying to open friends page in browser( In local Host ) in my blog app. I use Django==3.1.2. views.py @login_required def friend_list(request): p = request.user.profile friends = p.friends.all() context = {'p':p,'friends':friends} return render(request, 'mains/friends.html' , context ) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') friends = models.ManyToManyField(User, related_name='friends',blank=True,default='',null=True) friends.py {% block content %} <div class="container"> <div class="row"> <div class="col-md-8"> {% if friends %} <div class="card card-signin my-5"> <div class="card-body"> {% for user_p in friends %} <a href="{{ user_p.get_absolute_url }}">{{ user }}</a> <a class="text-dark" href="{{ user_p.get_absolute_url }}" ><b>{{ user_p }}</b></a> <small><a class="btn btn-danger float-right" href="{% url 'mains:delete_friend' user_p.id %}" >UnFriend</a></small> <br /><br /> {% endfor %} {% endif %} {% endblock content %} urls.py path('friends/', views.friend_list, name='friend_list'), The Problem When i open friends.html in browser it is giving me an error :- no such column: mains_profile_friends.user_id. What i have tried. 1). I have replaced all the names related to friend_list view. 2). I have also migrated in Terminal. Help me in this !! I will really appreciate your Help. Thank you in Advance. -
Signaling a long running Huey task to stop
I'm using Huey to perform some processing operations on objects I have in my Django application. @db_task() def process_album(album: Album) -> None: images = album.objects.find_non_processed_images() for image in images: if album.should_pause(): return process_image(album, image) This is a simplified example of the situation I wish to solve. I have an Album model that stores a various number of Images that are required to be processed. The processing operation is defined in a different function that s wrapped with @task decorator so it'll be able to run concurrently (when the number of workers > 1). The question is how to implement album.should_pause() in the right way. Current implementation looks like this: def should_pause(self): self.refresh_from_db() return self.processing_state != AlbumProcessingState.RUNNING Therefore, on each iteration, the database is queried to update the model, to make sure that state field didn't change to something other than AlbumProcessingState.RUNNING, which would indicate that the album processing tasks should break. Although it works, it feels wrong since I have to update the model from the database on each iteration, but these feelings might be false. What do you think? -
Access to XMLHttpRequest at .' from origin . has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present
I build my API using Django and trying to use this API from angular but getting a CORS policy error. below is my code. since I am new to both Django and angular, I would appreciate it if anyone could help me with the issue. Django settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'bd_api', 'rest_auth', 'rest_framework.authtoken' , 'django.contrib.sites' , 'allauth' , 'allauth.account', 'rest_auth.registration', 'django_filters', 'corsheaders' , ] CORS_ALLOW_CREDENTIALS = True ALLOWED_HOSTS = ['*'] CORS_ALLOWED_ORIGINS = [ 'http://localhost:4200', ] SITE_ID = 1 MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... Angular codes files intercept.ts import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class HttpHeaderInterceptor implements HttpInterceptor { constructor() {} intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> { const headers = new HttpHeaders({ // 'Access-Control-Allow-Origin': '*', 'Accept': 'application/json', }); const reqWithToken = request.clone({headers}); return next.handle(reqWithToken); } } http.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { environment } from '../../environments/environment'; @Injectable({ providedIn: 'root' }) export class HttpserviceService { baseUrl = environment.api_url; // headers = {Authorization: true} constructor(private http: HttpClient) { } public getContries(cond=''){ … -
There is no current event loop in thread 'Thread-12'
I am using Django with requests-html to scrape amazon and Udemy so I have a form that takes in details like the url, price and website but when I fill the form it returns There is no current event loop in thread 'Thread-12'. with any random thread (sometimes it is Thread-2, Thread-9, etc.) I don't know what is causing this error but is there any way that I can dispose of threads that don't have event loops by detecting them. views.py from django.http.response import HttpResponse from django.shortcuts import render from django.contrib.auth.decorators import login_required from requests_html import HTMLSession from Products.webscraper import get_udemy_course_price, get_amazon_product_price @login_required def index(request): if 'url' in request.POST and 'desired price' in request.POST and 'website' in request.POST: product_url = request.POST.get("url") desired_price = request.POST.get("desired price") website = request.POST.get("website") session = HTMLSession() if website == "autodetect": if "amazon" in product_url: website = "amazon" if "udemy.com" in product_url: website = "udemy" if "udemy.com" in product_url: title, current_price, thumbnail_url = get_udemy_course_price( session, product_url) elif "amazon" in product_url: title, current_price, thumbnail_url = get_amazon_product_price( session, product_url) else: return HttpResponse("Please enter an Amazon or Udemy URL") print(f"Product URL: {product_url}, Desired price: {desired_price}, Website: {website}, Title: {title}, Current Price: {current_price}, Thumbanil URL: {thumbnail_url}") return render(request, "Pages/index.html") The … -
how can i filter field django jsonfield that is datetime?
I want to filter base on time field in jsonfield,but this field store as string and i can not use this query: Notification.objects.filter(Q(data__payload__request_visit_time__gte=timezone.now())) -
Send mail from any from email and through other verified email from other domain
I am working on a Django application that can allow users to send emails from their emails or from their domain emails after verification, I intended to use Zoho SMTP for sending emails, I wrote a function like so: def send_email(subject, to_list, from_email, text_content, content): email_message = mail.EmailMultiAlternatives( subject=subject, body=text_content, to=tuple(to_list), from_email=from_email, ) email_message.attach_alternative(content, "text/html") email_message.send() The problem is that it always throws smtplib.SMTPDataError: (553, b'Relaying disallowed as abc@gmail.com'). Although, the first time I tried, it sent an email with an included via mydomain.com in the from section. How can I achieve the following without having to set up my own SMTP server: Send mail from any from_email including a via in the from section of the received email. Send mail from other domains after making them verify their domain using MX Records or something Any links, suggestions would be highly appreciated. Thanks -
datatable serverSide processing not working with Django
I am an absolute beginner in Datatables (just started reading yesterday) and I have been reading DataTables documentation and this is what I have done so far, I'm having an issue using Datatables with Django. This is my JS code <script> $(document).ready( function (){ var table = $('#table_id').DataTable({ serverSide: true, "searching": false, "paging": true, "aLengthMenu": [[5, 10, 25, -1], [5, 10, 25, "All"]], "iDisplayLength": 5, "ajax":{ url:"/datatabletest/", type:"POST", data:{ name:"someVal", // More data will be added here for filtering }, }, dataSrc:"", columns: [ { data: 'id' }, { data: 'country_id' }, { data: 'state_name' }, ], }); }) </script> I've tried this in my views.py @csrf_exempt def datatabletest(request): if request.method == "POST": name = request.POST.get("name") start = int(request.POST.get('start')) length = int(request.POST.get("length")) states = Table_States_List.objects.all().values()[start:start+length] lt = [] for item in country: lt.append(item) return JsonResponse({"draw": 1, "recordsTotal": states.count(), "recordsFiltered": length, 'data':lt}) The issue is, when I load the template, data is properly visible in Datatable, but after clicking on pagination buttons, a POST request is made on the server with proper parameters, and data is fetched from the database, but it doesn't appear in the table. The expected output is the no. of rows in the table of the selected … -
Django Model Reference to Multiple Foreign Key with Child Property
I have the following Models of customer details with each customers having different payment modes (eg. cash, online transfer, etc...) : class Customer(models.Model): #some customer details class Payment(models.Model): customer = models.ForeignKey(Customer, on_delete=models.RESTRICT, related_name='payments') payment_mode = models.CharField(max_length=255, blank=True, null=True) And I would like to add a new Invoice Model to include the customer as well as the customer's payment modes. class Invoice (models.Model): customer = models.ForeignKey(Customer, on_delete=models.RESTRICT, related_name='payments') payment_mode = models.ForeignKey(Customer.payments.payment_mode, on_delete=models.RESTRICT) I am going to create an Invoice for a customer and will input the customer's available payment mode. But the the invoice's payment mode is giving me an AttributeError: 'ReverseManyToOneDescriptor' object has no attribute 'payment_mode'. May I know how do I set up the reference to the customer's child data? Thank you. -
There is no current event loop in thread 'Thread-12'
I am using Django with requests-html to scrape amazon and Udemy so I have a form that takes in details like the url, price and website but when I fill the form it returns There is no current event loop in thread 'Thread-12'. with any random thread (sometimes it is Thread-2, Thread-9, etc.) I don't know what is causing this error but is there any way that I can dispose of threads that don't have event loops by detecting them. views.py from django.http.response import HttpResponse from django.shortcuts import render from django.contrib.auth.decorators import login_required from requests_html import HTMLSession from Products.webscraper import get_udemy_course_price, get_amazon_product_price @login_required def index(request): if 'url' in request.POST and 'desired price' in request.POST and 'website' in request.POST: product_url = request.POST.get("url") desired_price = request.POST.get("desired price") website = request.POST.get("website") session = HTMLSession() if website == "autodetect": if "amazon" in product_url: website = "amazon" if "udemy.com" in product_url: website = "udemy" if "udemy.com" in product_url: title, current_price, thumbnail_url = get_udemy_course_price( session, product_url) elif "amazon" in product_url: title, current_price, thumbnail_url = get_amazon_product_price( session, product_url) else: return HttpResponse("Please enter an Amazon or Udemy URL") print(f"Product URL: {product_url}, Desired price: {desired_price}, Website: {website}, Title: {title}, Current Price: {current_price}, Thumbanil URL: {thumbnail_url}") return render(request, "Pages/index.html") The … -
Django admin site is not showing default permissions of models
My Django admin site does not show any default permissions of any models. Actually, I checked the database and I can't find any model permission in the auth_permissions table. I've already run python manage.py makemigrations and python manage.py migrate I also tried deleting the database and migration files and run two above command again but doesn't work. I've already registered my models in admin.py Any other solutions I can try ? Thank you guys for your time. Merry Christmas !!! -
DoesNotExist at /cart/ Product matching query does not exist
def cartItems(cart): items=[] for item in cart: items.append(Product.objects.get(id=item)) return items -
ReactJS and Django Problems
mery techsmas btw So I was following this tutorial and was typing exactly what he types. When I load the page , and I click "Leave Room"; I get "this.props.leaveRoomCallback is not a function". I even checked the code hosted on github and it looked the same as my code. I dont know what I am doing wrong. Thank You. Feel free to contact me on discord : TooFastForYou#9742 -
How to make a search engine in django with suggestions?
I want to make a search bar that works with JavaScript. That way, I can add suggestions like Google does when you are looking for something. I already have the search bar and the view to filter the Patients (my model). Here is the code def search_patient(request): """ Will return all the patients that start with the name that the user searches """ q = request.POST['q'] results = Patient.objects.filter(names__startswith=q) for result in results: result.serialize() return JsonResponse({'results': results}, status=200) It is a pretty simple function. The problem is that I really think that requesting the new string every time the user types a letter or deletes one would blow up the server, and I don't want that. I really need help here, and I am open to every suggestion. Thanks! -
How to pass foreign key in django
I have created a form for feedback having model feedbackid = models.AutoField(primary_key=True) courseid = models.ForeignKey('Course', on_delete=models.CASCADE) description = models.CharField(max_length=500) submitdate = models.DateTimeField(auto_now_add=True) teacherid = models.ForeignKey('schoolTeacher', on_delete=models.CASCADE) studentid = models.ForeignKey('Student', on_delete=models.CASCADE) option = [('Good','Good'),('Average','Average'),('Bad','Bad')] rating = models.CharField(max_length=100, choices=option, default='none') And the input is taken through form <form action="/studentFeedBack/" method="POST"> {% csrf_token %} <label for="studentid">Student Id</label> <input type="number" name="studentid"><br><br> <label for="courseid">Course Id</label> <input type="number" name="courseid"><br><br> <label for="teacherid">Teacher Id</label> <input type="number" name="teacherid"><br><br> <label for="description" >Feedback</label> <textarea class="form-control" rows="3" name="description"></textarea><br><br> <label for="rating">Rating</label><br> <input type="radio" id="Good" name="rating" value="Good"> <label for="Good">Good</label><br> <input type="radio" id="Average" name="rating" value="Average"> <label for="Average">Average</label><br> <input type="radio" id="Bad" name="rating" value="Bad"> <label for="Bad">Bad</label><br><br> <button type="submit" class="btn btn-primary" >Submit</button> </form> This form has three foreign keys from the following tables class Course(models.Model): courseid = models.IntegerField(primary_key=True) coursedescription = models.CharField(max_length=500) coursename = models.CharField(max_length=50) userid = models.IntegerField() code = models.CharField(max_length=50) videolink = models.FileField(default='default_link') # roleid = models.ForeignKey(RoleName, on_delete=models.CASCADE) createddate = models.DateTimeField() imagelink = models.URLField(default='default_link') duration = models.DateTimeField() longdes = models.TextField() coursetype = models.CharField(max_length=50) # classid = models.ForeignKey(TblClass, on_delete=models.CASCADE) assignto = models.CharField(max_length=200) status = models.BinaryField() def _str_(self): return self.coursename class schoolTeacher(models.Model): teacherid = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) address = models.CharField(max_length=200) email = models.EmailField() contact = models.IntegerField() passowrd = models.CharField(max_length=13) image = models.ImageField(default='default.jpg') regno = models.CharField(max_length=20) joiningdate = models.DateTimeField() def … -
can not import views to urls in django 3.1.4
this is my directory this is my views.py from django.contrib import admin from django.urls import path from mysite.mysite.views import hello urlpatterns = [ path('admin/', admin.site.urls), ] this is my urls.py from django.http import HttpResponse def hello(request): return HttpResponse('hello world') but i got this error: No module named 'mysite.mysite' -
Celery runs locally but not in production
My app involves Django, Celery, Redis, and Scrapy. Locally, I fire up Django (python manage.py runserver) and celery (celery -A web_app worker). Then, I trigger a command which runs a scrapy webcrawler (via CrawlerRunner), retrieves some information, and makes additional async calls which are pushed to my task queue. This all works fine. However, when I run celery via Kubernetes (called the same way celery -A web_app worker), my tasks stop running after the scrapy task finished. The worker won't execute any additional tasks unless I restart it. Ideas? What's going on under the hood when I run celery with the same command in Kubernetes versus when I run it locally? -
Django pass all sub-posts into template
I'm trying to show all the sub-posts that are related to the Post in my PostDetailView view but I can't figure out how to get these values from the sub-post class... Models.py class Post(models.Model): title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Subpost(models.Model): title = models.CharField(max_length=100) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.title Views.py def home(request): context = { 'posts': Post.objects.all() } return render(request, 'home/home.html', context) class PostListView(ListView): model = Post template_name = 'home/home.html' context_object_name = 'posts' ordering = ['title'] class PostDetailView(DetailView): model = Post How can I pass in all the sub-posts that are related to the Post to my PostDetailView? -
Django choice.py file or form choices or model choice. Which to use?
I see you can list the choices you want to appear in a dropdown in different places. The forms.py file, in your models.py, or in a separate choices.py file. Which one is ideal and what is the consequence of each choice? forms.py from django import forms # iterable CHOICES =( ("1", "One"), ("2", "Two"), ("3", "Three") ) # creating a form class Form(forms.Form): the_field = forms.ChoiceField(choices = CHOICES) models.py from django.db import models # specifying choices SEMESTER_CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"), ) # declaring a Student Model class Student(models.Model): semester = models.CharField( max_length = 20, choices = SEMESTER_CHOICES, default = '1' ) choices.py (in choices.py file) bedroom_choices = { '1' : 1, '2' : 2, '3' : 3, } choices.py (in views.py file) from .choices import bedroom_choices ... context = { 'bedroom_choices' : bedroom_choices} choices.py (in the template file) <label class="sr-only">Bedrooms</label> <select name="bedrooms" class="form-control"> <option selected="true" disabled="disabled">Bedrooms (Any)</option> {% for key,value in bedroom_choices.items %} <option value="{{key}}" {% if key == values.bedrooms %} selected {% endif %} >{{value}}</option> {% endfor %} </select> -
Changing the content of the page by the user and creating new pages
I am learning Django and would like to know how I can implement editing the content of a page by an authorized user, as well as creating new pages with a fixed template and new URLs by a user with administrator rights. Can you give examples of how to accomplish this task?