Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JS gives me POST 404 (Not Found) when I try to update my models in django with fetch - even though the same code works for other function
I'm working on a small project and I'm trying to use JS fetch to delete an item (called script) from the read later for a specific user (ReadLater is a separate model in Django). Prior to writing this function, I also wrote the same function for adding and deleting notes of users (where Note is also a separate model) and the same code works as it should, but for some reason, when I try to remove from Read Later, in fetch I get Post 400 - not found. I've been busting my head for over an hour now, just looking at the code, but I don't see where I'm mistaken. What am I missing? URLs: urlpatterns = [ ... # API path("add_note/<int:script_id>", views.add_note, name="add_note"), path("delete_note/<int:note_id>", views.delete_note, name="delete_note"), path("read_later/<int:script_id>", views.read_later, name="read_later"), ... ] View: @csrf_exempt @login_required def read_later(request, script_id): """Removing selected script from read_later""" if request.method == "POST": try: script = Script.objects.get(pk=script_id) user = request.user data = json.loads(request.body) # Double-checking if remove is what we want if data.get('action') == 'remove': rl = ReadLater.objects.get(user=user, script=script) rl.delete() return JsonResponse({"message":"Removed from Read Later successfully."}, status=201) except Script.DoesNotExist: return JsonResponse({"error": "Script not found"}, status=404) else: return HttpResponseRedirect(reverse('index')) JS: document.addEventListener('DOMContentLoaded', function() { document.querySelector('#mp_read_later_view').addEventListener('click', function(e) { const … -
Login with custom css with Django
So i have a django web and i want in the login page to custom a background image by static files. I tried to do it but it seems that it doesn't read my static filed. settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static')] TNX! -
How to display data on Piechart from MYSQL database using django?
I am trying to extract data from the database and view the results on a pie chart, the charts should change dynamically when the values in the database change. But I am getting error in my script. Here is my view.py: def pie_chart(request): labels = [] data = [] queryset = Persons.objects.order_by('-id')[:3] for city in queryset: labels.append(city.firstname) data.append(city.salary) return render(request, 'breedingherdsummary.html', { 'labels': labels, 'data': data, }) Model.py: class Persons(models.Model): id = models.IntegerField(primary_key=True) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) address = models.CharField(max_length=100) dob = models.CharField(max_length=100) salary = models.IntegerField doj = models.DateField class Meta: db_table = "test" Here is my script: <script> var config = { type: 'doughnut', data: { datasets: [{ data: {{ data|safe }} , backgroundColor: [ '#FFA07A', '#E9967A', '#FA8072', '#F08080', '#CD5C5C' ], label: 'Salary' }], labels: {{ labels|safe }} }, options: { responsive: true, innerRadius: "40%" } }; window.onload = function() { var ctx = document.getElementById('pie-chart').getContext('2d'); window.myPie = new Chart(ctx, config); }; </script> Any help will be highly appreciated. Thank You! -
Understand `clean()` for customized form-wide data cleaning
In the source code of django/forms/forms.py class BaseForm(RenderableFormMixin): ... def clean(self): """ Hook for doing any extra form-wide cleaning after Field.clean() has been called on every field. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field named '__all__'. """ return self.cleaned_data If We want to perform additional form validation, we normally have below codes: class ContactForm(forms.Form): ... def clean(self): cleaned_data = super(ContactForm, self).clean() name = cleaned_data.get('name') email = cleaned_data.get('email') message = cleaned_data.get('message') if not name and not email and not message: raise forms.ValidationError('You have to write something!') Q: super().clean() does not perform any actual validation except return cleaned_data, how could ContactForm.clean() perform the basic data validation which is supposed to be invoked by super().errors or super().is_valid() or super.full_clean(). -
DjangoAdmin: POST data is empty when saving a model with a filefield
My application has been setup on AWS lambda, together with API gateway, S3, cloudfront, RDS. I'm having some troubles saving my model in DjangoAdmin that makes use of imagefield or filefields. For some reason, when I submit my model, my POST data is empty. This problem only comes forward upon saving a model that has a Filefield or Imagefield and when working online. So on localhost this isn't a problem at all and I can save images to my S3 bucket without a problem. The reason why I found out is because I got a csrftoken is missing error at first. So I made a custom csrf error view and printed out the request.POST data, where my csrfmiddleware token should be in. Any ideas why this only happens when I have a filefield or imagefield in my model? -
AbstractUser object has no attribute 'model'
Below is my model.py class CustomUser(AbstractUser): email = models.EmailField(unique=True, primary_key=True) I override the default user model by providing a value for the AUTH_USER_MODEL setting.py AUTH_USER_MODEL = 'home.CustomUser' But When I run server, I got AttributeError: 'CustomUser' object has no attribute 'model' What's problem in my code?? My django version = 4.0 -
I have a model Job with a manytomany field benefit. How will I make it accept pk value and str value?
How will I make the many-to-many field benefit in the job model which has a field name accept string also? If the new value is given it has to create a new instance also. now I'm getting the error "Incorrect type. Expected pk value, received str." { "benefit": [ 1 ], } what I have to input is { "benefit": [ 1,"new_instance" ], } and create new instance as the name in the benefits model. -
Is it possible to have generic a field in django models?
I am currently trying to work on designing a DB schema for a chat application. And I am having some confusion pertaining to the field type in which I should store the content of each message. Here is the partially completed DB schema of a chat message: ... ... ... # types of chat messages available TEXT = 'text' IMAGE = 'image' ... MESSAGE_TYPE = [ (TEXT, _('Chat message type : Text')), (IMAGE, _('Chat message type : Image')), .... ] # User class represents a user of the application class ChatMessage(models.Model): """ Class for storing chat messages between `Users` """ # type of the message message_type = models.CharField(choices=MESSAGE_TYPE, null=False) # user who created the text message sender = models.ForeignKey(User, on_delete=models.CASCADE, null=False) # user who is supposed to receive the message recipient = models.ForeignKey(User, on_delete=models.CASCADE, null=False) # timestamp at which the message was created created_at = models.DateTimeField(default=timezone.now) # whether the recipient has seen the message seen = models.BooleanField() # content of the chat message content = ..... I am planning to use encoder/decoder utilities to interpret the content for different types of chat messages using the message_type field. But I am having difficulty in specifying the field which is suitable to … -
Pre filled form data using id in Django?
Actually Everything is working fine and Id is also coming in URL but Data is not coming in fields when I click on Update button Here is my Code This is models that I have created #Models.py from django.db import models class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) mobile_number = models.IntegerField() cnic = models.CharField(max_length = 13) blood_group = models.CharField(max_length= 10) last_donation = models.DateTimeField(auto_now_add=True) This is MY views #views.py from django.shortcuts import render,redirect from .models import * from .forms import UserForm from django.urls import reverse def home(request): data = User.objects.all() #This function display All data on homePage context = { 'data': data } return render(request, 'home.html',context) def donor(request): if request.method == "POST": userform = UserForm(request.POST) #This Add New User if userform.is_valid(): userform.save() else: userform = UserForm() return render(request, 'donor.html',{'userform':userform,}) def Update(request,pk): context = {} if request.method == "POST": p_id = User.objects.get(pk = pk) form = UserForm(request.POST or None, instance= p_id) if form.is_valid(): form.save() return redirect(reverse('home')) context['form'] = UserForm() return render(request, 'update.html',context) #urls.py from django.urls import path from blood import views urlpatterns = [ path('',views.home, name='home'), path('donor/', views.donor, name = 'donor'), path('update/<int:pk>', views.Update, name='update'), ] This is Forms that I have created and check validation #forms.py from django.forms import ModelForm from … -
Django ModelField custom attribute
Very simple question: can you make a custom attribute for a Field? I have a Customer model with a bunch of Fields. Charfields, ForeignKeys,IntegerFields, BooleanFields etc. etc. When the form gets submitted for a new customer I want to export the data to an existing excel template, where cell names are B1 and value B2 for instance. So I was thinking to just give every field an 'cell position' attribute so I can just loop through the cells and easily assign each column their value, something like name = models.CharField(verbose_name='Name',max_length=30,'cell position' = 'B2'), Would that be possible? If so or not, how would I go about doing this? -
Unexpected FieldError, "Cannot resolve keyword 'conducted_by' into field. Choices are:..." while getting a queryset in Django
I have this model: class CTScan(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) amount=models.DecimalField(max_digits=10, decimal_places=2, default=0) date=models.DateField(default=datetime.date.today) conducted_by=models.CharField(max_length=4, default=None) remarks=models.TextField(max_length=500, blank=True, default=None) ctscan_date=models.DateTimeField(auto_now_add=True) And I have turned the conducted_by field into a radioselect field in forms.py: class CTScanForm(ModelForm): PARTY_SELECT = ( ('k', 'KCC'), ('o', 'OOPL'), ) conducted_by=forms.CharField(widget=forms.RadioSelect(choices=PARTY_SELECT, attrs={'class': 'form-check-inline'})) class Meta: model=CTScan fields='__all__' labels={ 'conducted_by':'Conducted By', } widgets={ 'date': DateInput(attrs={'type': 'date'}), } When I make a query in views.py like: ct_kcc=IpdReport.objects.filter(ctscan__date__range=(prev1, prev2), conducted_by='k') It throws a FieldError: Cannot resolve keyword 'conducted_by' into field. Choices are: approvedpackage, approvedpackage_id, claimedpendingcases, ctscan, ctscan_id, discharge, discharge_id, id, lockdata, lockdata_id, ongoingreport, package, package_id, patient, patient_id, radiations, radiations_id, realization, realization_id, reclaimedrepudiation, repudiatedclaims, unclaimedpendingcases What is wrong with my code? -
Typerror: object is not subscriptable Django test
I have some problems with my tests in Django. The ide is that I create questions for my learning platform, and I want to verify that the questions are actually created. The problem is that (from what I understand) I try to put a list, objects that in a list cannot fit. Do you have any ideas how I can correct this? Thank you very much! Error: response.context['latest_question_list'], TypeError: 'NoneType' object is not subscriptable The test: def test_two_types_questions(self): """ The questions index page may display multiple questions. """ lab1 = Lab.objects.create(lab_name="test lab past question", pub_date=datetime.now(), lab_theory="test lab past question") question1 = QuestionMultipleChoice.objects.create(lab=lab1, question='This is a test question', option1='1', option2='2', option3='3', option4='4', answer='1') question2 = QuestionFillText(lab=lab1, text1='1', text2='2', answer='1') response = self.client.get(reverse('labs:index')) print(response) self.assertQuerysetEqual( response.context['latest_question_list'], [question1, question2], ) -
Understand `_html_output()` from Django Forms Source Code
Below source code is from django/forms/forms.py class BaseForm(RenderableFormMixin): def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row): "Output HTML. Used by as_table(), as_ul(), as_p()." How is this private method _html_output() used / invoked by as_table(), as_ul(), as_p() please ? I did not find out from the source code. -
MultiValueDictKeyError while trying to add image to my blog post
I am trying to add image to my blog post but when i added this to my code image = request.Post['image'] And i keep getting errors. -
Django: Unable to save the model instance
I have models defined like the below: class Device(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) owner = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) def __str__(self): return self.name class DeviceReadings(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE) reading = models.FloatField() timestamp = models.DateTimeField() And I am trying to save models like below: device = Device.objects.get(pk=device_id) r = DeviceReadings(device_id=device, reading=reading, timestamp=timestamp) r.save() It gives an error that Invalid UUID format. It works if I set device.pk. I am not so well-versed in Django, unable to understand why the instance is not being saved. -
How can I make a model method editable through a dependent field in django admin list display
The scenario: I have a model like this from django.db import models from django.contrib import admin class Appointment(models.Model): time = models.DateTimeField(blank=True, null=True) topic = models.CharField( max_length=255, null=True, help_text="Topic to be discussed at the meeting" ) medium = models.URLField(blank=True, null=True, help_text="Meet link") def __str__(self): return f"{self.date_and_time}" @property @admin.display( ordering="time", description="Date and time of the appointment", ) def date_and_time(self): return self.time.strftime("%b %d, %I:%M %p") With an admin model from django.contrib import admin from .models import Appointment @admin.register(Appointment) class AppointmentAdmin(admin.ModelAdmin): date_hierachy = "time" list_display = ( "date_and_time", "medium", ) list_editable = ( "date_and_time", "medium", ) As shown in the code, I want to use a derived model method (date_and_time) in the Django list display, while making it editable through its dependent field "time". Of course, as expected, the above code throws an error because I included "date_and_time", which is the derived model method and not a field, in the list_editable tuple, I cannot add "time" as it doesn't exist in the list_display at all, instead it is represented as the date_and_time method which only formats the time field btw. My question: Is there a way to have the formatted DateTime (which is what the date_and_time does) displayed in the list table, allowing editing … -
Django OAuth2 Toolkit
I am using django oauth2 toolkit. Can anyone please help me in understanding? I am able to Signup the user based on the extended AbstractUser model. Based on Signup details, I'm able to authenticate the user by entering username, password, client_id, client_secret & grant_type. After entering login credentials, id & secret in these (127.0.0.1:8000/o/token/), I'm able to get the access & refresh token When getting the access_token, How can I pass the user details along with access_token. Can anyone please help me in sorting out these. I'm using Postman. Serializers.py from rest_framework import serializers from django.contrib.auth import authenticate from rest_framework.response import Response from django.contrib.auth import get_user_model User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name','last_name','username','password','email','date_of_birth', 'profile_image','bio','role','gender') extra_kwargs = {'is_staff': {'write_only':True}, 'is_active':{'write_only':True}, 'password':{'write_only':True}} def create(self, validated_data): return User.objects.create_user(**validated_data) Views.py from django.shortcuts import render from rest_framework import generics, permissions, serializers, viewsets from rest_framework.response import Response from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope from users.serializers import UserSerializer from users.models import User # Create your views here. class UserAPI(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() Urls.py from django.urls import path, include from rest_framework import routers from rest_framework.routers import DefaultRouter from users.views import UserAPI from users import views router = DefaultRouter() router.register('users', views.UserAPI, … -
"unique = True" - Django models - Unique for each user not unique for all data submitted by everyone
I have a models in Django currently and I have made a field "unique=True" so that no duplicates are submitted to the database. My problem is that it extends to all users. By this I mean that User 1 should be able to submit "Example1" and "Example2" and should never be able to submit "Example1" or "Example2" again and then User2 should come along and also be able to submit "Example1" and "Example2" but they cant because User 1 already submitted it. It there a way where I can get somewhat of a "unique=True" but separately for each user and not just conjoined like it is now. Thanks in advance. Code Below. The problem resides in "type = " and my users are being defined by ForeignKey also. class Field_Repo1(models.Model): user = models.ForeignKey(User, default=True, related_name="Field_Repo1", on_delete=models.PROTECT) title = models.CharField(max_length=20, verbose_name='Title of Field') type = models.CharField(max_length=200, blank=True, unique=True, null=True, verbose_name='Field') class Meta: ordering = ['-type'] def __str__(self): return str(self.user) or 'NONE' def get_absolute_url(self): return reverse('repo1') -
Useful design patterns for creating a neat Python Web App
We decided to refactor our code as almost every new feature was implemented as a form of a hack. Would to get some tips on what design patterns would be useful to have in a web app. Things like Factory or Facade don't suit, I feel those are more suited for libraries and not a web app. The gist of the web app is that it is a sort of translator that understands a user's queries and creates large queries to our DBs. It's a sort of search service. We have a ton of features and configuration that keep stepping on each other's functionalities and we have to add ugly hacks to overcome them. Hoping to have a good base that lets creating long complex chain of rules easier to modify. -
DJANGO how to REMOVE url parameters?
What would be the best way to remove parameters from url in django? For instance when facebook adds fbclid? I am trying to do a redirect directly in urlpatterns but the parameters keep getting passed through. For some reason I assumed this would be some simple command like 'allow_parameters=False' or something. -
how i solve django 3.x admin autocomplete error
I have tried python manage.py collectstatic but no effect.It seems to be the problem about app_label from error message. this is the Traceback: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/utils/datastructures.py", line 76, in getitem list_ = super().getitem(key) KeyError: 'app_label' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/views/autocomplete.py", line 61, in process_request app_label = request.GET['app_label'] File "/usr/local/lib/python3.7/site-packages/django/utils/datastructures.py", line 78, in getitem raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'app_label' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 250, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 232, in inner return view(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 417, in autocomplete_view return AutocompleteJsonView.as_view(admin_site=self)(request) File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/views/autocomplete.py", line 20, in get self.term, self.model_admin, self.source_field, to_field_name = self.process_request(request) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/views/autocomplete.py", line 65, in process_request raise PermissionDenied from e … -
Free way to send SMS using Django
hope you are doing well. I need help im Django. I need to send messages for free without using an API or email server. What I had tried: I use multiple API such as Twillio etc. But it is quite an expensive solution. I use an SMTP server to send messages Via Email. But in our area no SMS service provider is available. If you have any free or cheap solution to the above problem, so please state it there while mentioning me. I will do consider it. Thanks -
access to pk in a template form
I want to display all elements of a form including the pk and I have not found a satisfying method to do so: class SomeForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["number"] = forms.IntegerField(required = True) self.fields["id"] = forms.IntegerField(disabled = True) self.fields["data"] = forms.CharField(required = False) class Meta: model = SomeModel fields = ["id", "number", "data"] So now I just call the form in the view with: class SomeView(TemplateView): template_name = "app/sometemplate.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) obj = MODEL.objects.get(pk = context["pk"]) MODEL_data = {} MODEL_data["number"] = obj.number MODEL_data["id"] = obj.pk MODEL_data["data"] = obj.data context["form"] = SomeForm(initial = MODEL_data) return context and now in the templatetags I have a filter get_pk: @register.filter(name='get_pk') def get_pk(obj): return obj.initial["id"] and I get the pk in the template with {{ form|get_pk }} and I feel like this is not smart. I tried stuff like {{ form.instance.id }} like suggested here. I still feel there must be an easy way to achieve this? -
Django REST API doesn't output JSON but <Response status_code=200, "text/html; charset=utf-8">
I am using Django REST framework for a ML model and I input JSON data and I want to get output JSON results as response_dict. But when I print(Response(response_dict, status=200)), it prints <Response status_code=200, "text/html; charset=utf-8"> instead of whatever JSON results that my model predicts. BUT on the local Django server page, I can see my JSON output. How can I can output response_dict instead of this text/html? views.py class FraudDetection(APIView): def post(self, request): data = request.data df = pd.json_normalize(data) # some preprocessing fds_model = ApiConfig.model ypred = fds_model.predict_proba(df) response_dict = {"Fraud score: {:.3f}, Normal Transaction, Processing request".format(ypred[i][1]*100)} print(Response(response_dict, status=200)) return Response(response_dict, status=200) -
Django Rest Framework is throwing 400 before I can handle exception for ModelViewSet
I have a user model in my app with a unique field on email. However, I need to catch when a user is trying to do a duplicate request so I can do some processing in a different way. I am making a POST call to create this user. DRF of course throws a 400 with an existing email message. But even when I create a validate_email method in my model or try to catch it with a custom exception it doesn't catch. I created a custom ValidationError cause the general ValidationError didn't seem to have a way to filter it out specifically besides a generic code, unique, or matching the message string. How can I catch this specific validation in Django Rest Framework? Error Message: { "email": [ "user with this email address already exists." ], "status_code": 400 } User model: class User(AbstractBaseUser, PermissionsMixin): """ User Model """ USERNAME_FIELD = "email" REQUIRED_FIELDS = [] email = models.EmailField(_("email address"), unique=True) name = models.CharField(_("name"), max_length=30, blank=True) def validate_email(self): email = self.email valid_email = email is not None and email.endswith(self.email_domain) if not valid_email: raise ValidationError( _("Email is not valid"), code="invalid.email", ) if Users.objects.filter(email=email).exists(): import ipdb; ipdb.sset_trace() #does not get called raise EmailExists() …