Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django add object with the current user
I'm trying to create a todoapp with google login to create personal todolist for each users. here's views.py from django.contrib.auth.decorators import login_required @login_required def todoView(request): all_todo_items = Todoitem.objects.filter(userid=request.user.id) return render(request, 'todoapp/home.html', {'all_items': all_todo_items}) def addTodo(request): add_new_item = Todoitem(content=request.POST['content']) add_new_item.save() return HttpResponseRedirect('/home/') this is my code before without users but when there's currently login user it's throwing this error null value in column "id" violates not-null constraint / DETAIL: Failing row contains (null, sampletodo,null). I believe the third column which is null is the userid and first column null is auto increment id since I set it to id SERIAL primary key in todoitem table I'm 100% sure i need to add something @addTodo views.py, I just dont know how to add todolist with the current user -
Create foreign key from auth_group_permissions table in django
I want to make foreign key from auth_group_permissions table.(the M2M table between permission and group) I know that I can use through, but it isn't appropriate if I make modify in Django library. Is there any appropriate solution. -
does django encode passwords in the Database?
I created a user with a password password123 but in the database the password field look like this pbkdf2_sha256$260000$rJZWVrYXlokRG8fGMS1fek$S7Dm9soflUsy0Q74CJP8sB60tgfRWuRPdqj5XL0DBV0= the problem: is when I create new user via rest framework i got the poassword feidl look like passsword123 so how should i created new user in order to keep the django password encoding functionality also how to deactivate this password encoding functionality -
Django queryset time interval
I need to make object selections in my database by time interval currently i found a method to select only objects from a day but not from an interval with this: data.filter(end_at__day=datetime.datetime.now().day) I saw this on the django __gte documentation which means from a date until today but I failed to make it work I have try this: if request.method == 'POST': form = DashboardSettingsForm(data=request.POST) if form.is_valid(): dis_planned = form.cleaned_data.get('display_planned') dis_currently = form.cleaned_data.get('display_currently') dis_ended = form.cleaned_data.get('display_ended') end_at = start_at = datetime.now() if dis_ended: end_at = datetime.now() - timedelta(hours=12) if dis_planned: start_at = datetime.now() + timedelta(hours=12) data = data.filter(start_at__gt=start_at, end_at__gt=end_at) print(f"interval: start{start_at} end{end_at}") -
Error in setting up django model and serializer
I am having the following error in DRF ( Django Rest Framework ): Internal Server Error: /book/book/ Traceback (most recent call last): File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/generics.py", line 190, in post return self.create(request, *args, **kwargs) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/mixins.py", line 20, in create headers = self.get_success_headers(serializer.data) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 548, in data ret = super().data File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 246, in data self._data = self.to_representation(self.instance) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 515, in to_representation ret[field.field_name] = field.to_representation(attribute) File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/fields.py", line 1368, in to_representation return value.isoformat() AttributeError: 'SlotChoice' object has no attribute 'isoformat' Following is my serializer.py for booking: from rest_framework import serializers from .models import Booking from court.serializers import CourtSerializer from users.models import User from slots.models import SlotChoice from datetime import date class BookingSerializer(serializers.ModelSerializer): date = serializers.DateField( required=True, ) user = serializers.EmailField(required=True) court = CourtSerializer … -
Which AWS EC2 hardware options should I use for my project
I developed a django prject which uses social_auth (Google) for logins and when the user logs in to the website, their details (pre-stored in database) will be displayed to them and the user can select an option from a dropdown and then they will be provided an option to upload a pdf file and this submitted is stored in a Google drive. This project is an exam submission portal for our university where students can upload their answers written by them in a PDF format (as the exam is being conducted online). The PDF file size can be in range 2-10 mb. For storage I am using Google drive using the Django Google Drive Storage. Now, this project is completed and is working as expected in localhost but the problem is we couldn't figure out which ec2 service should we buy for this purpose. Let's say that the website is set to take submissions from 11:00 to 11:20 (Exam time ends at 11:00 , 20 mins for creating PDF and uploading it). The maximum number of submissions that can occur in that 20 mins is 3000. So, let's say that 1000 requests are done to the server at exact 11:10. … -
Why Django model extesion validator doesn't work
I want to only .xlsm files to be uploadable to the form.I tried a lot of thing according to this question. But did not work. I don't know why? How can I solve it? models.py from django.core.validators import FileExtensionValidator ... pdf = models.FileField(upload_to=customer_directory_path, null=True, blank=True, validators=[FileExtensionValidator(allowed_extensions=['xlsm'])]) ... -
How to include Run functionality in my API in Django?
I'm working on Django project where I have to make a API. In my normal Django I have one functionality named Run , that I want to add that functionality in my API View Here's my model class Robot(models.Model): robot = models.CharField(max_length=100) short_Description = models.CharField(max_length=200) status = models.CharField(max_length=20) parameter = models.CharField(max_length=200) jenkins_job = models.CharField(max_length=100, default='JenkinsJobName') jenkins_token = models.CharField(max_length=100, default='JenkinsToken') jenkins_build = models.CharField(max_length=10, default=0) jenkins_build_status = models.CharField(max_length=20, default="Never Run") def __str__(self): return self.robot class assignParameter(models.Model): parameterName = models.CharField(max_length=100, blank=True) assignRobot= models.ForeignKey(Robot, on_delete=models.CASCADE, related_name='param', blank=True, null=True) here's my serializer.py from .models import Robot,assignParameter from rest_framework import serializers class assignParameterSerializer(serializers.ModelSerializer): class Meta: model = assignParameter fields = ['id', 'parameterName', 'assignRobot'] class RobotSerializer(serializers.ModelSerializer): param = assignParameterSerializer(many=True, read_only=True) class Meta: model = Robot fields = ['id', 'robot', 'short_Description', 'status', 'parameter', 'jenkins_job', 'jenkins_token', 'jenkins_build', 'jenkins_build_status','param'] here's my normal run function def Run_data(Request,id): if Request.method == 'POST': pi = Robot.objects.get(pk=id) jenkinsJob = list(Robot.objects.values('jenkins_job').get(pk=id).values())[0] jenkinsToken = list(Robot.objects.values('jenkins_token').get(pk=id).values())[0] fm = RobotReg(Request.POST, instance=pi) out = fm.data robot_params = list(dict(out).values()) node = robot_params.pop(1)[0] url = list(Lookup.objects.values('Value').filter(Type='JENKINS_URL').values())[0].get('Value') Uipath = list(Lookup.objects.values('Additionalinfo').filter(Type='JENKINS_NODES',Value=node).values())[0].get('Additionalinfo') robotexe = list(Lookup.objects.values('Value').filter(Type='ROBOT_EXE_PATH',Additionalinfo=node).values())[0].get('Value') robot_params.append(['node', node]) robot_params.append(['Uipath', Uipath]) robot_params.append(['robotexe', robotexe]) params_count = len(robot_params) params_exist = len(robot_params[1][0]) params = "" urlFinal = "" # url = Lookup.objects.filter(Type="JENKINS_URL").values_list(Value) if params_count > 0: for i in … -
How to correctly delete Model object field in django
Hello I want to delete my field : tag_number = models.PositiveIntegerField('Tag number', validators=[ MinValueValidator(1), MaxValueValidator(MAX_TAG_NUMBER), ]) and write fo this method: # @require_POST def book_tag(request, pk): book = get_object_or_404(Book, pk=pk) book.tag_number = **book.tag_number.delete()** book.tag_number = book.generate_tag() book.save() return redirect('book:book-list') But it delete all Book Model!I want to delete just the field 'tag_number'. -
Can I write one viewset for List, Retrieve, Update, and Delete?
I am using a viewset.ModelViewSet to list, retrieve, update and delete Car objects. I have two urls: one ends with .as_view({'get': 'list'}) and other with .as_view({'get': 'retrieve'}), and latter one is used for updating and deleting a car object. Is it ok (won't it throw some errors in the future) or should I rewrite the PUT and DELETE in another view? -
Best practice to compile Django translation files
I am looking for a best practice approach on how to compile translation files in Django. Currently the following is given: GitHub + POEditor Importing into POEditor is done with Webhooks, which works quite fine. Exporting is also done automatically, but compiling the *.po to a *.mo still needs human intervention. One approach could be to do this with GitHub Actions. Is there such a thing as a Best Practice for this? How are large organisations are dealing with this? Thanks -
Using fields from a aggregated QuerySet in a django template
So I got a QuerySet result from an aggregate function to display in a low-spec eBay clone of mine. But my problem is displaying certain fields in the Django template as I want, for example, I want to display the highest bidder's username and bid. When I call the whole object itself like so {{winner}}, then it displays. But when I try to access its fields like so {{winner.user_id.username}}, I get no output although the QuerySet does execute. When I try to get a field like so (winner.user_id.username): When I only call winner: models.py from django.contrib.auth.models import AbstractUser from django.db import models CATEGORIES = [ ('Appliances', 'Appliances'), ('Tech', 'Tech'), ('Gaming', 'Gaming'), ('Fashion', 'Fashion'), ('Sports and Fitness','Sports and Fitness'), ('Other','Other'), ("Hygiene and Medicine","Hygiene and Medicine"), ("Stationery","Stationery"), ('Decor', 'Decor'), ('Furniture','Furniture'), ('Cars and Mechanical Things','Cars and Mechanical Things'), ("Tools","Tools") ] # Create models here class User(AbstractUser): pass class Auction_Listing(models.Model): user_id = models.IntegerField(default=1) list_title = models.CharField(max_length=64) desc = models.TextField(max_length=600) img_url = models.URLField(max_length=200, null=True, blank=True) start_bid = models.IntegerField() category = models.CharField(choices=CATEGORIES, max_length=35, null=True, blank=True) active = models.BooleanField(default=True) def __str__(self): return f"ID:{self.id}, {self.list_title}: {self.desc}, {self.start_bid} posted by user:{self.user_id} in Category:{self.category}, url:{self.img_url}" class Bids(models.Model): user_id = models.ForeignKey('User', on_delete=models.CASCADE) auctions = models.ForeignKey('Auction_Listing', on_delete=models.CASCADE, default=1,related_name='bidauc') bid = models.IntegerField() def … -
How to obtain custom simpleJWT tokens in views with Django?
I have a custom serializer to get tokens without a password for a user: class ObtainTokensWithoutPasswordSerializer(TokenObtainPairSerializer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['password'].required = False def validate(self, attrs): attrs.update({'password': ''}) return super(TokenObtainPairWithoutPasswordSerializer, self).validate(attrs) In my views I use it like this: class ObtainTokensWithoutPasswordView(TokenViewBase): serializer_class = ObtainTokensWithoutPasswordSerializer And finally, this is the url to get the tokens: path('token/', views.ObtainTokensWithoutPasswordView.as_view()), Making a request to this url returns tokens correctly but I would need to obtain a pair of tokens in another class in views.py. Can I do it somehow using my serializer class, for example something like this: class UserClass(generics.ListCreateAPIView): permission_classes = (AllowAny,) serializer_class = UserSerializer def post(self, request): ... tokens = ObtainTokensWithoutPasswordSerializer -
Django web app css not being refreshed in browser
I'm having some issue with a django app and it's CSS file refreshing. Basically I can see that the changes I make in my file are identified and copied in the root folder of my website, however when I open up the web browser that change is not being displayed at all: I am using Firefox as a browser however this issue happens also on Chromium browser -
How do I send a file to the Django server via ajax?
I can't figure out for more than a week, I need to send an image to the Django server, but I get the error: 415 (Unsupported Media Type) If I change ContentType to multipart/form-data, I get: 400 (Bad Request) is sent via postman normally, what could be the error?: ( Script updateUser() { $.ajax({ url: "http://localhost:8002/api/update_profile/" + this.username + "/", data: { first_name: this.first_name, username: this.login, last_name: this.last_name, email: this.email, photo: this.image }, DataServiceVersion: 2.0, processData: false, contentType: false, // contentType:"multipart/form-data", type: "PUT", success: function(data) { location.reload() }, error: function(response) { console.log(this.data) let err = response.responseJSON; for (let key in err) { alert(key, err[key].toString()); } } }); }, -
Want to convert proper JSON request in AXIOS ReactJs to send to django
My payload is in string form as below: payload= "[{"message":"message text", "id":1, "code":0}, {"message":"message text", "id":2, "code":1}, {"message":"message text", "id":3, "code":0}]" I am getting the pay load from query string. ex = https:\xyz.com\endpoint?payload=[{"message":"message text", "id":1, "code":0}, {"message":"message text", "id":2, "code":1}, {"message":"message text", "id":3, "code":0}] JSON.stringify(payload) does not help here as it is a string and JSON.parse(payload) throws error. the axios request is as below: try { const response = await axiosInstance.post('/postenpoint/', payload, { headers: authHeader }); return response; } catch (error) { console.log(error); }; is there any inbuilt function or effective way in JS other than string parsing in such case? The problem is at backend which is developed using django gets the response as {'[{"message":"message text", "id":1, "code":0}, {"message":"message text", "id":2, "code":1}, {"message":"message text", "id":3, "code":0}]': ''} This must go as proper json form instead it' goin as a key only. -
pip library body_measurements (python)
I want to get the body measurements through an image using pip library body_measurements. Is there any material related to this? I have seen openCV2 library for this thing but that does not my requirement. -
Fetching specific data from SQLite DB to django forms
how do I fetch like specific data I want to a django form. I know how to fetch the entire database to a table by using loops. But I want to fetch specific data according to what user select. At the back of my mind, i know the flow. Eg. Step 1, user choose which data they want to look. Step 2, goes to the table to find the specific data user wants. Step 3: Display it in a html page. I have this table in my web and when user lets say click the edit button for 1st row, it goes to a new html with all its details listed in a table. Eventually i want it to display a form with all the data (2 tables) stored Html: {% extends "interface/base.html" %} {% block footer_scripts %} {{ block.super }} <script> // additional javascript </script> {% endblock footer_scripts %} {% block content %} <div class="content-page"> <div class="content"> <!-- start page title --> <div class="row"> <div class="col-12"> <div class="page-title-box"> <!--<div class="page-title-right"> <ol class="breadcrumb m-0"> <li class="breadcrumb-item"><a href="javascript: void(0);">Hyper</a></li> <li class="breadcrumb-item"><a href="javascript: void(0);">eCommerce</a></li> <li class="breadcrumb-item active">Devices</li> </ol> </div> --> <h4 class="page-title">{{hostname}}</h4> </div> </div> </div> <!-- end page title --> <div class="row"> … -
Django multiple radio input from HTML form with same name
I am having a problem with Django forms. I am currently using the request.POST to validate the POST within views. I want to send inputed-data(radio type) from my template with the same name. In my template.py: <form method="post" action="{% url 'app:AnsSubmission' %}"> {% csrf_token %} {% for i in Exam %} <div class="form-group col-xl-12"> <label>{{ i.question }}</label> <div class="radio"> <label><input type="radio" class="mx-2" name="givenAns" array_column="{{ i.pk }} value="True" required>True</label> </div> <div class="radio"> <label><input type="radio" class="mx-2" name="givenAns" array_column="{{ i.pk }} value="False" required>False</label> </div> </div> {% endfor %} <button type="submit" class="btn btn-primary">Submit</button> </form> And willing to fetch these data in views.py like: givenAns_list = request.POST.getlist('givenAns') for i in givenAns_list: this_givenAns = givenAns_list[i] But the problem here is this radio type input field doesn't take value for the same name(not as a list I wish). If I select answer of 2nd question, the 1st one's selection is unselected. Please suggest how can I fix this? -
Django Jazzmin add button disappeared after adding mptt admin
I'm using jazzmin for django admin and mptt. After adding mptt to admin, in jazzmin theme add button disappeared. I'm using latest versions of all libraries class CustomMPTTModelAdmin(MPTTModelAdmin): # specify pixel amount for this ModelAdmin only: mptt_level_indent = 30 admin.site.register(Menu, CustomMPTTModelAdmin) Here you can see the admin where button disappeared When I disable jazzmin or remove Mptt add button returns back on place INSTALLED_APPS = [ # 'jazzmin', ..... ] Here you can button returns back There is also issue was opened on github https://github.com/farridav/django-jazzmin/issues/126 but I could not find solution for this problem -
cannot activate virtualenv via python terminal
I create a virtual environment named djangoenv. I can run it with using cmd but I cannot in python terminal this is cmd picture and this is python terminal picture how can I run this server in python terminal? -
Problems in debugging Django projects in Pycharm
I'm having a problem debugging Django projects in Pycharm (2021 CE) and following is my config I can run (by clicking the run button) the project with no problem; Server runs fine and serves traffic. But I have problems debugging it. This the command generated by Pycharm /home/cheng/Environments/proj1_env/bin/python3.8 /snap/pycharm-community/248/plugins/python-ce/helpers/pydev/pydevd.py --multiproc --qt-support=auto --client 127.0.0.1 --port 34965 --file /home/cheng/code/test_web/manage.py runserver The error message is Connected to pydev debugger (build 212.4746.96) /home/cheng/Environments/proj1_env/bin/python3.8: can't find '__main__' module in '' Need some help. Thanks! -
Please help me on following error with Django and PostgreSQL with docker
My Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /django COPY requirements.txt requirements.txt RUN pip install -r requirements.txt My docker-compose.yml version: '3' services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres container_name: postgres_db web: build: . volumes: - .:/django ports: - "8000:8000" links: - db:db depends_on: - db image: web:django container_name: django_container command: python manage.py runserver 0.0.0.0:8000 And I am getting error like django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution -
Django REST with jwt + regular admin panel
I've setup a basic django app using scaffolding which creates all those nice admin panels for free. I want to expose a REST api so I've followed this tutorial to get it running and add JWT authentication through simplejwt. I have tested my rest auth endpoints, gotten a token and used that token to consume a secured rest endpoint. The problem is -- as soon as I enable this auth scheme, the admin panel stops working. I can't login at all. Which I guess it makes sense considering I've changed the auth paradigm, but it kinda defeats the purpose of the scaffolding to lose all those free admin panels. Is it possible to combine both jwt authentication for my REST services while keeping regular authentication scheme for my admin panel? I want to do a public frontend through REST but keeping my backoffice within the same deployment as the backedn itself. -
I send any email with website that also show me on my email's sent box
Hello I have 1 question that i want to integrate my outlook with my django website that means if i send any email with website that also show me on my email's sent box. Can anyone help me to do this.