Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
friends help me my login system doesnt function doesnt redirect to dashboards and there is no detected errors, below are codes
please help login system doesnt function i cant login in my django system class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) username = models.CharField(max_length=150, unique=True, null=True, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) -
django messages wont show up in template
Okey this has been asked aloooot but no answer has helped, tried tutorials and asked my student collegues for help but no one can answer why. They have looked and says it looks fine, that it could be something wrong with my django itself. I'm trying to just show a successful logged in message on my django app. I can't make it work. Please bare with me, my first django project and im a student that suffers real bad from imposter syndrome, play nice :) My folder setup home <--app projectfolder media static with images and css folder users <-- app So to start off i use djangos built in auth system. Works great on the site. Using djangos own form for login and logout. Whats really weird is that the div dosent even show up when i render the page and check inspect, nothing in console either. views.py in users from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect def login_user(request): """ Login form and messages """ if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request, "You have been … -
Django socket communication
I have a Django server with a list of devices and their corresponding MAC addresses. I have also created firmware for these devices, and I want to license them using my Django webserver in order to prevent the firmware from being copied onto other chips. The problem I'm facing is that the data will be sent to my web backend every 10 minutes (which could be reduced to 1 minute in the future). Additionally, I want the communication between the devices and the web server to be two-way, so that I can disable the devices at any time by sending a message. I'm unsure of how to handle this situation. Would Django channels be a useful solution in this case, and if so, how can I implement them? The firmware is written in C++. -
How can I edit the contents of a datalist element based on a selection made in another dropdown
I'm writing a section of a Django template file for inputting multiple fields using dropdown menus. Two of the sections are 'State' and 'County'; currently the county dropdown list is just a datalist of all the counties in the entire country, but I would like to use some Javascript to rewrite the datalist whenever a selection is made in the State dropdown option to show only the counties in that particular state. Any suggestions are appreciated! -
Overidding dj-rest-auth Registration Serializer
I am trying to override the register serializer, I want to add a name field but the default view still shows this is my configuration in settings.py ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = 'none' REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'accounts.serializers.CustomRegisterSerializer' } my url looks like this urlpatterns = [ path('', include('dj_rest_auth.urls')), path('registration/', include('dj_rest_auth.registration.urls')), ] while my serializer from dj_rest_auth.registration.serializers import RegisterSerializer class CustomRegisterSerializer(RegisterSerializer): name = serializers.CharField(max_length=100) email = serializers.EmailField() class Meta: model = get_user_model() fields = [ 'name', 'email' ] -
How to type hint self.client.patch in django.test.TestCase?
I am wondering what type hint to use as the output of _request in the following Django test case: from django.test import TestCase class SomeTestCase(TestCase): def _request(self, id: int, update_data: dict[str, Any]) -> ?: url = reverse('path', kwargs={'id': id}) return self.client.patch(url, update_data) ... -
Django-Rest - How to create URL & View to extract "GET" query parameters in different formats?
I have an application that is sending a GET request in the form of /myapi/details/?id="myid". Currently my Django-Rest server is setup to receive requests as follows: urls.py urlpatterns = [ path('/details/<str:id>/', views.details.as_view()), ] views.py class details(APIView): def get(self, request, id): //id contains the data This works fine when sending a GET request as /myapi/details/"myid". To try and also receive requests with /?id="myid" I added path('/details/?id=<str:id>/', views.details.as_view()), to urlpatterns, but sending the request still hits the other URL regardless of the order. What would be the correct way to go about this? Ideally, I would like to accept both /"myid" and /?id=<str:id> formats. -
How to filter table with class name in html?
If class = "node focused" , how can i filter the data with its id in table table-bordered table-sm table-active in base.html i want to see deatils only selected node in my table. {d.1} = div id <div id="TEM01" data-parent="ATK" class="node focused"><div class="title" style="width:200px"><i class="oci oci-leader symbol"></i>ATK</div> <div id="TEM02" data-parent="ATK" class="node"><div class="title" style="width:200px"><i class="oci oci-leader symbol"></i>ATK</div> chart.js below nodeClickHandler: function (event) { this.$chart.find('.focused').removeClass('focused'); $(event.delegateTarget).addClass('focused'); }, css below .orgchart .node.focused { background-color: rgba(217, 83, 79, 0.8); } base.html below. <body> <div id="chart-container"></div> {% block content %} {% endblock %} <script type="text/javascript" src="{% static 'js/jquery.js' %}"></script> <script type="text/javascript" src="{% static 'js/jquery.orgchart.js' %}"></script> <script src="{% static 'js/bootstrap.js' %}"></script> <div id=" row justify-content-md-center"> <div class="col-sm"> <h5 align="center"><i><span style="background-color: #262626" class=" badge badge-info">Node Information </span></i> </h5> <table class="table table-bordered table-sm table-active"> <tr> <th>DVS</th> <th>DWH</th> <th>AO_Trap</th> <th>BO_Trap</th> <th>Info</th> </tr> <tr> <tbody> {% for d in alltables %} <tr> <td>{{d.1}}</td> <td>{{d.1}}</td> <td>{{d.2}}</td> <td>{{d.3}}</td> </tr> {% endfor %} </tbody> </tr> </table> -
Django rest framework and fetch don't work
I am trying to make a simple api where a user writes something in an input, presses a button and a new instance is added in a database. To do this I am using react and django rest framework. App.js function handleClick() { fetch("http://127.0.0.1:8000/post", { method: "POST", body: { title: name, name:name } }) } return ( <> <form> <input type='text' value={name} onChange={handleChange} /> <button onClick={handleClick}>OK</button> </form> </> ); views.py @api_view(['POST']) def home2(request): serializer = ItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response() But when I press the button I get manifest.json:1 GET http://127.0.0.1:8000/manifest.json 404 (Not Found) and manifest.json:1 Manifest: Line: 1, column: 1, Syntax error. in javascript. In django I get manifest.json:1 Manifest: Line: 1, column: 1, Syntax error. Also I am using npm run build for javascript and manifest.json is in public folder. -
Django reflexive relationship
I am working with MongoDB v6.0.6 and Django v4.1.9. I have a reflexive relationship in one of my models: class Learner(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) supervisor = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL, related_name='learner_supervisor') profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="learner_profile") company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="learner_company") When I try to create an object in the Django admin, I encounter an issue with the error message: No exception message supplied A screenshot of the error message is available below: I'm not sure what the cause of this issue is. Can someone provide guidance on how I can solve it? Thank you. -
How Can I check image size and resize it in Django
I am working on a Django project where I want to check uploaded image size if it is more than 14kb, and resize it to be less than or equal to 14kb. My code below does the other checks but doesn't work on reducing the image size to be less than or equal to 14kb. So the image is been uploaded with the original size. Someone help with the best way using my code below. Understand that using django-imagekit could help me with all I needed while processing the image because of the implementation process. def clean_image(self): image = self.cleaned_data.get('image') if image: # Check if the image size exceeds 14kb if image.size > 14 * 1024: # 14kb in bytes # Open the image using Pillow with Image.open(image) as img: # Resize the image while preserving the aspect ratio max_size = (img.width, img.height) img.thumbnail(max_size) # Rotate the image if it's originally landscape if img.width > img.height: img = img.transpose(Image.ROTATE_90) # Convert the image to RGB mode img = img.convert('RGB') # Save the modified image to a BytesIO object buffer = BytesIO() img.save(buffer, format='JPEG') # Create a new InMemoryUploadedFile object with the modified image data modified_image = InMemoryUploadedFile( buffer, None, 'modified.jpg', … -
NameError: name 'Include' is not defined
I'm currently developing a Mobile Application with Django as Backend (I'm a beginner), but I have a problem with Python:Since I created my App I can't run % python manage.py makemigrations and got error line 8, in path('', Include('api.urls')), NameError: name 'Include' is not defined Am using Python -v 4.2 I tried % python manage.py makemigrations And expected Migration for "school": school\migration\0001_initial.py Create model Article -
Django Rest Framework POST not saving to database
@api_view(['POST']) def addProduct(request): serializer = ProductSerializer(data = request.data) if serializer.is_valid(): print("valid!!!") serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Above is my views.py for adding a product Below is my serializers.py from rest_framework import serializers from django.contrib.auth.models import User from products.models import Product from userProfile.serializers import UserSerializer class ProductSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Product fields = "__all__" Below is my Product model: class Product(models.Model): uuid = models.CharField(max_length=100) product_name = models.CharField(max_length=50) model = models.CharField(max_length=30) date_of_purchase = models.DateField() description = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) defects = models.CharField(max_length=500) price = models.IntegerField(default=100) slug = models.SlugField(max_length=200) def save(self, *args, **kwargs): self.slug = slugify(self.uuid) super(Product, self).save(*args, **kwargs) def __str__(self): return f"{self.product_name}" UserSerializer used in ProductSerializer from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username','first_name', 'last_name','email','date_joined','is_staff','is_active'] My input: { "id": 4, "user": { "username": "Anirudh", "first_name": "", "last_name": "", "email": "email@email.com", "date_joined": "2023-06-15T15:15:57.138400Z", "is_staff": true, "is_active": true }, "uuid": "qwerty", "product_name": "Phone", "model": "iPhone 12 mini 64GB", "date_of_purchase": "2021-08-15", "description": "Working condition, no dents. all buttons work. Upgrading to new phone so I am selling", "defects": "None", "price": 20000, "slug": "qwerty" } I am getting an error stating that user already exists with this username … -
Django model-field-choices became fields in table and cause not-null error
The choices of a multiselectfield seem to have become fields in my table. I cannot give them a value, but I get an error that they violate the non-null constaint. (I anonimised some of the code) My model.py class Plate(models.Model): Other irrelevant model fields here ------------------------ PR_MDPH = 'PR-variable1' PR_MDM = 'PR-variable2' PR_AL = 'PR-variable3' PR_LE = 'PR-variable4' PR_FB = 'PR-variable5' PR_DB = 'PR-variable6' PR_DFR = 'PR-variable7' PR_BDG = 'PR-variable8' PR_ME = 'PR-variable9' PR_NO = 'None' DEFECT_PR_CHOICES = ( (PR_MDPH, 'PR-variable1'), (PR_MDM, 'PR-variable2'), (PR_AL, 'PR-variable3'), (PR_LE, 'PR-variable4'), (PR_FB, 'PR-variable5'), (PR_DB, 'PR-variable6'), (PR_DFR, 'PR-variable7'), (PR_BDG, 'PR-variable8'), (PR_ME, 'PR-variable9'), (PR_NO, 'None'), ) AR_MDPH = 'AR-variable1' AR_MDM = 'AR-variable2' AR_AL = 'AR-variable3' AR_LE = 'AR-variable4' AR_FB = 'AR-variable5' AR_DB = 'AR-variable6' AR_DFR = 'AR-variable7' AR_BDG = 'AR-variable8' AR_ME = 'AR-variable9' AR_BO = 'AR-variable10' AR_GL = 'AR-variable11' AR_BW = 'AR-variable12' AR_NO = 'None' DEFECT_AR_CHOICES = ( (AR_MDPH, 'AR-variable1'), (AR_MDM, 'AR-variable'), (AR_AL, 'AR-variable'), (AR_LE, 'AR-variable'), (AR_FB, 'AR-variable'), (AR_DB, 'AR-variable'), (AR_DFR, 'AR-variable'), (AR_BDG, 'AR-variable'), (AR_ME, 'AR-variable'), (AR_BO, 'AR-variable'), (AR_GL, 'AR-variable'), (AR_BW, 'AR-variable'), (AR_NO, 'None'), ) PR_defect = MultiSelectField(choices=DEFECT_PR_CHOICES, default=PR_NO) AR_defect = MultiSelectField(choices=DEFECT_AR_CHOICES, default=AR_NO) When I look in my local pgAdmin database, I now have the following: randomField text blabla moreFields boolean NOT NULL "AR_defect" character varying(29) … -
How to define a model one-to-many relationship using a foreign key
I am trying to connect to tables using a foreign key in the following code: models.py class DailyTestDraft(models.Model): index = models.AutoField(db_column='Index', primary_key=True) # Field name made lowercase. gantry = models.IntegerField(db_column='Gantry', null=True) '.....' class DailyTestInput(models.Model): index = models.AutoField(db_column='Index', primary_key=True) # Field name made lowercase. energyID = models.IntegerField(db_column='energyID',null=True) '.......' indexid = models.ForeignKey(DailyTestDraft, on_delete=models.CASCADE, null=True, blank=True, default=None) # Field name made lowercase. views.py: form = DailyTestDraft(gantry=3) form.save() form2 = DailyTestInput(indexid=form) form2.save() I would like the table DailyTestInput to save the primary key of DailyTestDraft (which is index) into its foreign key variable which is indexid. However, I get the error "(1054, "Unknown column 'indexid_id' in 'field list'")" and when I change it to form2 = DailyTestInput(indexid_id=form) I get the error "Field 'index' expected a number but got <DailyTestDraft: 58>.". But when I change it to form2 = DailyTestInput(indexid_id=form.index) then I get the same error 1054. If I put form2 = DailyTestInput(indexid=form.index) then I get the error "Cannot assign "58": "DailyTestInput.indexid" must be a "DailyTestDraft" instance." Sorry for all the options, but I've been trying to make it work in many ways and I am a bit lost as to how it should be implemented. Thanks in advance for your help! -
Postgresql id conflict when migrated old db to new one
I migrated some data from my old db to new one with pk(id). What should I do in order to my new db continue from last id of migrated data. I encounter no problem while migrating but when project is running, there is problem while adding new object to the db. Project is done in django -
From DOCX to PDF replacing text
I have some docx where I want in django/python to replace text and then save them as PDF. They have pictures too so I need to keep them and some similar distribution. The thing is now Im unziping the docx, replacing the text and then opening it with libreoffice and saving them as PDF. I cannot change the fact that from the beginning the documents are docx, maybe they could be libreoffice but nothing else. The thing is that whenever I do that some pictures dissapear, they disspear when I open manually with libreoffice too, but I find nothing else. How could I proceed? -
choices=Status.choices, NameError: name 'Status' is not defined
I am receiving a "NameError: name 'Status' is not defined" when trying to run my Django program. This error occurs in my Post model when defining the Status field choices. I am following the Django book in 4 examples by Mele Antonio. Can you help me understand and fix this error? from django.db import models from django.utils import timezone class Post(models.Model): class Status(models.TextChoices): DRAFT = 'DF', 'Draft' PUBLISHED = 'PB', 'Published' title = models.CharField(max_length=250) slug = models.SlugField(max_length=250) body = models.TextField() published = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=2, choices=Status.choices, default=Status.DRAFT) class Meta: ordering = ['-published'] indexes = [ models.Index(fields=['-published']), ] def __str__(self): return self.title Note: This question is related to my previous question, and I will apply the solution given there to fix this issue. -
What is wrong with this Django model?
This Django model wmodel will not makemigration. In my app called question I have model.py as follows from django.db import models class Question(models.Model): question_number = models.PositiveIntegerField(default=1) part = models.CharField(max_length=4) sub_part = models.CharField(max_length=3) level = models.CharField(max_length=2) year = models.PositiveIntegerField(default=2) ceist = models.TextField() topic = models.CharField(max_length=20) sub_topic = models.CharField(max_length=20) type = models.CharField(max_length=20) answer = models.TextField() formula_definition = models.TextField() def __str__(self): return f'Question: {self.year} {self.question_number}' I try to migrate this with python3 manage.py makemigrations And this gives Migrations for 'questions': questions/migrations/0005_question_question_number_question_year.py - Add field question_number to question - Add field year to question But I don't see anything wrong with year. Any help would be greatly appreciated. -
template does not save Image to database
I'm creating a website where projects can be uploaded, each with a name, description, image, and a deadline. When I press the "Save Project" button, i get redirected to the homepage as expected, but the image does not get saved even though everything else does. I don't receive any error message. My Question is, why doesnt it save images to the database, but everything else does? Screenshot of input form: (https://i.stack.imgur.com/ZUVrC.png) Screenshot of homepage after saving a project: (https://i.stack.imgur.com/wrb0o.png) Here is my code: In models.py: from django.db import models class Project(models.Model): project_name = models.CharField(max_length=100) project_description = models.CharField(max_length=2000) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True,) deadline = models.DateTimeField(null=True, blank=True) def __str__(self): return self.project_name class Image(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='project_images') image = models.ImageField(null=True, blank=True, upload_to="images/") def __str__(self): return self.image.name In forms.py: from django import forms from django.forms import inlineformset_factory from .models import Project, Image class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ['project_name', 'project_description', 'deadline'] widgets = { 'deadline': forms.DateTimeInput(attrs={'type': 'date'}), } ImageFormSet = inlineformset_factory(Project, Image, fields=('image',), extra=5, can_delete=True,) In views.py: from django.shortcuts import render, redirect, get_object_or_404 from .models import Project from .forms import ProjectForm, ImageFormSet def homepage(request): projects = Project.objects.all() context = { 'projects': projects, } return render(request, 'project.html', context) def … -
How to use Authentication in Next js with the help of Api with JWT token?
Hello friends I want the authentication of NextJS using Django API from Simple JWT authentication. Mainly, I want to know how to redirect to the login if not authenticated and if login direct to the homepage (Checking the Authentication). -
calendar icon is not displayed django admin page
I'm currently working on customizing my Django admin page, and I'm facing an issue where the date picker icon is not displayed in the date input field. class FactureAdmin(ImportExportMixin,admin.ModelAdmin): inlines = (AllocationFactureInline,) admin.site.register(Facture,FactureAdmin) I was expecting to see a date picker with icons to choose the date, similar to this example: Additionally, my browser's console is reporting the following error: -
How do I access my Django app hosted on EC2?
I am running a django-based application (Arches) in an AWS EC2 instance, and am unable to access it on either the Public IPv4 address, or the Public IPv4 DNS. I have tried virtually all combinations of parameters, as well as the steps described in the following discussions: How do I access my Django app running on Amazon EC2? Access Django app on AWS EC2 host Connecting to EC2 Django development server Without :8000 ec2-xxxxxxxx.eu-central-1.compute.amazonaws.com refused to connect. With :8000 This site can’t provide a secure connection ec2-xxxxxxxxx.eu-central-1.compute.amazonaws.com sent an invalid response. Terminal output Changing the protocol to http gives the following error OSError at / Error reading /home/ubuntu/suhozid/suhozid/webpack/webpack-stats.json. Are you sure webpack has generated the file and the path is correct? Request Method: GET Request URL: http://3.76.192.148:8000/ Django Version: 3.2.19 Exception Type: OSError Exception Value: Error reading /home/ubuntu/suhozid/suhozid/webpack/webpack-stats.json. Are you sure webpack has generated the file and the path is correct? Exception Location: /home/ubuntu/dev/lib/python3.10/site-packages/webpack_loader/loader.py, line 29, in load_assets Python Executable: /home/ubuntu/dev/bin/python Python Version: 3.10.6 Python Path: ['/home/ubuntu/suhozid', '/home/ubuntu/suhozid', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/ubuntu/dev/lib/python3.10/site-packages', '/home/ubuntu/suhozid/suhozid'] Server time: Fri, 16 Jun 2023 04:50:13 -0500 I was hoping to be able to access my Django app by adding the addresses in settings.py ALLOWED_HOSTS = … -
access request object in custom function without passing as arg - django
Django issue: I’ve an issue accessing request object of api in a custom logger function where I save my logs to -> rabbitMQ and then Elastic for analysis. I need some of the information from request object and a userInfo(I add that key into request object at auth middleware), now when I create log schema I need some of the fields like request body, path , method, user info etc. to create user-specific logs. But I can’t pass request object directly to each function wherever I’m using my logger. Worst case: view -> function1 -> function2 -> function3…and so on. I need to pass request object to this nested chain where I’m logging in function_n. Is there any other way than passing request all through the chain. Any luck? Log Schema: <there have been multiple logs in a single api request at any point and of any type <info, error, warn or critical> { "tags": "LOG_TYPE_SHORTHAND", "custom": true, "req_id": "user_id:req_start_time", // nano seconds "timestamp": "TIMESTAMP", // for debugging and visual representations "message": "LOG_MESSAGE", // actual msg for that particular log "level": "LOG_LEVEL", // info, warn, err, debug, critical "service": "SERVICE_NAME", // router/main OR search - configurable once at api server … -
DRF best practice approach to handle custom errors in this code
I have a Django Rest project, and I'm looking for the best practice approach to handle custom errors and send them back to the user. Currently, there is a custom error being used in the API to respond to the user. However, this error is being used in another file that is not exclusively related to the API. I would prefer to capture the error within the view and display it to the user in that context. This way, the 'report.py' file can remain decoupled from the API and be used anywhere. Is this the best approach, and how can I effectively propagate the error upwards while still utilizing my custom error only within the view? In my report.py, I have this: if (self.total == 0): raise ValueError() but this is what I was doing before in report.py but I feel it is wrong as report.py is used not just on the API if (self.total == 0): raise MyAPIValueError() So can you do the following and is it the best approach or should I stick with above In the report raise normal ValueError class MyListView(BaseReportView): ……….. def get_queryset(self): queryset = super().get_queryset() try: return Report().data except (CustomAPIValueError)