Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django is not updating my database after submitting my form
I have created a model and a form, both are working correctly, and I have added data to the database using the admin module models.py class Client(models.Model): firstname = models.CharField(blank=True, max_length=30) lastname = models.CharField(blank=True, max_length=15) company = models.ForeignKey(Company, on_delete=models.CASCADE, default="company") position = models.CharField(blank=True, max_length=15) country = CountryField(blank_label='(select country)') email = models.EmailField(blank=True, max_length=100, default="this_is@n_example.com") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) phone = PhoneField(default="(XX)-XXX-XXX") def __str__(self): return f'{self.firstname}' forms.py class ClientForm(forms.ModelForm): class Meta: model = Client fields = ('firstname', 'lastname',"position",'country','email','phone') views.py @login_required def add_client(request): if request.method == "POST": client_form = ClientForm(instance=request.user, data=request.POST) if client_form.is_valid(): client_form.save() messages.success(request, 'You have successfully added a client') else: messages.success(request, "Error Updating your form") else: client_form = ClientForm(instance=request.user) return render(request, "account/add_client.html", {'client_form':client_form}) add_client.html {% extends "base.html" %} {% block title %}Client Information {% endblock %} {% block content %} <h1> Client Form</h1> <p>Please use the form below to add a new client to the database:</p> <form method="post" enctype="multipart/form-data"> {{ client_form.as_p }} {% csrf_token %} <p><input type="submit" value="Save changes"></p> </form> {% endblock %} Everything seems to be working fine, I can submit data in the website and I get a message stating that the the submission when fine, however, when I check the admin website and inspect the database, … -
Django Foreign Key Related Objects Not Saving Changes, Cannot Edit
I have two models, Movie and Review. Review has a foreign key field related to Movie. I have been trying to edit the Review objects associated with an instance of Movie. models.py class Movie(models.Model): title = models.CharField(max_length=160) class Review(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name='reviews') author = models.CharField(max_length=150) active = models.BooleanField(default=True) views.py # Create and save movie object movie = Movie(title="Nightcrawler") movie.save() # Create and save two review objects review1 = Review(movie=movie, author="John", active=True) review2 = Review(movie=movie, author="Rob", active=False) review1.save() review2.save() print("Before: " + movie.title + " has " + str(len(movie.reviews.all())) + " reviews.") active_reviews = movie.reviews.filter(active=True) print("There are " + str(len(active_reviews)) + " active reviews.") movie.reviews.set(active_reviews) movie.reviews.first().author = "Abby" # Try and save both objects just for good measure. # Not sure if it is necessary to do this. Does not # seem to work anyway movie.reviews.first().save() movie.save() print("After: " + movie.title + " has " + str(len(movie.reviews.all())) + " reviews.") print("Author of the first review is: " + str(movie.reviews.first().author)) The output of the views.py code is as follows: Before: Nightcrawler has 2 reviews. There are 1 active reviews. After: Nightcrawler has 2 reviews. Author of the first review is: John I want and expected the changes made to movies.reviews … -
Django is not picking CSS file
Django is not picking CSS file from static folder, though its picking image file in static folder. here is my Django structure rootapp -settings.py -urls.py -wsgi.py app1 -views.py app2 -views.py template -app1home -app2home -base static -logo.png -style.css urls.py from django.views.static import serve urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^media/(?P<path>.*)$', serve, kwargs={'document_root': settings.MEDIA_ROOT}), re_path(r'^static/(?P<path>.*)$', serve, kwargs={'document_root': settings.STATIC_ROOT}) ] In base.html.I have {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> It is picking logo as follows in the base file <img src="{% static "logo.png" %}" alt="logo"></a> <h1>Disease Diagnosis via AI</h1> But not picking style.css file. CSS file looks like h1{ margin-top: 10px; color: red; } Settings file MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Also, media paths are working -
Django template: two different font sizes on same line
I'd like to be able to render two different font sizes on the same line using a Django template. Here's my code: <div> <h5>Details</h5> </div> <div> <h6>Creator By:</h6> {{ order.creator }} </div> <div> <h6>Category:</h6> {{ order.category }} </div> This is rendering as follows: Details Created By: Janice Category: Automotive ############################################# Notice that the variables are skipping to a new line. I would like to render these as follows (on the same line): Details Created By: Janice Category: Automotive Is this just a simple mistake I've made with the HTML? Or, is there some nuance I'm missing with the Django form? Thank you! -
How to get the related field of a related field in Django REST Framework serializers?
Imagine having three Django Models: class A: Susu = models.CharField() # props... class B: a = models.ForeignKey(A) Bar = models.CharField() # props... class C: b = models.ForeignKey(B) c_prop # props... I'd like to write a serializer for C objects, such that they are represented as { "c_prop": "Foo", "b" : { "Bar": "Agu" }, "a" : { "Susu", "Jaja" } } i.e. the foreign key of the B class is representated at the same level of nesting as the B object (instead of "within" B) I have these serializers: class ASerializer(serializers.ModelSerializer): class Meta: model = A fields = ("Susu", ) class BSerializer(serializers.ModelSerializer): class Meta: model = B fields = ("a", ) class CSerializer(serializers.ModelSerializer): b = BSerializer class Meta: model = C fields = ('c_prop', 'b', 'a', ) # <-- How to get the 'a' here (not just the PK of 'a' but the nested object representation? -
Django authentication/user create functions
I'm trying to start a project in Django, where users can register on my site and subsequently login/logout when they visit it. I have found a template for a user creation view, that looks like this: from django.views.generic import CreateView from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login class CreateUserView(CreateView): template_name = 'register.html' form_class = UserCreationForm success_url = '/' def form_valid(self, form): valid = super(CreateUserView, self).form_valid(form) username, password = ( form.cleaned_data.get('username'), form.cleaned_data.get('password1') ) new_user = authenticate(username=username, password=password) login(self.request, new_user) return valid Now, I'm wondering why a call to authenticate with a non-existing username should create a new user. I'm trying to find any documentation for the imported functions authenticate and login, however, I can only find documentation for the User-model, AnonymousUser object, Permission-model, Group-model, some authentication backends and signals/validators, but I don't find any documentation for (standalone) functions authenticate and login. Can someone provide me the with a link to the relevant documentation or at least confirm that the way as they are used above is (still?) correct? -
Put the value of Not null in a field using Alterfield
In my Django project, I first added new fields to the project and set their null value to true, and then I wanted to set the Not null value for those fields via AlterField, but I was unable to do so. In this project, I manually created two migrations for these changes. 0002_edit_model: from django.db import migrations,models def excavating_information(apps, schema_editor): Person = apps.get_model('people', 'Person') #get data from fullname field full_name = [i.split(';') for i in Person.objects.values_list('fullname', flat=True)] full_name_finall = [f for i in full_name for f in i] #get data from information field information_field = [i.split(';') for i in Person.objects.values_list('information', flat=True)] information_field_final = [f for i in information_field for f in i] #Extract data from fullname first_name = [k[11:] for k in full_name_finall if k[1] == 'i'] last_name = [k[10:] for k in full_name_finall if k[1] == 'a'] #Extract data from information id_code = [k[8:] for k in information_field_final if k[1] == 'd'] born_in = [k[8:] for k in information_field_final if k[1] == 'o'] bith_year = [k[11:] for k in information_field_final if k[1] == 'i'] #final step for person,f, l, i, b, bi in zip(Person.objects.all(),first_name, last_name, id_code, born_in, bith_year): #update fields in person model person.objects.update(first_name=f, last_name=l, id_code=i, born_in=b, birth_year=bi) class … -
Optimizing Django with prefetch and filters in large table
I had a database in php/html using MySQL and am transferring this to a Django project. I have all the functionalities working, but loading a table of the data I want is immensely slow because of the relations with other tables. After searching for days I know that I probably have to use a model.Manager to use prefetch_all. However, I am not stuck on how to call this into my template. I have the following models(simplified): class OrganisationManager(models.Manager): def get_queryset_director(self): person_query = Position.objects.select_related('person').filter(position_current=True, position_type="director" ) return super().get_queryset().prefetch_related(Prefetch('position_set', queryset=person_query, to_attr="position_list")) def get_queryset_president(self): person_query = Position.objects.select_related('person').filter(position_current=True, position_type="president" ) return super().get_queryset().prefetch_related(Prefetch('position_set', queryset=person_query, to_attr="position_list")) class Person(models.Model): full_name = models.CharField(max_length=255, blank=True, null=True) country = models.ForeignKey(Country, models.CASCADE, blank=True, null=True) birth_date = models.DateField(blank=True, null=True) class Organisation(models.Model): organisation_name = models.CharField(max_length=255, blank=True, null=True) positions = models.ManyToManyField(Person, through='Position') # positions are dynamic, even though there should only be only one director and president at each given time, a onetoone model wouldn't work in this scenario objects = OrganisationManager() # The following defs are currently used to show the names and start dates of the director and president in the detailview and listview def director(self): return self.position_set.filter(position_current=True, position_type="director").last() def president(self): return self.position_set.filter(position_current=True, position_type="P").last() class Position(models.Model): POSITION_TYPES = ( ('president','President'), ('director','Director'), ) … -
Displaying javascript style alert after form submit in Django
I am creating a simple application in Django. I have a form on a page and after the form is submitted, I want to redirect the user to a new page and display a JavaScript alert like this. How would I go about doing this? My code is down bellow. This is the function that stores the form data and redirects to a new page, the new page only has simple html on it. def donate(request): if request.method == "POST": title = request.POST['donationtitle'] phonenumber = request.POST['phonenumber'] category = request.POST['category'] quantity = request.POST['quantity'] location = request.POST['location'] description = request.POST['description'] # New part. Update donor's stats. UserDetail.objects.filter(user=request.user).update(donations=F('donations') + 1) UserDetail.objects.filter(user=request.user).update(points=F('points') + (quantity * 2)) return render(request, 'dashboard.html', ) return render(request,'donate.html') I have done lot's of research but I can not find a logical solution to my problem. Past questions have asked me to use Django messages, which is something I don't want to use. Thank you to everyone who helps! -
Django App - I have a list of students which I upload within the app, how can I connect the student list with login so they only create new password
from django.shortcuts import render from .forms import csvForm from .models import csvList import csv from portal.models import Studentlist Create your views here. def upload_file_view(request): form = csvForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = csvForm() obj = csvList.objects.get(activated=False) with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) for i, row in enumerate(reader): if i==0: pass else: print(row) #studID = row[0] middlename = row[1] #User.objects.get(username=row[1]) gender = row[2].capitalize firstname = row[3] #User.objects.get(username=row[3]) tPeriod = row[4] unitNum = row[5] teamid = row[6] Studentlist.objects.create( id = int(row[0]), surname = middlename, title = gender, name = firstname, teachPeriod = tPeriod, unitCode = unitNum, teamId = teamid ) obj.activated = True obj.save() return render(request, 'home.html', {'form': form}) -
unexpected keyword argument
enter code here class Client(models.Model): enter code here name = models.CharField(max_length=100, verbose_name="Client name") enter code here description = models.TextField(verbose_name="Client say") enter code here image = models.TextField(upload_to="clients", default="default.png") enter code here def __str__(self): enter code here return self.name i'm getting a TypeError: init() got an unexpected keyword argument 'upload_to' -
unable to get related table field data using select_related django
using Select_related i got the query what exactly i need. but i unable to figureout how to see anyfield or all field of related tables. prod = ProblemProductBind.objects.all().select_related('prod_id') >>> print(prod.query) SELECT "repair_problemproductbind"."id", "repair_problemproductbind"."prob_id_id", "repair_problemproductbind"."prod_id_id", "repair_problemproductbind"."A_price", "repair_problemproductbind"."B_price", "repair_problemproductbind"."A_buying_price", "repair_problemproductbind"."B_buying_price", "repair_problemproductbind"."A_ISmash_price", "repair_problemproductbind"."B_ISmash_price", "repair_problemproductbind"."isLCD", "repair_problemproductbind"."askQuote", "repair_problemproductbind"."time_stamp", "products_products"."id", "products_products"."pName", "products_products"."cat_id_id", "products_products"."subCat_id_id", "products_products"."type_id_id", "products_products"."brand_id_id", "products_products"."pImage", "products_products"."weRepair", "products_products"."weRecycle", "products_products"."time_stamp" FROM "repair_problemproductbind" INNER JOIN "products_products" ON ("repair_problemproductbind"."prod_id_id" = "products_products"."id") -
How to reorder the fields when we have two forms of two models in Django?
How can I reorder the fields in the form of my Django models ? I have two models : Student inherited from the User class inherited from an AbstractBaseUser class. I want the student to register on my webpage having these fields in this order : firstname ; lastname ; address ; email ; password. But Firstname and Lastname are in the User class, address in the Student class, then email and password in the User class. How can I reorder them ? Here is my code : forms.py : class CreateUserForm(UserCreationForm): class Meta: model = CustomUser fields = ('firstname', 'lastname', 'email') class StudentForm(forms.Form): address = forms.CharField(max_length = 30) class Meta: model = Student fields = ['address'] models.py : class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField('email address', unique=True) firstname = models.CharField(max_length = 30, null = True) lastname = models.CharField(max_length = 30, null = True) class Student(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) address = models.CharField(max_length = 60, null = True) register.html : <div> <form method="POST" action="{% url 'register' %}"> {% csrf_token %} {{ form.as_p}} {{student_form.as_p}} <button class="btn btn-secondary"> Je m'inscris </button> </form> </div> -
How to make custom filter based on user
I have an application which is being used globally at my company. It is used to track internal hardware inventory. Each product is associated with a category (for example a product could have a category of 'cable', or 'development kit', or 'PC peripheral'). Now, each category is associated with a location (for example 'Boston', 'Budapest', and so forth). I have extended the user model in django to allow for a location to be associated with each admin user. I want to create a dropdown list filter in the admin space for each user. The user should be able to filter by product categories, but only the categories with the same location as the user. models.py ##product model class dboinv_product(models.Model): pk_product_id = models.UUIDField( default = uuid.uuid4, primary_key=True, null=False ) product_creation_time = models.DateTimeField( auto_now_add=True, null=True ) product_name = models.CharField( max_length=50, null=False ) product_description = models.CharField( max_length=500, null=True ) current_qty = models.IntegerField( null=False ) fk_location_name = models.ForeignKey( dboinv_location, verbose_name="Location name", default='Boston', on_delete=models.CASCADE, null=True, blank=True ) fk_product_category = models.ForeignKey( dboinv_product_category, verbose_name='Product category', on_delete=models.CASCADE, null=True, blank=True ) def __str__(self): return f"{self.product_name}, {self.fk_location_name}" class Meta: db_table = "dboinv_product" verbose_name = "Product" managed = True ##category model class dboinv_product_category(models.Model): pk_category_id = models.UUIDField( default = uuid.uuid4, primary_key=True, null=False … -
Session variable (Django) in one route exists, and in other is None
Currently I'm working on a project where I'm using React as frontend and Django as backend. In react i created a login page, where I through axios send files to django, and in this route index i sent all the information from the login page, and define a session variable reqeuset.session['id']=150 in it. But when i call reqeust.session['id'] in a diffrent route, it says that it is type None. This is the code: @api_view(['POST']) def index(request): data=request.data.get('data') korisnik = Korisnik.objects.filter(korisnicko_ime=data.get('user'), if korisnik.exists(): korisnik_json=serializers.serialize('json',korisnik) request.session['id']=150 print(request.session['id']) # if not request.session.session_key: # request.session.create() return HttpResponse(korisnik_json) else: return HttpResponse(status=404) @api_view(['GET']) def korisnik(request,id): print(request.session.get('id')) korisnik=Korisnik.objects.filter(pk=id) korisnik_json=serializers.serialize('json',korisnik) return HttpResponse(korisnik_json) This is the output from python console Image Also note, I'm using django restframework. Did anyone, have this problem before, any help is appreciated. -
How to display items in a row of 4 across using django, html, and python
this is my code. I want the items to be displayed horizontally. I've tried changing the col-md-3 and still no luck <title>Document</title> </head> <body> <div class="container"> <div class="row"> {% for product in product_objects %} <div class="col-md-3"> <div class="card"> <img src="{{ product.image }}" class="card-img-top"> <div class="card-body"> <div class="card-title"> {{ product.title }} </div> <div class="card-text"> {{ product.price }} </div> </div> </div> </div> {% endfor %} </div> </div> </body> </html> -
How can i pass a Django form to Html Asynchronously with intial data
I am representing data in a table and taking input for new data using a form on the same webpage. In my table at the end column, there is an update button for each row. When I will click the button, I want the existing form will populate with the data of the row. I want to update the data of a selected row asynchronously. I did it quite well with regular Django. But when I tried to do it with ajax/jquery. I have encountered a problem passing the form with populated data to HTML/script(Django view to frontend). I have added few lines of code below. Here is my Django view, def update_view(request,pk): p = People.objects.get(pk=pk) if request.method == 'POST': form = RecordUpdateForm(request.POST,instance=p) if form.is_valid(): form.save() else: form = RecordUpdateForm(instance=p) return !!! here is the url path, path('<int:pk>/update_view',views.update_view,name="update-view"), -
Cannot Debug Django using pdb
I am trying to add a breakpoint() to a particular line in a Django code which is running on an ec2 instance. I have tried ipdb, pdb tried import pdb;set_trace() it quits giving a BdbQuit error. tried simply adding breakpoint This simply gets ignored None of them stop the code. If I run the code like this python -m pdb manage.py runserver , it immediately drops into pdb and fails after executing 2 lines. How exactly should I use pdb in Django correctly? Old answers don't work. -
Filtering parent/child using NestedTabularInline in Django
Stuck in getting conceptually my head around a Django/ORM problem for a few days. Searching online (stackoverflow) didn’t address my problem. Furthermore I’m quite new to Django and Python and trying to understand the concepts of abstract models, multitable inheritance and proxy models but I don’t think that’s the solution. Outline: I’ve a general description of a activity/method/task model which describes a general assembly instruction. See my Activity/Method/Task/TaskImage model. On a actual product I want to execute a plan, in which I concretize a series of activity steps, hence my PlanActivity and PlanMethod models. Moreover for each actual plan I want to assign a bill of materials to make the product (therefore the TaskBOM). For convenience I’m heavily using NestedTabularInline for both drag/drop and inline properties. My problem is a bit twofold: Any activity step can have only one single method (Q1) and the available method’s need to be filtered (Q2) on it’s parent (activity). The tasks need to be filtered on the same way based on it’s parent (method). I think/hope my model is sane (thus no need for abstract models, multitable inheritance and proxy models) and I believe I need to use get_queryset or formfield_for_foreignkey functions in some … -
How to Remove " Password Condtions text " in django crispy form
I have added Password and using django crispy form. But can anyone help me how to remove the Password conditions text? Is there any easy way to remove """" Your password can’t be too similar to your other personal information. Your password must contain at least 8 characters. Your password can’t be a commonly used password. Your password can’t be entirely numeric. New password confirmation* "" enter image description here this text -
Django Rest Registration (3rd party package) asking for signature to verify registration.. What signature?
I'm using 'django rest registration' and when I create a new user everything works fine. The issue is that the 'verify-registration' endpoint requires a user_id, timestamp and a signature and I have no idea what timestamp and signature I'm supposed to post to the endpoint. The documentation is not really giving me any clues. Can anyone tell me what exact signature this 'verify-registration' endpoint is asking to have posted to it please? Here's the piece from the docs: and then it should perform AJAX request to https://backend-host/api/v1/accounts/verify-registration/ via HTTP POST with following JSON payload: { "user_id": "<user id>", "timestamp": "<timestamp>", "signature": "<signature>" } -
ValueError when i try to visit the dashbord of my app (( Cannot query "adivaumar@domain.com": Must be "FriendList" instance.))
Here is my dashboard view.py the error I think is coming from the user_data instance, I just couldn't think of a way to go about it. I have also search on stack overflow for solutions but they happens to be different issue but the same Value error. what could possibly be the problem with my code? def dashboard(request, session_username): user_videos = VideoPost.objects.filter( user__username=request.user.username).order_by('-id') user_data = User.objects.get_or_create( user=User.objects.get( username=request.user.username))[0] user_video_likes = 0 user_videos_views = 0 for video in user_videos: user_video_likes += video.likes.count() user_videos_views += video.video_views.count() params = {'videos': user_videos, 'user_data': user_data, 'total_likes':user_video_likes, 'total_views': user_videos_views} return render(request, 'dashboard.html', params) -
Django how to show correct pagination object to it's right user?
Right now my paginations is same for all user. Let you explain. Assume I listed 2 items per page if user Jhone have 4 items then he will see total 2 page number. see the picture: But User Mick haven't any items in his account but why he is seeing only page numbers? see the picture here is my code: views.py def ShowAuthorNOtifications(request): user = request.user notifications = filters.NotificationFilter( request.GET, queryset=Notifications.objects.all().order_by('-date') ).qs paginator = Paginator(notifications, 5) page = request.GET.get('page') try: page_obj = paginator.page(page) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) notification_user = Notifications.objects.filter(user=user).count() Notifications.objects.filter(user=user, is_seen=False).update(is_seen=True) template_name ='blog/author_notifications.html' context = { 'notifications': notifications, 'notification_user':notification_user, 'page_obj':page_obj, } print("##############",context) return render(request,template_name,context) #html {% for notification in page_obj.object_list %} {%if user.id == notification.blog.author.id %} #my code {%endif%} {%endfor%} #my pagination code: <!-- Pagination--> <ul class="pagination justify-content-center mb-4"> {% if page_obj.has_previous %} <li class="page-item"><a class="page-link" href="?page=1">First Page</a></li> <li class="page-item"><a class="page-link" href="?page={{ page_obj.previous_page_number }}">← Back</a></li> {% endif %} {% if page_obj.has_next %} <li class="page-item"><a class="page-link" href="?page={{ page_obj.next_page_number }}">Next Page →</a></li> {% endif %} {% for i in page_obj.paginator.page_range %} {% if page_obj.number == i %} <li class="page-item"><a class="page-link" href="#!">{{ i }}</a></li> {% elif i > page_obj.number|add:'-3' and i < page_obj.number|add:'3' %} <li class="page-item"><a … -
fetching data shows as undefined [duplicate]
import React, { Component } from 'react' export default class Main extends Component { constructor(props){ super(props) this.state = { name: 'NA', author: 'NA', } this.getBooks() } getBooks() { fetch('http://127.0.0.1:8000/api/get-books') .then((response) => { return response.json() }) .then((data) => { console.log(data) this.setState({ name: data.name, author: data.author, }) }) } render() { return ( <div> Name: {this.state.name} <br></br> Author: {this.state.author} </div> ) } } When I console.log(data) it logs: Object { id: 1, name: "book1", author: "Author1", passcode: "123" }, Object { id: 2, name: "book2", author: "Author2", passcode: "321" }, but for some reason data.name is undefined... how can i fix this? -
DRF exception 'NotAuthenticated' raising 500 Internal Server Error in place of 401/403
I have a Django middleware where I verify a firebase IDToken. from rest_framework import exceptions def process_request(request): ... try: decoded_token = auth.verify_id_token(id_token) uid = decoded_token['uid'] except: raise exceptions.NotAuthenticated(detail='not authenticated') When the verification fails, auth raises an exception, which is caught by the try except block. But instead of raising 401/403 error, 500 Internal Server Error is raised by NotAuthenticated. Is it because of some working of DRF Exceptions that this is happening ?