Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display multiple forms on one page with colliding field names
I need to have 2 forms on the same page that both have the field email and are both submitted at the same time: Person form that has the email field: class PersonForm(forms.ModelForm): class Meta: model = Person fields = [ 'first_name', 'last_name', 'email' ] And an organization form, which also has the email field: class OrganisationForm(forms.ModelForm): class Meta: model = Organisation fields = [ 'name', 'url', 'email', ] However, the request.POST.email will obviously always have the last displayed form's value, overwriting the first value. Is there a way to deal with this, like if we renamed the organisation's email as organisation_email? fields = [ 'name', 'url', 'email AS organisation_email', ] without having to define in OrganisationForm a custom field: org_email = models.EmailField(max_length=4096, blank=True, db_index=True) and have to overwrite the save() method? Plus, I don't like having to redefine the max_length and blank properties in case they change in the original Model. -
Change the default message in django-admin when deleting
I have a model where a user can add some data and assign this data to a specific month. But if that user had already added some items and try to delete a specific data who is assigned to a previous month it should be locked. I had success with this, but my problem now is with the message for the user. I would like to remove the default message of the delete button on admin but until now without success. Here is the image of the problem: MessageImage admin.py class MontlyReleaseAdmin(admin.ModelAdmin): form = MontlyReleaseForm def get_actions(self, request): actions = super().get_actions(request) if 'delete_selected' in actions: del actions['delete_selected'] return actions def delete_model(self, request, obj): if not is_valid_date(obj): messages.add_message(request, messages.ERROR, 'Not Deleted') else: super().delete_model(request, obj) admin.site.register(MontlyRelease, MontlyReleaseAdmin) -
How should I go about integrating wagtail-lazyimages with Wagtail's RichTextField?
I'm trying to implement lazy loading for my blog post images, but I'm utilizing RichTextField for my blog posts, so I'm unable to specify each image tag like the Wagtail-LazyImages documentation suggets I should. According to the Wagtail Docs on RichTextField internals, an image may be stored as <embed embedtype="image" id="10" alt="A pied wagtail" format="left" /> but upon rendering is translated to <img alt="A pied wagtail" class="richtext-image left" height="294" src="/media/images/pied-wagtail.width-500_ENyKffb.jpg" width="500"> meaning there's not every any explicit tag usage like LazyImages is looking for. This is more of a conceptual question, as I'm just not sure where in the process to hook into Wagtail's RTF processing. Could I utilize the register_rich_text_features hook to make a new "feature" for lazy images that will then use the lazyimages class? -
Django Connect To MySql DB Table
I'm trying to Make an auth system without using the Django user.authenticate system because I want to make 2 seperate Login Systems. 1 For the IT & Web Development Dept. and another 1 for the general users. So I'm using the same MySql Database and the Auth_user for my IT dept. and I created a accounts app which I want to use the accounts_benutzer (users in german) table. I can add thanks to the app system users etc. over the Admin Panel but I want that the users which are registered by an IT Dept User log in on the Main Page with the given username and password My views/models/template is like: accounts/models.py: class Benutzer(models.Model): regex = RegexValidator(regex=r'^\+?1?\d{7,15}$') name = models.CharField(max_length=100) passwort = models.CharField(max_length=32) email = models.EmailField(max_length=254) .... accounts/views.py : from django.shortcuts import redirect, render from django.contrib import messages from django.contrib.auth.models import User, auth from .models import Benutzer def login(request): if request.method == 'POST': username = request.POST['name'] passwort = request.POST['passwort'] if (username == Benutzer.name) and (passwort == Benutzer.passwort): return redirect('/') else: messages.info(request,'Falsche Zugangs Daten!') return redirect('/accounts/login') else: return render(request, 'login.html') login.html: {% load static %} <form action="login" method="post"> {% csrf_token %} <p>Benutzername: <input type="text" name="name" placeholder="Benutzer Name"></p> <p>Passwort: <input type="password" … -
Django + Angular authentication fails when Django hosts page. Works on separate servers
I have a web application using Django as the backend and Angular for the frontend. I have implemented TokenAuthentification which works fine when I am using ng serve --poll 2000 and python manage.py runserver but when I use Apache2 + wsgi_mod to run the Django project with Angular built with node --max_old_space_size=5048 ./node_modules/@angular/cli/bin/ng build --prod --aot --output-path ../backend/static/ang --output-hashing none and loaded in the index.html. The page renders fine, and collects data from the DB (provided no auth is required for that page) but when I'm looking for user specific data and use request.user its not available. Looking at the headers the Authorization header is still being sent but in my Django code the user is unauthenticated. I have spent ages on this and can't figure out why the request is being treated differently. Any advice? -
Django server reporting "Forbidden (CSRF token missing or incorrect.)" despite sending token correctly?
I am trying to send a JSON POST request to my Django server. It reports this error: Forbidden (CSRF token missing or incorrect.): In my Django template, options.html, I say this: <script>const incomingToken = "{{ csrf_token }}";</script> And this: <input type="hidden" name="csrf-token" id="csrf-token" value="{{ csrf_token }}" /> Then in my JavaScript file that runs in the client I say: const serverUrl = "http://127.0.0.1:8000/" const headers = new Headers({ 'Accept': 'application/json', // 'X-CSRFToken': getCookie("CSRF-TOKEN") "X-CSRFToken": document.getElementById("csrf-token").value }) fetch(serverUrl, { method: "POST", headers: { headers }, mode: "same-origin", body: JSON.stringify(editorState.expirationDate, editorState.contracts, editorState.theta) // FIXME: server goes "Forbidden (CSRF token missing or incorrect.)" and 403's }).then(response => { console.log(incomingToken) console.log(document.getElementById("csrf-token").value) console.log(response) }).catch(err => { console.log(err) }); Both incomingToken and document.getElementById("csrf-token").value report the same value. So I know I'm getting the correct string for the CSRF token. How can this be? What am I doing wrong? For reference, here is what I see in another thread on the subject: const csrfToken = getCookie('CSRF-TOKEN'); const headers = new Headers({ 'Content-Type': 'x-www-form-urlencoded', 'X-CSRF-TOKEN': csrfToken }); return this.fetcher(url, { method: 'POST', headers, credentials: 'include', body: JSON.stringify({ email: 'test@example.com', password: 'password' }) }); Instead of running a function to retrieve the value from a cookie, I simply insert … -
How to show fields of a model in django?
Suppose I have a situation where I input a field from user and depending upon the field I have to query the corresponding model. Say if the user enters rice then I have to query on rice model. Also there are many models where each models have different number of fields.. What I want is to return a list containing n number of dictionary where n is the number of fields in that model. Say if I have username and age fields in student model then I want to return [{"username":"Sagar"},{"age":21}]. Any suggestion on how to achieve this. -
How to properly add multi choice field to existing form in Django?
Just like in title. This is what I currently have. I've tried django-multiselectfield but I had many issues with my foreignkey and ManyToMany usage in models. Maybe I should just use a JavaScript or something? I'm a newbie to Django and I really don't know which way to take. MODELS class Category(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return f'{self.name}' class Expense(models.Model): class Meta: ordering = ('date', '-pk') category = models.ForeignKey(Category, null=True,blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8,decimal_places=2) date = models.DateField(default=datetime.date.today,db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' FORMS class ExpenseSearchForm(forms.ModelForm): GROUPING_CHOICES = ('date', 'category asc', 'category desc') grouping = forms.ChoiceField(choices=[('', '')] + list(zip(GROUPING_CHOICES, GROUPING_CHOICES))) SORTING_CHOICES = ('date asc', 'date desc' ) sorting = forms.ChoiceField(choices=[('', '')] + list(zip(SORTING_CHOICES, SORTING_CHOICES))) class Meta: model = Expense fields = ('name','category') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for i in self.fields: self.fields[i].required = False -
Is there a way in Django to filter through choices?
There's a field in Django called choices, where you can fill out 'choices'. ''' connector = models.CharField( max_length=255, null=True, blank=True, choices = Food, verbose_name="food", Food = [ ('chicken', 'Chicken'), ('queso', 'Queso'), ('carne', 'Carne') ] ''' Like that for example. But what if the list of choices is much, much larger than just 3? Is there a way to add a searching functionality so that it can narrow it down? Like an autocomplete? I have a list of over 300 items that I want as choices, but I only want them to show when I type the relevant letters - i.e. I type "A" I'd like a dropdown list of the choices that start with A. Is there a way to do this easily within Django? -
ValueError: too many values to unpack (expected 2) returning from function
I am returning two values from a function, however, I am unable to unpack them. My first function returns: return ("Fail", image_url) When I try to retrieve the values via; result, screen_url = test.test_signin(email, password, exp) I am getting a "too many values to unpack error". I have tried running the code without the () in the return statement. I get the same error. -
Django form POST resulting in 404
I am attempting to take in a form for update or delete, run the process and either return the updated url, or the updated list of objects. I've got the dynamic url building working, but when I hit submit I get a 404. I am struggling with the how to process the POST, as it doesn't even seem to be hitting that far in the code. Code below: urls.py path("customers/", views.customers, name="customers"), path("customers/customer/<int:id>/", views.customer), forms.py class CustomerMaintForm(ModelForm): class Meta: model = AppCustomerCst fields = ('id_cst', 'is_active_cst', 'name_cst', 'address_1_cst', 'address_2_cst', 'address_3_cst', 'city_cst', 'state_cst', 'zip_cst', 'country_cst', 'salesrep_cst', 'type_cst', 'is_allowed_flat_cst', 'iddef_cst', 'date_created_cst', 'date_suspended_cst', 'date_first_tran_cst', 'date_last_tran_cst', 'is_credit_hold_cst', 'old_balance_cst', 'balance_notify_cst', 'balance_statement_cst', 'balance_conversion_cst', 'balance_cst', 'receive_emails_cst', 'contact_domain_cst' ) labels = {'id_cst': 'Customer ID', 'is_active_cst': 'Active?', 'name_cst': mark_safe('<p>Name'), 'address_1_cst': 'Address 1', 'address_2_cst': 'Address 2', 'address_3_cst': 'Address 3', 'city_cst': 'City', 'state_cst': 'State', 'zip_cst': 'Zip', 'country_cst': 'Country', 'salesrep_cst': 'Sales Rep', 'type_cst': 'Type', 'is_allowed_flat_cst': 'Allowed Flat?', 'iddef_cst': mark_safe('<p>Id'), 'date_created_cst': 'Created Date', 'date_suspended_cst': 'Suspended Date', 'date_first_tran_cst': 'First Tran Date', 'date_last_tran_cst': 'Last Tran Date', 'is_credit_hold_cst': 'Credit Hold?', 'old_balance_cst': 'Old Balance', 'balance_notify_cst': 'Balance Notify', 'balance_statement_cst': 'Balance Statement', 'balance_conversion_cst': 'Balance Conversion', 'balance_cst': 'Current Balance', 'receive_emails_cst': 'Receive Emails?', 'contact_domain_cst': mark_safe('<p>Contact Domain')} views.py def customer(request, id): if request.method == "GET": obj = AppCustomerCst.objects.get(id_cst=id) instance = get_object_or_404(AppCustomerCst, id_cst=id) … -
Django does not create object in the database during pytest run
I am having weird issue with objects not being saved into database during test run. Code sample: @pytest.mark.django_db class TestCosts(TestCase): def setUp(self): self.account = mixer.blend(Account) acc_settings = Settings.objects.create( account=self.account ) print(acc_settings.id) all_settings = Settings.objects.all() print(len(all_settings)) Weird thing is that running this test suite standalone works correctly, but when running all tests this always failed(Printed length is always zero even though printed id is correct). Unfortunately I am not able to build minimal reproducible example. Is there any known reason this could happen? How can I debug this issue? This started to happen after I have migrated Django from 2.2 to 3.1 and pytest from 2.7 to 4.0 -
How to add a progress bar which keeps track of student completion of courses in a Django LMS
I'm new to Django and have a running e-learning(Learning Management System) website in Django where students can view contents uploaded by Instructors but i would like to add a progress bar which keeps track of the modules completed by students in the form of checkboxes and automatic checking of boxes if the student spends more than a minimum number of minutes (if possible). Models.py file with course and modules model Views.py file from the students app Student Course Detail Template -
Save two model (One contains foreign key) data from a single template
I'm pretty new to django and working on a blog based project where user can add ratings to specific type of review post.For example giving stars are enabled for restaurant but not for tech stores. I have created two different form for "review" and "star" model. I want to rate the restaurant using the model named "star" and do it in same template.But I'm having difficulties to do that. my review model kinda looks like this (Removed other attributes which aren't related to this problem): class Review(models.Model): review_title = models.CharField(verbose_name='Title', max_length=100) review_body = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) restaurant_or_techstore = models.CharField(verbose_name='Foods or Travel',max_length=20) slug = models.SlugField(null=False,unique=True,max_length = 300) My rating model looks like this: class Star(models.Model): post_id = models.ForeignKey(Review, on_delete = models.CASCADE ) food = models.FloatField(verbose_name='Food',null=False) service = models.FloatField(verbose_name='Food',null=False) cleanliness = models.FloatField(verbose_name='Food',null=False) and my view : def CreateReview(request): ImageFormSet = modelformset_factory(Image,form=ImageForm,extra=5) if request.method == 'POST': reviewForm = ReviewForm(request.POST) formset = ImageFormSet(request.POST,request.FILES,queryset=Image.objects.none()) starsForm = StarsrForm(request.POST) if reviewForm.is_valid() and formset.is_valid() and starsForm.is_valid(): review_form = reviewForm.save(commit=False) review_form.author = request.user review_form.post_or_discussion = 1 review_form.food_or_travel = 'Foods' review_form.save() reviewForm.save_m2m() starsForm.save() for form in formset.cleaned_data: if form: image = form['image'] photo = Image(review=review_form,image=image) photo.save() messages.success(request,'Image Uploaded Successfully') return HttpResponseRedirect("/") else: print(reviewForm.errors, formset.errors) else: reviewForm = ReviewForm() formset … -
Where the Http404 and PermissionDenied are handled exactly in django?
Where and how do the Http404 or PermissionDenied are handled exactly in django? I could not find functions or methods to catch these exceptions. -
ImportError: cannot import name 'ORDER_PATTERN' from 'django.db.models.sql.constants'
I want to add SearchFilter to the filte_backends but every time I imported rest_framework.filters I get this error -
Compare list with string in Python and highligth matches
I'm trying to compare a python list with a string and highlight matches with mark inside a new string. But it won't work. Following example: string = 'This is my string where i would find matches of my List' list = ['This is', 'would find', 'bla', 'of my List'] result_that_i_need = '<mark>This is</mark> my string where i <mark>would find</mark> matches <mark>of my List</mark>' Has anybody any idea how to solve this? Can somebody help me please? -
Django 2.2 -> 3.1 Upgrade: TypeError: the JSON object must be str, bytes or bytearray, not dict
After upgrading from Django 2.2 to 3.1 I'm getting this on every one of my views with no clear traceback: TypeError: the JSON object must be str, bytes or bytearray, not dict Has anyone else run into this? I am using the older, now deprecated django.contrib.postgres.fields.JSONField in a few models, and planned to do this until it's removal in 4.0 (since it said it wasn't being removed). Do I actually have to migrate all of my django.contrib.postgres.fields.JSONFields to a django.db.models.JSONField? Or is not the cause? It doesn't mention in the documentation that these fields don't work anymore. I don't have any other relevant code to share– it's happening on all views that load this model, and there isn't any clear traceback. Anyone else run into this? -
Django - MAX ... GROUP BY on ForeignKey to itself
I have a model similar to this: class Tree(models.Model): description = models.CharField(max_length = 255, null = False, blank = False) parent = models.ForeignKey("Tree", null = True, blank = True, on_delete = models.CASCADE) I need to find the latest record for each parent. I tried with this: latests = Tree.objects.values("parent").annotate(Max("pk")) The result is not correct because the SQL query is: select parent_id, max(id) from tree group by id The ORM translates the foreign key to the source and does not use the value inside the field. Is there a way not to "follow" the foreign key and to use instead the value of the field? -
Change value of a model based on value of other model Django
I have a models Wallet and StudentPayment. Every time I add or update StudentPayment, the Wallet balance should change based on the added or updated StudentPayment. class Wallet(models.Model): ... balance = models.DecimalField(decimal_places=2, max_digits=100, default=0.00) ... class StudentPayment(models.Model): ... wallet = models.ForeignKey( Wallet, on_delete=models.SET_NULL, null=True, related_name='students_payment') amount = models.DecimalField(decimal_places=2, max_digits=100) ... For Example: if I add payment with 1000 amount, the wallet balance should change to 1000 too, I know how to do this, but don't know how to deal with the update, ex: if I change the payment amount to 900, the wallet balance should also change. Appreciate any help) I tried to implement with overriding save() method, but nothing works -
How to use same field in again and again in forms Django Framework
I want to add a subject and mark multiple in the same form. Now as I am only filling one time only. But unable to find how to use the field again and again in the form. I want to add the option add another inform when the user clicks on add another the user will get two extra fields of subject and marks again and again. I tried a lot and search a lot, but unable to find how to do this. Anybody will please help me. )------- Thanks models.py class Courses(models.Model): name = models.CharField(max_length=254) price = models.IntegerField(default=False) def __str__(self): return self.name class CourseSubject(models.Model): course = models.ForeignKey('Courses', on_delete=models.CASCADE) name = models.CharField(max_length=254) def __str__(self): return self.name class Exam_result(models.Model): student = models.ForeignKey('student.Student',on_delete=models.CASCADE, default=False) course = models.ForeignKey('student.Courses', on_delete=models.CASCADE, default=False) subject = models.ForeignKey('student.Subject', on_delete=models.CASCADE, default=False) marks = models.IntegerField() def __str__(self): return str(self.student) forms.py class ExamResult(forms.ModelForm): class Meta: model = Exam_result fields = "__all__" widgets = { 'student' : forms.Select(attrs={'class': 'form-control'}), 'course' : forms.Select(attrs={'class': 'form-control'}), 'subject' : forms.Select(attrs={'class': 'form-control'}), 'marks' : forms.TextInput(attrs={'class': 'form-control', 'placeholder': ' Enter Student marks'}) } views.py def exam_result(request): forms = ExamResult() if request.method == 'POST': forms = ExamResult(data=request.POST.getlist) if forms.is_valid(): forms.save() return redirect('/panel/exam/result/list/') return render(request, 'exam/exam_result.html', {'forms' :forms}) -
TypeError at /accounts/register/
Error Page's Picture enter image description here If doesn't work https://hizliresim.com/AaNt5f -
My Django Python code is not changing the database record
I'm creating an auction site and I want to be able to change the data in a table to change the price to the new bid. I'm kind of new to Django and Python so I must be missing something. Right now I'm not getting any errors - it's just not changing the data in the DB. Does anyone see the issue? Here is my HTML and Python code (the relevant parts): views.py: def bid(request, username): price = request.POST.get("price") itemID = request.POST.get("itemID") newBid = request.POST.get("newBid") title = request.POST.get("title") query = Bid.objects.filter(itemID = itemID).first() print(query) if(newBid > price and username != query.highestBidder): query2 = NewPost.objects.filter(title = title).first().update(price = newBid) new = Bid.objects.create(itemID = itemID, newBid = newBid, highestBidder = username) new.save() return render(request, "auctions/post.html") models.py: class Bid(models.Model): itemID = models.CharField(max_length=64) newBid = models.IntegerField() highestBidder = models.CharField(max_length=64) post.html: {% extends "auctions/layout.html" %} {% block body %} <h2>{{ p.title }} - Category: {{ p.category }}</h2> <p>Price = ${{ p.price }}</p> <div> {% if user.is_authenticated %} <form name="bid" action="/post/{{p.title}}{{p.price}}" method="post" > {% csrf_token %} <input autofocus class="form-control" type="text" name="newBid" placeholder="Enter New Bid"> <input autofocus class="form-control" type="hidden" name="itemID" value={{p.title}}{{p.price}}> <input autofocus class="form-control" type="hidden" name="price" value={{p.price}}> <input autofocus class="form-control" type="hidden" name="title" value={{p.title}}> <input class="btn btn-primary" type="submit" … -
Problems with Django Rest Framework-filters
I'm new in django rest and i'm trying build filters for my apps. Looking at the documentation https://github.com/philipn/django-rest-framework-filters I followed all the implementation steps, but when I try to filter my search by username, nothing works settings.py INSTALLED_APPS = [ 'general', 'suprimentos', 'corsheaders', 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django.contrib.contenttypes', 'simple_history', 'django_filters', 'rest_framework_filters', 'django_dbconn_retry', 'rest_framework' ] REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ( 'rest_framework_filters.backends.RestFrameworkFilterBackend', ) } views.py import django_filters.rest_framework from rest_framework import viewsets from rest_framework import filters import rest_framework_filters as filters from rest_framework_filters import backends class UsernameFilter(filters.FilterSet): username = filters.AllLookupsFilter(name='username') class TrackUserView(viewsets.ModelViewSet): model = TrackUser queryset = TrackUser.objects.all() serializer_class = TrackUserSerializer filter_backends = [backends.RestFrameworkFilterBackend] filter_class = UsernameFilter def get(self, request): track = UserLoginActivity.objects.all() serializer = UserLoginActivitySerializer(track, many=True) data = serializer.data return Response({'result':data}) def post(self, request): url = request.data['page'] ip_client = request.META.get('HTTP_IP_CLIENT') if ip_client: ip = ip_client.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') username = request.user.username user_agent_info = request.META.get('HTTP_USER_AGENT', '<unknown>')[:255] hour = datetime.datetime.now() model = TrackUser.objects.create(url=url, ip=ip, username=username, user_agent_info=user_agent_info, datetime=hour) return Response(status=status.HTTP_200_OK) urls.py path('trackuser/',TrackPagesView.as_view({'get':'get','post':'post'}), name='trackuser') I don't know if something is missing or I put something wrong in somewhere, but I can't find the error or syntax problem that's causing it. -
How to keep a form from submitting when creating a Django model object with many-to-many field selection that is doesn't exist in the related model?
I'm using Django to create a web app. I have multiple Django models with relationships between each other. One of my models is called "Type" and another is called "TestEquipment". The Type model has a many-to-many relationship with TestEquipment. To allow the user to create a new Type, I have an html form and to select which TestEquipment will be associated with that Type I have am using searchable dropdown with "chips" (javascript) which loads all TestEquipment and allows you to search and select multiple objects to add. When the user submits the form, the selected TestEquipment is added. Everything works great other than when the user enters text and presses enter, instead of selecting from the dropdown, a chip is added with that text. When the form submits it tries to add a TestEquipment that doesn't exists. I would like to find a way to either not allow adding an objects that doesn't exist or throw an alert "must select from existing test equipment"; somehow I have to ensure that the form does not submit to my constructor and create the new Type if text is added to the field. I've tried to find an answer to this and …