Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError 'model' object has no attribute 'get_choices'
I'm trying to send this model class Product(models.Model): title = models.CharField(max_length=100, verbose_name='title', unique=True) text = models.CharField(max_length=200, verbose_name='text', null=True, blank=True) price = models.BigIntegerField('price') description = models.CharField(max_length=500, verbose_name='description') category = models.ForeignKey(Category, on_delete=models.CASCADE) features = models.ManyToManyField(Features, ) created_time = models.DateTimeField(auto_now_add=True, verbose_name='created_time') update_time = models.DateTimeField(auto_now=True, verbose_name='update_time') The Product serializer class ProductSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) features = serializers.ManyRelatedField(child_relation=FeaturesSerializer()) rating = serializers.SerializerMethodField() class Meta: model = Product fields = ( "id", "title", "text", "price", "description", "category", "features", 'rating' ) I found out the problem is in the 'features' field, because if you remove this field in the serializer, then there is no more error, but instead of the 'features' fields, I get the id of the defined 'features' The Features serializer: class FeaturesSerializer(serializers.ModelSerializer): class Meta: model = Features fields = '__all__' Models: class Features(models.Model): key = models.CharField(max_length=200) value = models.CharField(max_length=200, unique=True) views.py class GetItemOfProduct(generics.RetrieveUpdateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [IsAdminOrReadOnly, ] json without 'features' field in serializer: # ... product: title, id, price, description and other ... "features": [ 6, 4, 1 ], I tried to send 'features' field in json with key and value fields for example # ... product: title, id, price, description and other ... "features": [ { "id": 6, … -
Django Admin Inline - same UUID being generated for primary key
When I click on "add new button" in django admin to add another inline item. UUID field (primary key) is same for all inlines. see following gif: -
Image is not being upload Django
I created a post form and embedded with the template and view as usual, when I test the form and try to create a new post all the fields process and save the data correct to the object except the image object. It does not prompt me an error, it is like ignoring completely the file that I upload. The post model: from django.db import models from User.models import User class Post(models.Model): author = models.ForeignKey(User, related_name="post", on_delete=models.CASCADE) title = models.CharField(max_length=280) content = models.CharField(max_length=500) post_image = models.ImageField(upload_to="post_images/", blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) The form class: class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content', 'post_image'] The post_create view: def create_post(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): author = request.user title = form.cleaned_data['title'] content = form.cleaned_data['content'] post_image = form.cleaned_data['post_image'] post = Post.objects.create(author=author, title=title, content=content, post_image=post_image) return redirect("home") form = PostForm() return render(request=request, template_name="post/create_post.html", context={"form": form}) The create_post.html {% extends "base/base.html" %} {% block content %} <form method="POST" action="{% url 'create_post' %}"> {% csrf_token %} {{ form.as_p }} <button type="submit">Create Post</button> </form> {% endblock %} The urls: from django.urls import path from . import views urlpatterns = [ path("create_post", views.create_post, name="create_post") ] When I create … -
Stripe integration is giving an error in views.py
my stripe integration code in the views.py code is following: def checkoutsession(request): try: checkout_session = stripe.checkout.Session.create( line_items=[ { 'price': '20', 'quantity': 1, }, ], mode='payment', success_url='http://localhost:3000' + '/success.html', cancel_url='http://localhost:3000' + '/cancel.html', ) except Exception as e: return str(e) return HttpResponse(checkout_session.url, code=303) The error: AttributeError: 'str' object has no attribute 'get' the HTML code is following: {% extends 'basic.html' %} {% block body %} <script src="https://js.stripe.com/v3/"></script> <section> <div> <div> <h3>Pay</h3> <h5>$20.00</h5> </div> </div> <form action="/checkoutsession" method="POST"> {% csrf_token %} <button type="submit" id="checkout-button">Checkout</button> </form> </section> {% endblock body %} I am integrating a sandbox payment gateway. The frontend is displaying correctly , but the backend is problematic.I am using django framework. -
Nginx Is Showing the Default Page Instead of the Django Application
I am hosting a django website on gunicorn/nginx with ubuntu 22.04. I am following below guide for configuration. it is still showing the default nginx site. (I know there are similar question and also the troubleshooting guide and potential reasons also given in the document i am following; I tried everything but could not solve the issue. Infrastructure : 1) ubuntu 22.04 2) Hestial CP - Using for firewall instead using ufw (bcoz with Hestia default ufw is not installed) 3) Postgres 4) Django 5) gunicorn/nginx Followed all the steps and performed the verification at each stage the document suggest and its showing positive results. but when i am trying to access my site it is still showing the default nginx site. Configuration: etc/nginx/sites-available/myproject server { listen 80; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myuser/main/myproject; } location / { include proxy_params; proxy_pass //unix:/run/gunicorn.sock; } } etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=myuser Group=www-data WorkingDirectory=/home/myuser/main/myproject ExecStart=/home/myuser/main/envProject/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application [Install] WantedBy=multi-user.target gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target Firewall (I have opened all major ports without ip restrictions, shall start closing once the setup works) PS: … -
Missing csrf_token in application cookies
I have problem with setting my csrf_token in cookies which i have to retrieve in order to use it in the next API call Response header Application cookies CSRFToken.jsx import React, { useState, useEffect } from "react"; import axios from "axios"; const CSRFToken = () => { const [csrftoken, setcsrftoken] = useState(''); const getCookie = (name) => { let cookieValue = null; if (document.cookie && document.cookie !== "") { let cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { let cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; }; useEffect(() => { const fetchData = async () => { try { await axios.get(`${import.meta.env.VITE_APP_API_URL}/api/csrf_cookie`); } catch (error) {} }; fetchData(); setcsrftoken(getCookie('csrftoken') || ""); }, []); return ( <input type="hidden" name="csrfmiddlewaretoken" value={csrftoken} /> ); }; export default CSRFToken; Backend: @method_decorator(ensure_csrf_cookie, name='dispatch') class GetCSRFToken(APIView): permission_classes = (permissions.AllowAny, ) def get(self, request, format=None): return Response({ 'success': 'CSRF cookie set' }) Any help provided will be much appreciated, thanks! I should use csrftoken in API Call which i need to get from cookies, but they are not provided export const login = (email, password) => … -
API issue for webpage with Django+Rest backend and React+Axios frontend
I am developing a webpage ("loading" is rendered on the page when the datapoints cannot get fetched via the API) that will be used to display some data from a IOT project I am doing. The backend is written using Django with the Rest framework. The frontend is written in React and to handle http requests, axios is used. I am new to web development so I started writing everything without a thought of deploying and when I got everything up and running localhost on my maching, I started looking into how to deploy it. I then decided on using Docker, Nginx and Gunicorn to do this but seeing as I had written everything outside of docker, it was not as straight forward as I would have liked. I got everything to work except the API calls from axios to the backend. One of all the issues I have gotten is the Failed to load resource: the server responded with a status of 404 (Not Found).Here is the link to the Github repo where the code is stored, I figure it might be easiest to look through there because of the amount of code and me not understanding where the … -
how i can put two action for a html-python from?(Django)
I working on a django project which is employee management system. every employee has a card fill with personal information and this is a text box and a dislike button in form, working like that every time manager fill textbox with a number and pressing dislike button and the amount from salary and a SMS going to employee phone number. now I added a like button and i want when employee input a number and pressing like button employee have a increase on salary as given amount. have i can put two action on my form? view.py class PenaltyEmployee(LoginRequiredMixin, UserPassesTestMixin, generic.View): def post(self, request, pk): employee = get_object_or_404(Employee, pk=pk) penalty_amount = int(request.POST.get('penalty_amount')) employee.salary -= penalty_amount employee.save() employee_phone_number = employee.phon_number api_key ='#' url = '#/%s/#' %api_key pay_load = { 'sender' : '#', 'receptor': employee_phone_number, 'message': 'penalty' } res = requests.post(url, data = pay_load) return redirect('home') def test_func(self): return True and this is my list_view.html <form method="POST" action="{% url 'penalty' yaroo.pk %}"> {% csrf_token %} <input type="number" name="penalty_amount" placeholder="Enter penalty amount"> <button type="submit" class="btn btn-secondary"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" class="bi bi-hand-thumbs-down" viewBox="0 0 16 16"> <path> </path> </svg> </button> <p> | </p> <!-- ... this is my like button ... --> <button … -
boto3 call works in Python console but not in Django app -- exact same code, exact same machine
I have the following piece of code. (Redacting the value of COGNITO_POOL, but otherwise this is the exact code I am running.) AWS_REGION = "us-gov-west-1" COGNITO_POOL = "**********" import boto3 def demo(): client = boto3.client("cognito-idp", region_name=AWS_REGION) output = client.list_users( UserPoolId=COGNITO_POOL, Filter='email = "test@email.com"' ) print(output) I am running this on an EC2 instance, which has all the right permissions set up. I know it has the right permissions, because when I remote into the instance, open a Python shell, run the above code, and call demo(), it works fine and spits out a list. However, when a Django website running on the same machine imports the demo() method and runs it, I get: botocore.exceptions.ClientError: An error occurred (UnrecognizedClientException) when calling the ListUsers operation: The security token included in the request is invalid. I have done everything I can think of to make the shell run under the same conditions as Django. I tried activating my virtual environment before running the test. I tried writing a script that would import the demo function and execute it, then ran that script from the command line. I ran it under the same user as Django. No matter what I do, shell works and … -
How do I solve GET 500 (Internal Server Error) error?
After the + button is clicked The quantity increases when I refresh the page The console shows the 500 Internal Server Error every time I click the + button. Also, the ajax coding for the button only works when I refresh the page. Could someone enlighten me what causes this error and how to solve it? related section in cartpage.html {% extends 'base.html' %} {% load static %} {% block content %} <div class="d-flex"> <div class="border rounded p-4 m-4" style="width:1000px;"> <p class="display-4 pl-4 ml-4">Shopping Cart</p> <hr> <table class="table table-fixed"> <thead class="thead-dark"> <tr> <th></th> <th class="w-5">Image</th> <th>Product</th> <th>Quantity</th> <th>Price</th> </tr> </thead> <tbody> <tr> {% for cart in cart %} <td><ion-icon name="close-outline"></ion-icon></td> <input type="hidden" name="prodid" value="{{product.ProdID}}" id="prodid" class="prodid"> <td class="w-5"><image src="{{ cart.product.ProdPic.url }}" style="height:80px; width:65px;" class="rounded-circle"></td> <td>{{cart.product.ProdName}}</td> <td class="cart-product-quantity"> <input type="button" pid = "{{ cart.product.ProdID }}" class="minus-cart btn btn-light btn-circle btn-sm" value="-"></input> <span id="quantity" min="1">{{ cart.item_qty }}</span> <input type="button" pid = "{{ cart.product.ProdID }}" class="plus-cart btn btn-light btn-circle btn-sm" value="+"></input> </td> <td>RM{{cart.product.ProdPrice}}</td> </tr> {% endfor %} </tbody> </table> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <!-- links to popper js and bootstrap js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <script> $(document).ready(function(){ $('.plus-cart').click (function(){ var id=$(this).attr("pid").toString(); console.log(id) $.ajax({ type : "get", url … -
ImportError: cannot import name 'People' from partially initialized module 'Contacts.models' (most likely due to a circular import)
I have two models. People and Related Contacts. Related contacts has a foreign key relation from People. I don't understand why I'm getting a circular import yet they are not related to each other. The error from Miscellaneous.models import PersonContactTypes, Genders File "D:\Projects\Amicas\Back-End\Miscellaneous\models.py", line 2, in <module> from Contacts.models import People ImportError: cannot import name 'People' from partially initialized module 'Contacts.models' (most likely due to a circular import) Company model class Companies(models.Model): contact_type = models.ForeignKey(CompanyContactTypes, verbose_name='Contact Type', on_delete=models.CASCADE, max_length=255, null=True, blank=True) created_by = models.ForeignKey(User, verbose_name="Created By", on_delete=models.CASCADE) tenant = models.ForeignKey(Tenant, verbose_name='Tenant', max_length=255, null=True, blank=True, on_delete=models.CASCADE) People model from Tenants.models import Tenant from django.db import models from Members.models import User from django_countries.fields import CountryField from Miscellaneous.models import PersonContactTypes, Genders class People(models.Model): contact_type = models.ForeignKey(PersonContactTypes, verbose_name='Contact Type', on_delete=models.CASCADE, max_length=255, null=True, blank=True) gender = models.ForeignKey(Genders, verbose_name='Gender', on_delete=models.CASCADE, max_length=255, null=True, blank=True) created_by = models.ForeignKey(User, verbose_name="Created By", on_delete=models.CASCADE) company = models.ForeignKey(Companies, verbose_name='Company', max_length=255, null=True, blank=True, on_delete=models.SET_NULL) tenant = models.ForeignKey(Tenant, verbose_name='Tenant', max_length=255, null=True, blank=True, on_delete=models.CASCADE) Related Contacts model from django.db import models from Contacts.models import People from Tenants.models import Tenant from Members.models import User class RelatedContacts(models.Model): name = models.ForeignKey(People, verbose_name='Name', null=True, blank=True) created_by = models.ForeignKey(User, verbose_name="Created By", on_delete=models.CASCADE, blank=False, null=False) tenant = models.ForeignKey(Tenant, verbose_name='Tenant', max_length=255, null=False, … -
Limit Foreignkey choices in form
I have a form which has a foreignkey field 'mon_1', I am trying to limit it's choice by using init () method, but no changes is reflected in my webpage (Even if I make errors intentionally, it doesn't throw an error). Note: 'limit_choices_techers' function works fine, no error in that piece of code #forms.py def limit_choices_teachers(period): limited_choice = [] already_used_choice = TimeTable.objects.values_list(period,flat=True) #returns id of the teacher already linked on that period for teacher in Teachers.objects.all(): if teacher.id not in already_used_choice: limited_choice.append(teacher) return limited_choice class TimeTableForm(forms.ModelForm): class Meta(): model = models.TimeTable fields = ('__all__') def __init__(self, *args, **kwargs): super(TimeTableForm, self).__init__(*args, **kwargs) self.fields['mon_1'].queryset = limit_choices_teachers('mon_1') #models.py class Subjects(models.Model): Subjects_available = ( ('Maths','Maths'), ('English','English'), ('Computer','Computer'), ('Chemistry','Chemistry'), ('Physics','Physics'), ) subject_name = models.CharField(max_length = 256,choices = Subjects_available,unique=True) def __str__(self): return str(self.subject_name) class Teachers(models.Model): classes_available = ( ('Grade 1','Grade 1'), ('Grade 2','Grade 2'), ('Grade 3','Grade 3'), ('Grade 4','Grade 4'), ('Grade 5','Grade 5'), ('Grade 6','Grade 6'), ('Grade 7','Grade 7'), ('Grade 8','Grade 8'), ('Grade 9','Grade 9'), ('Grade 10','Grade 10'), ('Grade 11','Grade 11'), ('Grade 12','Grade 12'), ) name = models.CharField(max_length = 256) subject = models.ForeignKey(Subjects,on_delete=models.CASCADE,related_name='teacher_subject') teaches_for_class = models.CharField(max_length=256,choices=classes_available) def __str__(self): return str(self.subject) + ' - ' + self.name class TimeTable(models.Model): standard_choice = ( ('Grade 1','Grade 1'), ('Grade 2','Grade … -
How to delete password form (ps i ve redefined user model, authentication)?
i ve got a problem. First of all this is my idea: a user registers his account using username and his face. The website takes his photo. And so ive redefined authenctication, user model and so on. But i CANT DELETE PASSWORD FORM!!! let me show you my code first models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) # Create your models here. \#user's part class UserManager(BaseUserManager): def create_user(self, username, \*\*extra_fields): if not username: raise ValueError('Users must have an username ') user = self.model( username=username, **extra_fields ) user.set_unusable_password() user.save(using=self._db) return user def create_staffuser(self, username): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( username, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, username): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( username, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): username = models.CharField( verbose_name='username', max_length=255, unique=True ) main_img = models.ImageField(upload_to='main_imgs/%Y/%m', verbose_name='Главное фото') checking_photo = models.ImageField(upload_to='checking_photo/%Y/%m', verbose_name='Временное фото для проверки ') is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a … -
why stripe button is not appearing?
I am integrating stripe checkout gateway in my website. For this , I am following a tutorial for this. I am copying its code as it is. However, the button is not displaying for me. {% extends 'basic.html' %} <h2> buy</h2> <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="{{ key }}" data-description = "payment gateway" data-amount = "500" data-locale="auto"> </script> I know that their is no button tag but the tutorial I am following is also the same . I tried to implement a button which will take me to the checkout form. -
Setting up a webhook for a telegram bot in django
I want to make a simple telegram bot on Django, I have seen some tutorials on how to make a bot using plain python but I need to make it on Django I followed this tutorial and tried to adapt it to a Django project https://www.youtube.com/watch?v=vZtm1wuA2yc this is my views.py from typing import Final from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from telegram import Update from telegram.ext import CommandHandler, MessageHandler, filters, ContextTypes, Application API_KEY: Final = 'myapikey' BOT_USERNAME: Final = 'myusername' # Comands async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text("Hello! I am fellow human!, Im the bot and I want to play a game with you.") async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text("I will help you somehow") async def custom_command(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text("This is a custom command") # Responses def handle_response(text: str) -> str: text = text.lower() if 'hello' in text: return 'Howdy' if 'how are you' in text: return 'Fine' return "Im sorry I don't understand" async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): message_type: str = update.message.chat.type text: str = update.message.text print(f'User => {update.message.chat.id} in {message_type}: "{text}"' ) if message_type == 'group': if BOT_USERNAME in text: new_text: str = text.replace(BOT_USERNAME, '').strip() # Remove username from … -
django ORM - subqueries with Max
I'm having some issues when trying to use the Django ORM with subqueries and the Max function (db: PostgreSQL 15) On the following model: class Task(models.Model): declaration = models.ForeignKey( Declaration, null=True, default=None, on_delete=models.CASCADE, related_name="tasks", ) sequence = models.PositiveIntegerField(blank=True, null=True) # # other fields I'm trying to filter tasks related to a declaration with the highest sequence. here's my attempt: sequences = Task.objects.filter(declaration=OuterRef("declaration")).exclude(sequence__isnull=True).order_by("sequence").distinct().values("sequence") max_sequences = sequences.annotate(max_seq=Max("sequence")).values("max_seq") qs = Task.objects.filter(sequence=Subquery(max_sequences)) however iterating the qs throws this error: ProgrammingError: more than one row returned by a subquery used as an expression inspecting the SQL, looks like this: SELECT "task"."id", "task"."declaration_id", "task"."sequence" FROM "task" WHERE "task"."sequence" = ( SELECT "subquery"."max_seq" FROM (SELECT DISTINCT MAX(U0."sequence") AS "max_seq", U0."sequence" FROM "task" U0 WHERE (U0."declaration_id" = ("task"."declaration_id") AND NOT (U0."sequence" IS NULL)) GROUP BY U0."sequence" ORDER BY U0."sequence" ASC) subquery) and the execution gives back the same error. Adding LIMIT 1 to the first subquery solves it on the db shell: SELECT "task"."id", "task"."declaration_id", "task"."sequence" FROM "task" WHERE "task"."sequence" = ( SELECT "subquery"."max_seq" FROM (SELECT DISTINCT MAX(U0."sequence") AS "max_seq", U0."sequence" FROM "task" U0 WHERE (U0."declaration_id" = ("task"."declaration_id") AND NOT (U0."sequence" IS NULL)) GROUP BY U0."sequence" ORDER BY U0."sequence" ASC LIMIT 1) subquery)` but I don't know how … -
Common User management for Django project ecosystem
I have been working with Django for the last few months and have built some projects in it. I was wondering whether it is possible for the distinct Django projects to share a common-use authentication and authorization project? There is a user management portal for the internal employees where the admin can add various employees to different user roles (like a manager, etc.). I will then define in the other projects what user role can access what part of the application statically. Additional parameters: There will be read-and-write operations on the user from all the projects There will be user-specific data (not user role specific user specific) Until now I have looked at the Django multi-database support which can solve my user authentication problem, but there is a catch in the authorization part where the foreign key constraints cause some problems in the models Currently, I have written a database router and am creating a user management portal for the authentication of users from a single source. -
Chained select inputs using Django CBV
I am trying to create an interface for a teacher to set homework tasks. This homework includes a student, a chapter, and questions belonging to a selected chapter. Therein lies my problem, I would like for my chapter dropdown to limit the selection from my question dropdown. Here is the current model, I added a chapter to simplify this process however ideally the chapter is not a necessary part of the homework, it only serves as a filter for the questions. class Homework(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) chapter = models.ForeignKey( Chapter, on_delete=models.SET_NULL, null=True, related_name="chapter_homework" ) question = models.ForeignKey( Question, on_delete=models.CASCADE, related_name="homework" ) agenda = models.ForeignKey( Agenda, on_delete=models.CASCADE, related_name="homeworks" ) This is the CreationView I have modified : class HomeworkCreationView(CreateView): template_name = "agenda/homework_create.html" form_class = HomeworkForm success_url = reverse_lazy("agenda:create_homework") def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['chapters'] = Chapter.objects.filterByAuthor(self.request.user) return context def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["user"] = self.request.user return kwargs And this is a function based view which is meant to asynchronously update the question choices : def loadQuestions(request): chapter_id = request.GET.get('chapter') questions = Question.objects.filterByChapterID(chapter_id).order_by('title') return render(request, 'agenda/question_dropdown_list_options.html', {'questions':questions}) Here is the form : class HomeworkForm(forms.ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop("user", None) super().__init__(*args, **kwargs) teacher = user.userToTeacher() self.fields["chapter"].queryset … -
Django - ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.User' that has not been installed
I went through a few related questions but not sure how to resolve the error when trying to use the custom User model with registration form. Error: ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.User' that has not been installed register.html <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Submit</button> </form> views.py: from django.contrib.auth.forms import UserCreationForm from .models import Users from .forms import UsersForm def registerPage(request): form = UserCreationForm() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'base/register.html', context) models.py: from django.db import models from .manager import MyUserManager from django.contrib.auth.models import AbstractBaseUser from django.utils import timezone from django.contrib.auth import get_user_model User = get_user_model() class User(AbstractBaseUser): email = models.EmailField(max_length=255,unique=True,) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin setting.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products.apps.ProductsConfig', 'pages.apps.PagesConfig', 'services.apps.ServicesConfig', 'users' ] AUTH_USER_MODEL = 'users.User' forms.py: type hfrom django import forms from django.core.exceptions import ValidationError from .models import User class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Enter Password Again', widget=forms.PasswordInput) class … -
Django custom .mo filenames not working for translations?
I have been playing with django app translation for a while now. But as my main app is becoming more complex, I've seen that some of the strings are not anymore detected by "makemessages", probaly as they originate from lists, and are only translated in the template through a {% trans my_list_item %} tag That means that each time I'm making a makemessages, those msgids are not detected, so the django.po file is updated, and my "undetected translations" are commented out. Ok, I can live with it. My next move is to create a separate po file undetected_messages.po where I stick all the translations which remain undetected. But the translations are not happening ... even if the corresponding undetected_messages.mo file seems to be created ok, and seems to contain the right info. When I put the undetected translation in the django.po file, everthing seems to happen as expected. But not when they are in a different po file with custom namefile. Any idea why? Any idea how I could solve the issue? Subsidiary question: Any idea how I could keep the translations linked to the "admin" module of each app in a separate file ... to avoid having those translations … -
AttributeError at /signup
I am trying to add a signin feature to my movie project on django and this error is showing: AttributeError at /signin 'str' object has no attribute 'POST' this is the template, signin.html {% extends 'base.html' %} {% load static %} {% block content %} <div class="container"> <h1>Sign-in</h1> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> <label class="form-label"></label> <input class="form-control" type="text" name="u" placeholder="Enter your username"> <div class="form-text"></div> </div> <div class="mb-3"> <label class="form-label"></label> <input class="form-control" type="text" name="p" placeholder="Enter your password"> <div class="form-text"></div> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> {% if messages %} {% for i in messages%} <ul class='messages'> <li>{{i}}</li> </ul> {% endfor %} {% endif %} </div> {% endblock %} path from django.urls import path from movie import views app_name='movie' urlpatterns = [ path('signin',views.signin,name='signin'), ] views.py from django.contrib.auth.models import User from django.contrib.auth import authenticate,login,logout from django.contrib import messages def signin(request): if(request.method=='POST'): u=request.method.POST['u'] p=request.method.POST['p'] user=authenticate(username=u,password=p) if user: login(request,user) return home(request) else: messages.error(request,'Invalid Credentials') return render(request,'signin.html') The error is showing after clicking submit... -
Deploying django to vercel not working due to routing issues
I have a django project I am trying to host on vercel. When I configure my vercel.json as such, { "builds": [ { "src": "drinksData/wsgi.py", "use": "@vercel/python" } ], "routes": [ { "src": "/(.*)", "dest": "drinksData/wsgi.py" } ] } The application works, like the templates load but then if I try to access any of the JSON response views and treat it like an API, I get a CORS issue. So trying to follow the docs I then change it to this: { "builds": [ { "src": "drinksData/wsgi.py", "use": "@vercel/python" } ], "routes": [ { "src": "/(.*)", "dest": "drinksData/wsgi.py" } ], "headers": [ { "source": "/(.*)", "headers": [ { "key": "Access-Control-Allow-Credentials", "value": "true" }, { "key": "Access-Control-Allow-Origin", "value": "*" }, { "key": "Access-Control-Allow-Methods", "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT" }, { "key": "Access-Control-Allow-Headers", "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" } ] } ] } But then I get a deployment issue about routes and headers clashing. So then I try using rewrites: { "builds": [ { "src": "drinksData/wsgi.py", "use": "@vercel/python" } ] ,"rewrites" : [{ "source": "/(.*)", "destination": "drinksData/wsgi.py" }], "headers": [ { "source": "/(.*)", "headers": [ { "key": "Access-Control-Allow-Credentials", "value": "true" }, { "key": "Access-Control-Allow-Origin", "value": "*" }, { … -
Django: Optimization using forms .has_changed in save method
I just noticed that django forms has a method .has_changed() and I'm just wondering if it would be a good idea for optimization to use it by overriding the save method and checking if form has changed before hitting the db? By doing this we would actually skip one unnecessary call to the db. What do you guys think about it? Would look something like this: def save(self, commit=False): property = super(PropertyPriceForm, self).save(commit=False) if self.is_valid(): ... if commit and self.has_changed(): property.save() return property -
When to use DRF Serializer's methods .save(), .create() and .to_internal_value?
On DRF documentation we have that: .to_internal_value() - For write operations. .create() - For saving instances. .save() - To persists the validated data into an object instance. It seems that we can do the same stuff with any of these. So what is the best practice to use them? -
Why are my images not loading in Django? - "GET /static/app/piechart.jpg HTTP/1.1" 404 1807
I cannot seem to load in an image in a website I'm creating in Django. I get the error "GET /static/app/piechart.jpg HTTP/1.1" 404 1807 in terminal whenever I load my site. My page's css stylesheet loads in without problems but the image does not load. These are the important snippets of code from my project files. I would assume that the error lies somewhere here. settings.py STATIC_URL = '/static/' STATIC_ROOT = "/Users/NAME_RETRACTED/Projects/stockOpt/app/static" STATICFILES_DIRS = [ BASE_DIR / "static", "/app/static", ] urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from app import views urlpatterns = [ path('admin/', admin.site.urls), path("", include("app.urls")), path('', views.index, name='views') ] .html files stylesheet link <link rel="stylesheet" type="text/css" href=" {% static 'app/styles.css' %} "> image tag <img src=" {% static 'app/piechart.jpg' %} " alt=" Image didn't load"/> This is what my file structure looks like. The image is in app/static/app/piechart.jpg. Now I assume that the problem either lies in how I referenced the static files in the .html files since when I command+click (follow link) on both references, it says "The editor could not be opened because the file was not found." OR it's something to do with …