Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest framework get vieset by route basename
A basic class based view in django gives view name by reslove(reverse("url-name")).func But is there anyway I get viewset name by route basename. When I try reverse("basename") I get errors. -
Django : request.body isn't null but request.POST is null
I wanna test LOGIN function. I used Insomnia to send signal. like this: enter image description here I found request.POST is always null, but request.body is not. In terminal, Output is as follows: print(request.body) : b'{\n\t"userid" : "TEST",\n\t"userpw" : "TEST",\n\t"created" : ""\n}' print(request.POST) : <QueryDict: {}> My code in PyCharm: models.py : from django.db import models class AppAddresses(models.Model): userid = models.CharField(max_length=30, null=False, default=False) userpw = models.CharField(max_length=30, null=False, default=False) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created'] serializers.py : from rest_framework import serializers from .models import AppAddresses class AppAddressesSerializer(serializers.ModelSerializer): class Meta: model = AppAddresses fields = ['userid', 'userpw'] urls.py : from django.contrib import admin from django.urls import path, include from addresses import views urlpatterns = [ path('app_login/', views.app_login), path('app_signup/', views.app_signup), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] views.py : from django.contrib.auth.models import User from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from .models import AppAddresses from .serializers import AppAddressesSerializer from django.contrib.auth import authenticate @csrf_exempt def app_login(request): if request.method == 'POST': id = request.POST.get('userid', '') pw = request.POST.get('userpw', '') print(request.body) print(request.POST) login_result = authenticate(username=id, password=pw) if login_result: print("SUCCESS!") return JsonResponse({'code': '0000', 'msg': 'SUCCESS'}, status=200) else: print("FAILED!") return JsonResponse({'code': '1001', 'msg': 'FAILED'}, status=401) elif request.method == 'GET': query_set = AppAddresses.objects.all() serializer = AppAddressesSerializer(query_set, … -
Error : "Invalid block tag on line 51: 'endif', expected 'empty' or 'endfor'. Did you forget to register or load this tag?' in Django vscode
I was unable to solve this error which was occured in Django website. Here's my view.py file from django.shortcuts import render from .models import Product from math import ceil from django.http import HttpResponse def index(request): products = Product.objects.all() n = len(products) nSlides = n//4 + ceil((n/4) + (n//4)) params = {'no_of_slides': nSlides, 'range': range( 1, nSlides), 'product': products} return render(request, "shop/index.html", params) def about(request): return render(request, 'shop/about.html') def contact(request): return HttpResponse("We are at contact") def tracker(request): return HttpResponse("We are at tracker") def search(request): return HttpResponse("We are at search") def prodview(request): return HttpResponse("We are at product view") def checkout(request): return HttpResponse("We are at checkout") Basic.html file :- <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous" /> <title>{%block title%} {%endblock%}</title> <style> {%block css%} {%endblock%} </style> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#">My Awesome Cart</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#" >Home <span class="sr-only">(current)</span></a > </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" … -
Creating an inline-formset with inlineformset_factory
okay, I still dont get how to create an inlineformset. Following 2 different tutorials and everything I found in the docs I still dont get question to show up. It only displays the 3 Choices for me models.py class Question(models.Model): question_text = models.CharField(max_length=200) pub_date: DateTimeField = models.DateTimeField('date published', default=timezone.now) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) forms.py class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ['question_text'] class ChoiceForm(forms.ModelForm): class Meta: model = Choice fields = ('choice_text',) QuestionFormSet = inlineformset_factory( Question, Choice, form=ChoiceForm, min_num=2, max_num=10, extra=1, can_delete=True ) views.py class IndexView(generic.CreateView): model = Question template_name = 'polls/index.html' form_class = QuestionFormSet success_url = None def get_context_data(self, *, object_list=None, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) if self.request.POST: context['form'] = QuestionFormSet(self.request.POST) else: context['form'] = QuestionFormSet() return context -
My Django website's LINKS is not working on Cpanel
I have already uploaded my Django project file on CPANEL. My website is hosted (https://abccypher.com/) correctly. But when I click on my links it is showing- FILE NOT FOUND. This is the homepage and when you will click sign up or any links it will show "File not found" If anyone is there please guide me. I can discuss this with you. -
How to set uniques values only for the child model?
I have the following related models: class DeviceType(models.Model): type_name = models.CharField(primary_key=True, max_length=64, unique=True) type_description = models.TextField(max_length=512, blank=True) class DeviceTypeMarker(models.Model): marker_status = IntegerField() marker_status_text = models.CharField(max_length=64) marker = models.ImageField(upload_to='images/types/') marker_device_type = models.ForeignKey(DeviceType, on_delete=models.CASCADE, related_name='marker') Where it is possible to define many DeviceType elements. For every DeviceType element there can be many differents marker_status, marker_status_text and marker. The thing is that i don't want that inside a single DeviceType this elements are duplicated. They can be repeated but only in an another DeviceType. For example, if type1 is a DeviceType object, then there can be only a marker_status with value "1", only a marker_status_textwith value "error" and the same for marker. This values could only be repeated in an other DeviceType object. For example, type2.. How is this done? -
Django created_at field not added when creating an object
I'm trying to get Django automatically add a field to an object where the date and time is saved in the field as a timestamp. When I create the object in my view and I go check in admin page, every other field is created but not this one. views.py : newconf = ConfigUser.objects.create( ref=''.join(random.SystemRandom().choice( string.ascii_lowercase + string.ascii_uppercase + string.digits ) for _ in range(20)), name='', user=request.user, # Here I don't add created_at because I want it to be automatic (see models.py) cpu=cpu[0], gpu=gpu[0], ram=ram[0], ssd_m2=ssd_m2[0], ) models.py : class ConfigUser(models.Model): ref = models.CharField(max_length=20, unique=True, default='') name = models.CharField(max_length=128, default='') user = models.OneToOneField(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) cpu = models.ForeignKey(CPU, on_delete=models.CASCADE) gpu = models.ForeignKey(GPU, on_delete=models.CASCADE) ram = models.ForeignKey(RAM, on_delete=models.CASCADE) ssd_m2 = models.ForeignKey(SSD_M2, on_delete=models.CASCADE) def __str__(self): return self.name -
Unauthorized user probllem with jwt tokens in django rest framework
i am logged in with verified credentials then i verified the token which is sent to the user email.then when i am trying to login again i am not able to do so it is showing the below error. System check identified no issues (0 silenced). December 26, 2020 - 16:52:04 Django version 3.1.4, using settings 'backend_api.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Unauthorized: /user/login/ [26/Dec/2020 16:52:10] "POST /user/login/ HTTP/1.1" 401 43 Unauthorized: /user/login/ [26/Dec/2020 16:52:27] "POST /user/login/ HTTP/1.1" 401 34 Unauthorized: /user/login/ [26/Dec/2020 16:52:33] "POST /user/login/ HTTP/1.1" 401 34 -
How can I check user id in Django in order to redirect him based on his role (admin or normal user)?
I want to use the same login form in order to redirect the user into the required page if he is an admin go to the admin page if not go to normal user page. -
Django UpdateView Reverse for 'update_hours' with arguments '('',)' not found
So I have this ListView that work but when I want to put a button on it to update one of the objects I get error Reverse for 'update_hours' with arguments '('',)' not found. update_hours is the namespace VIEWS.PY class HoursList(ListView): context_object_name = 'object' paginate_by = 32 fields = ( 'start_date', 'end_date', 'hours_int', ) k_url_kwarg = 'pk' template_name = 'users/hours-list.html' def get_queryset(self): queryset = TimeLog.objects.filter(id=self.kwargs['pk']) return queryset class update_hours(UpdateView): # model = TimeLog fields = '__all__' template_name = 'users/hours-update.html' success_url = reverse_lazy('hours_list') def get_object(self): return get_object_or_404(TimeLog, pk=self.kwargs['pk']) All is fine at this point, but when I add a button in hours-list.html (the last line as shown below), I get the error. hours-list.html (template) {% for obj in object %} <tr> <td>{{ obj.end_date |date:' l ' }}</td> <td>{{ obj.end_date |date:' M jS ' }}</td> <td>{{ obj.start_date |date:' g:i A' }}</td> <td>{{ obj.end_date |date:' g:i A' }}</td> <td>{{ obj.hours_int }} h</td> <td> <button href="{% url 'update_hours' em.pk %}">pdf></button> </td> </tr> {% endfor %} What I'm I missing? Will really appreciate any help. -
Why i get 'NoneType' object has no attribute 'quantity' this error in my code
I want to subtract product quantity to user_give_quantity . But it has show these types of error 'NoneType' object has no attribute 'quantity' class Order(models.Model): item_name = models.CharField(max_length=255, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, null=True) distribute_price = models.IntegerField(null=True) mrp_price = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) user_give_quantity = models.IntegerField(null=True, blank=True) user_price = models.IntegerField(null=True, blank=True) def __str__(self): return self.item_name def total_price(self): return self.mrp_price * self.user_give_quantity def available_quantity(self): return self.product.quantity - self.user_give_quantity -
django what happends if I bulk_update values which are not changed?
So I have a function like this, which bulk-updates a many-many field for the parent_object with the given data. The problem is, not every object given in the data parameter will have its position changed. So, What will happen if I tell django to bulk_update values whose positions aren't changed already? Will any exceptions be raised? For instance, let the list of objects in a many-many field be: [id=1'blue', id=2'green', id=3'yellow'] If I tell django to update these values like [id=1 update to 'blue', id=2 update to 'purple', id=3 update to 'magenta'] will any errors occur? def overwrite_object_positions(self, data: list, parent_object): """ Overwrites object-positions, enclosed within a transaction. Rolls-back if any error arises. """ transaction.set_autocommit(False) try: self.get_overwrite_objects(parent_object).bulk_update(data, ['position']) except Exception as err: transaction.rollback() raise ValueError(err) else: transaction.commit() finally: transaction.set_autocommit(True) -
nested serialize Django object
hi guys i want to serialize my model's object. and my model like this : class User (models.Model): name = models.CharField(max_length=30) family_name = models.CharField(max_length=30) and i have another model like this: class Child (models.Model): little_name = models.CharField(max_length=30) user = models.ForeignKey("User", on_delete=models.CASCADE,) i want to serialize one of my child object with all fields in user field for example like this: {"id": 1 , "little_name": "Sam", "user": {"id": 1, "name": "Karim", "family_name":"Kari" } } i use model_to_dict() and dict() and serializer of django but i can't get user field compeletly and they return it like this : {"id": 1 , "little_name": "Sam", "user": "id": 1, } and i don't want to use django rest serializer what can i do ?!? -
Getting This Error : TemplateDoesNotExist at post/1/
Can anyone please help me with this error when i am trying to access the page it shows this error Exception Type: TemplateDoesNotExist Exception Value: firstblog/post_detail.html Exception Location: C:\Users\ADMIN\Envs\test\lib\site-packages\django\template\loader.py, line 47, in select_template views.py class PostDetailView(DetailView): model = Post url.py urlpatterns = [ path('',PostListView.as_view(), name='blog-home'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('about/',views.about, name='blog-about'), ] -
Is it possible to create SQLite Triggers, Procedures, Views in Django?
I am working on my DBMS college Project. I am using Django to create an event management website, my teacher told me to also add Triggers, Views, and Procedures to my website but I don't know how to do it. Please tell me how to write SQLite Triggers, Procedures, Views in a Django Project. -
Django Save generated pdf from django-renderpdf
I'm using this package to generate pdf files and it works like a charm. Now I have to send the generated file per email and I'm wondering how to automatically save the generated file on a specific path or sending directly per email. The problem is not sending the email, but how to get the content of the pdf to save it or to send it. Here what I have so far: from django_renderpdf.views import PDFView class InvoiceSpecification(PDFView): template_name = 'reports/invoice/specification.html' prompt_download = True @property def download_name(self) -> str: invoice = Invoice.objects.get(pk=self.kwargs['pk']) return f"WeeklyMetre_{invoice.invoice_number}.pdf" def get_context_data(self, **kwargs): context = super(InvoiceSpecification, self).get_context_data(**kwargs) mlss = MarketLaborSpecification.objects.filter(invoice_id=self.kwargs.get('pk')).order_by('specification__category', 'specification__position') market_labor_specifications = {} for mls in mlss: if mls.specification.category.name not in market_labor_specifications.keys(): market_labor_specifications[mls.specification.category.name] = [] if not any(d.get('position', 'bla') == mls.specification.position for d in market_labor_specifications[mls.specification.category.name]): market_labor_specifications[mls.specification.category.name].append( { 'position': mls.specification.position, 'name': mls.specification.name, 'validated': mls.validated_quantity, 'invoice_price': mls.invoice_price } ) else: for d in market_labor_specifications[mls.specification.category.name]: if d['position'] == mls.specification.position: d['validated'] += mls.validated_quantity break invoice = Invoice.objects.get(pk=self.kwargs.get('pk')) context.update({ 'page_title': _('Incoice overview: {}'.format(invoice)), 'invoice': invoice, 'market_labor_specifications': market_labor_specifications, }) return context The template is a simple html file. Any help will be appreciated ;) -
I wanted to create a google classroom like thing with python [closed]
Actually, I wanted to create a google classroom like thing (not with all the features just video conferencing) with python on web. I searched for it a lot but could not find out anything. Please help me out with this and plz send a sample code if you can. ASAP!!!!! -
How I can store api keys in django tenants app
I am facing a problem to store apikeys for django tenant application, where each subdomain owners need to have payment processing, so is ther any way owners can add their keys without the help of developers, when they create a new domain. I tried to store in db on shared app and called but the out put is empty for tenant users, but getting the value printed in main domain. from accounts.models import ExternalKeys api_key = ExternalKeys.objects.all().order_by('pk').first().secret_key try: print(api_key) except: pass -
For loop not working in python shell while inputting data in sqlite Db
For loop not working to input data from a python df column to a django model, i have used similar techniques in the past but this time the loop only iterates once, i tried checking the colist and it prints list of cos perfectly, doesnt seem to work inside the loop. Help would be much appreciated. import pandas as pd from Main.models import ServiceCos df = pd.read_csv('Assets/SERVICESdf.csv') colist = df['Company Name'] cos_list = df['Symbol'] for c in colist: s = ServiceCos(company_N_ser=c) #company_N_ser is the field name s.save() -
Django Internationalization sımple question
Hello guys i've a simple question for django. I have a model like this: Link_tr Link_en Link_fr And at template i want to use like this: {{pk1.Link_{{LANGUAGE_CODE}}}} but django dont accept. I hope someone can solve my problem. -
cx_Oracle.DatabaseError: DPI-1013: not supported
0 I am trying to run a code to create tables in oracle database.I am using Python 3.9.0 and Oracle Database 10g Express Edition Release 11.2.0. in windows 64 bit. -
How can I use multible images for Django product model?
I want to create a online shop website in Django and I don't know how to make a model of product that can have many images. For example it can contain 0, 5 or even 50 Images. I don't want to write spagetti code with 10 image fields with blank=True + null=True. And by searching on the internet I have not found anything that can help me. So please just don't send other stackoverflow question. Also I will add a new product from Admin page not from templates :) hope this question is gonna be answered! -
Django fetch latest matching rows for each entity
I'm using Django. My tables look like that: class Person: id = ... name = ... city = models.TextField(null=False) class Picture: id = .... date_captured = models.DateTimeField() Person = models.ForeignKey(Person, related_name='+', null=False, on_delete=models.CASCADE) I want to fetch for each person from the city XXX all the images from the latest date their image was taken. For example: If person A from city XXX had his pictures taken on July 10, 12, 14 And person B from city XXX had his pictures taken on July 6, 10, 19 And person C from city YYY had his pictures taken on July 1, 5, 25 Then I want to fetch for person A all his images from July 14 (NOTE that there can be multiple images of person A from the 14th, and I need all of them), and for person B all of his images from July 10, and ignore Person C since he is not from city XXX. How can this be done -
customizing registration django fields
i am trying to make my own blog, and every blog have a registration template, when it comes to customizing it in my template i did it all wrong so please help template.html: <form action="" method="post"> {% csrf_token %} <label for="username">Username</label><br> {{forms.username}} <br> <label for="email">Email</label><br> {{forms.email}}<br> <label for="password1">Password</label><br> {{forms.password1}} <br> <label for="password2">Confirm Password</label><br> {{forms.password2}} <br> {% if forms.errors %} {% for field in forms %} {% for error in field.errors %} <h5 style="color: red;">{{ error|escape }}</h5> {% endfor %} {% endfor %} {% for error in forms.non_field_errors %} <h5 style="color: red;">{{ error|escape }}</h5> {% endfor %} {% endif %} <br> <input type="submit" value="Register"> </form> my forms.py: class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def clean_username(self): username = self.cleaned_data.get("username") if User.objects.filter(username=username).exists(): raise forms.ValidationError("Username is not unique") return username def clean_email(self): email = self.cleaned_data.get("email") if User.objects.filter(email=email).exists(): raise forms.ValidationError("Email is not unique") return email my views.py: def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() else: form = RegisterForm() context = {'forms':form} return render(request, 'register/register.html', context) i dont know how to edit my template to have a customized registration form. thank you<3 -
dramatiq: Requested setting INSTALLED_APPS, but settings are not configured
I have following code structure manage.py src/ invoices/ helpers/ invoce_worker.py (def retrieve_invoices - dramatiq task) I run dramatiq task using dramatiq --watch . src.invoices.helpers.invoice_worker and get following error [2020-12-26 12:56:02,331] [PID 32562] [MainThread] [dramatiq.MainProcess] [INFO] Dramatiq '1.9.0' is booting up. [2020-12-26 12:56:02,348] [PID 32562] [MainThread] [dramatiq.MainProcess] [CRITICAL] Worker with PID 32565 exited unexpectedly (code 1). Shutting down... Process Process-1: Traceback (most recent call last): File "/usr/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap self.run() File "/usr/lib/python3.8/multiprocessing/process.py", line 108, in run self._target(*self._args, **self._kwargs) File "/home/m0nte-cr1st0/.virtualenvs/sortif-backend/lib/python3.8/site-packages/dramatiq/cli.py", line 330, in worker_process module, broker = import_broker(args.broker) File "/home/m0nte-cr1st0/.virtualenvs/sortif-backend/lib/python3.8/site-packages/dramatiq/cli.py", line 120, in import_broker module, broker = import_object(value) File "/home/m0nte-cr1st0/.virtualenvs/sortif-backend/lib/python3.8/site-packages/dramatiq/cli.py", line 109, in import_object module = importlib.import_module(modname) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "./src/invoices/helpers/invoice_worker.py", line 5, in <module> from src.invoices.helpers.invoices_filter import get_unfiltered_invoices File "./src/invoices/helpers/invoices_filter.py", line 5, in <module> from src.mails.models import MailAttachment File "./src/mails/models.py", line 7, in <module> from src.prest_jwt_auth.models import ClientEmail File "./src/prest_jwt_auth/models.py", line 5, in <module> class Plan(models.Model): File "/home/m0nte-cr1st0/.virtualenvs/sortif-backend/lib/python3.8/site-packages/django/db/models/base.py", …