Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to access tables with Foreign Keys in Django Admin site
I'm pretty new to Django and have been following a few online courses and create a own project on my one. I recently encountered a problem with the foreign keys in Django. Whenever I try to access the attributes from my admin site, the attributes with Foreign keys declared react with an Operational Error:(https://i.stack.imgur.com/ECRve.png) as attached. Are there any steps or pieces of code which I'm missing? Models.py file: import sys from django.utils.timezone import now try: from django.db import models except Exception: print("There was an error loading django modules. Do you have django installed?") sys.exit() from django.conf import settings import uuid from django.core.validators import RegexValidator import datetime from django.utils.text import gettext_lazy as _ #Specifications of Donor class Donor(models.Model): donor_id=models.IntegerField(blank=False, unique=True, primary_key= True) donor_firstname=models.CharField(blank=False,max_length=60) donor_surname=models.CharField(blank=False,max_length=60) donor_dob=models.DateField(blank=False,default=datetime.date.today) DONOR_GENDERS=[ ('Male','Male'), ('Female','Female') ] donor_gender=models.CharField(blank=False,max_length=60,choices=DONOR_GENDERS) donor_contact=models.IntegerField(blank=False,validators=[RegexValidator(regex='^[0-9]{10}$',message=_('Invalid Phone Number'))]) donor_email=models.EmailField(blank=False) donor_medical_history=models.CharField(blank=True,max_length=300) def __str__(self): return "Donor ID: " + self.donor_id + "Donor First Name: " + self.donor_firstname + \ "Donor Surame: " + self.donor_surname + "Donor Date of Birth: " + self.donor_dob + \ "Donor Gender: " + self.donor_gender + "Donor Contact Phone Number: " + self.donor_contact+\ "Donor Email: " + self.donor_email + "Donor medical History: " + self.donor_medical_history class Hospitals(models.Model): hospital_id=models.IntegerField(blank=False, unique=True, primary_key= True) hospital_name=models.CharField(blank=False,max_length=60) hospital_contact_person=models.CharField(blank=False,max_length=60) … -
Updating and refreshing front end variables with javascript
I am wanting the item quantity my Cart page to refresh and update if quantity is changed with out having to refresh the page. The buttons are working regarding adding and removing items to the back end. But nothing is happening on the Cart page its self. My view: def get_item_quantity(request): user = request.user if user.is_authenticated: try: cart = Cart.objects.get(user=user) quantities = {item.product_id: item.quantity for item in cart.items.all()} return JsonResponse({'quantities': quantities}) except Cart.DoesNotExist: return JsonResponse({'status': 'error', 'message': 'Cart not found'}) else: return JsonResponse({'status': 'error', 'message': 'User not authenticated'}) My script: function updateItemQuantity() { fetch("/get_item_quantity/") .then((response) => response.json()) .then((data) => { if (data.status === 'error') { console.error(data.message); } else { document.getElementById("item-quantity") } }) .catch((error) => { console.error(error); }); } window.addEventListener("load", updateItemQuantity); HTML SNIPPET {{item.quantity}} is what i want to be updated: {% for item in items %} <svg class="icon--cart update-cart" data-product="{{item.product.id}}" data-action="add"> <use href="/media/sprite.svg#plus-solid"/> </svg> <span id="item-quantity{{item.product.id}}" class="quantity">{{item.quantity}}</span> <svg class="icon--cart update-cart" data-product="{{item.product.id}}" data-action="remove"> <use href="/media/sprite.svg#minus-solid"/> </svg> {% endfor %} -
Field 'id' expected a number but got '6/'
models.py: class Cart(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE, default=1, null=True, blank=True) quantity = models.PositiveIntegerField(default=1) @property def total_cost(self): return self.quantity * self.product.discounted_price views.py: def add_to_cart(request): user = request.user product_id = request.GET.get('prod_id') product = Product.objects.get(id=product_id) Cart(user=user,product=product).save() return redirect('/cart') def show_cart(request): user = request.user cart = Cart.objects.filter(user=user) return render(request, 'app/addtocart.html', locals()) I am trying to learn django through a youtube tutorial, and am getting this error, what could be the issue? I deleted my migrations twice but still getting the same error. -
Wagtail: RichTextField data not showing on index page when using urls.py and views.py
I am trying to build a very basic home page with Django/Wagtail. The page model has a single text field, and the view creates a new session if the user is visiting the page for the first time. The Home Page loads fine as my root page and I can see the text content I have added via Wagtail admin in the body RichTextField. The problems start when I try to configure urls.py and views.py to to verify if there is already a session saved for the current user. The session logic works, but the RichText Field content disappears. I end up with two scenarios: If I run it as presented below, the code in views.py works, but the body content is not shown. If I comment the urls.py home_views.home line, I get the body content but the views.py code is bypassed. I am not looking for the best way of handling sessions. I am trying to learn how everything works and I feel like I am missing some basic concept to make this work. Models.py contains the following: class HomePage(Page): body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('body'), ] urls.py contains the following: from home import views as … -
How to mock a django settings config value inside __init__
I have this scenario: class MyClass: my_protocol: MyProtocol def __init__(self) -> None: if settings.EXAMPLE == "foo": self.my_protocol = Foo() elif settings.EXAMPLE == "bar": self.my_protocol = Bar() def my_method(self) -> Union[int, None]: [...] result = self.my_protocol.another_method() [...] I'm using a variable inside settings.py to choice which method to use. It's ok, my code works. But I need to write some tests. Something like this: @override_settings(EXAMPLE="foo") def test_my_procotol(): ... The value changed works only inside method (my_method). Inside the __init__ the value not changes. Does anyone have any ideas? -
How to redirect to pagination page in Django?
I have view: def questions(request,id): if request.method=='GET': if question.objects.findId(id) == None: raise Http404 ans=answer.objects.sortByTop(id) return render(request, 'question_page.html',{'page_obj':paginate(ans,request,2), 'answers':ans, 'que':question.objects.findId(id)} ) if request.method == 'POST': form = AnswerForm(data=request.POST) print(form.data) que = question.objects.findId(id) print(que) print(que.title) ans = answer( txt=form.data['anstxt'], authorId=Profile.objects.get(profile=request.user), questionId=que, id=answer.objects.getLastId()+1 ) ans.save() a=answer.objects.sortByTop(id) i=0 for c in a: if c==ans: break i=i+1 return redirect('questions', id=que.id)#how to redirect??? When user has asked question django must redirect him to page with answer. I use standart pagination object to implement pagination so pages are in GET parametes(?page=...) urls: urlpatterns = [ path('',listing, name='main'), path('login/', Login, name='login'), path('signup/',registration,name='signup'), path('hot/',hot,name='hots'), path('ask/',ask,name='ask'), path('question/<int:id>/', questions, name='questions'), path('tag/<slug:tg>/',tag_search,name='tag'), path('logout/',logout,name='logout'), path('edit/',settings,name='edit') ] question has dynamic url. How can I redirect user to page of answers after submitting? form template: <div class="yourans"><form class="ansfrom" method="POST" action="{%url 'questions' id=que.id%}?page={{page_obj.number}}"> {%csrf_token%} <div class="allf"><textarea name="anstxt" class="atxt" placeholder="answer" required maxlength="1000"></textarea></div> <div class="ansbut"> <input type="submit" value="Answer" class="goans"></div> </form></div> I tried this: path('question/<int:id>/(?P<page>\d+)/$', questions, name='questions'), But it's not good. And this: return redirect('questions', id=que.id,page=int(i/2)+i%2) But it doesn't work -
undefined when trying to get product
hello everyone i am working on this project and i am making ajax get request but my product foreign key is coming out as undefined, how do i access the name associated to that foreign key. you can check my code below what i want to do is to get the product name associated with that forign key but i keep getting undefined and the other field is working fine JS CODE $(document).ready( function(){ $.ajax({ type:'GET', url:"/order/getorder/", data:{category:$('#category').val() }, success: function(response){ for (var key in response.currentorder){ let temp = '' temp+="<tr><td>"+response.currentorder[key].order_id+"<td><tr>"; console.log(response.currentorder[key].product); $('#order-table').append(temp); } }, }) }) VIEW.PY def getorder(request): currentorder = PoductOrder.objects.all() return JsonResponse({"currentorder":list(currentorder.values())}) -
Python/Django. Difference between Decimal calculation local and server
We use Decimal number to store values. I have simple formula: price * quantity * percent / 100 def round_value(value): x = math.floor(value) if (value - x) < .50: return x else: return math.ceil(value) def calculate_reward(price, quantity, percent): return round_value(price * quantity * percent / 100*) So in my case i have values: calculate_reward(77, 2, 87) On local machine i have: 134 On server: 130 I dont have even a clue why such behavior on the server. Does anyone know? -
Django template doesn't render properly. Prints DTL tags as regular text
I'm in the middle of creating a base.html template for my very first Django project. Unfortunately, i've already encountered a problem. My DTL tags are visible in a browser for some reason, it gets printed out like a regular text. Here is my code (as you can see I didn't even start doing anything yet): <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Base</title> {% block head %} {% endblock %} </head> <body> {% block content %} <h1>Base</h1> {% endblock %} </body> </html> Here is what i get: How do a get rid of it?? Do i need some sort of extension for this?? Or where in the settings should I look for the problem? I have absolutely no clue. -
The photo uploaded by the user is not saved in the media directory
If I enter the image manually in the admin panel, it is correct, but if it is entered through the form, it is not saved in the media directory. views.py if request.method == "POST": ... photo_prof = request.FILES['photo_prof'] ... models.py class Profile(models.Model): ... photo_prof=models.ImageField(max_length=10000,upload_to='photo/%y/%m/%d/',blank=True) ... template: <form method="post" action="{% url 'profile_additional_info' %}" enctype="multipart/form-data"> ... <input name="photo_prof" type="file" class="custom-file-input"id="inputGroupFile04" aria-describedby="inputGroupFileAddon04"> ... </form> I put MEDIAROOT, MEDIAURL in settings and set urls.py file I found some similar questions on SO but none of them solved my problem. -
Is there a way to change the amount in two fields of different models with one form?
from django.db import models class Product(models.Model): name = models.CharField(max_length = 50) quantity = models.FloatField(default=0) def __str__(self): return self.name class Customer(models.Model): name = models.CharField(max_length=100) primary_contact = models.CharField(max_length=10) secondary_contact = models.CharField(max_length=10) address = models.TextField(blank=True) def __str__(self): return self.name class Issue(models.Model): date = models.DateTimeField(auto_now_add = True) customer = models.ForeignKey(Customer, on_delete = models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, ) quantity = models.PositiveIntegerField() kt = models.IntegerField() rate = models.FloatField() vat = models.IntegerField(default=15) @property def kt_21(self): return self.kt / 21 * self.quantity @property def vat_amt(self): return self.quantity * self.rate * self.vat/100 @property def total_amt(self): return self.quantity * self.rate + self.vat_amt def __str__(self): return str(self.customer) + " - "+ str(self.total_amt)+' SAR' I have these models now I what I want is that when I issue a product and enter some quantity in the Issue model the same amount of quantity should be deducted from the Product model's quantity field. -
Combine custom model fields in django forms
I hava a model view, which I'm accessing from django admin view. I added some custom fields to a form and then added this form to a ModelAdmin. The user will input specific values in those fields. Then I want to get the values from the custom fields to create a python dict. Example: # models.py class Style(models.Model): style_id = models.AutoField(primary_key=True) style_name = models.CharField(max_length=200, verbose_name=("Nome do Estilo")) style_desc = models.TextField(null=True) scales = models.JSONField(encoder=None, decoder=None) def __str__(self): return f'{self.style_id} - {str(self.style_name)}' class Meta: verbose_name = 'Estilo' # admin.py class StyleModelForm(forms.ModelForm): ca = forms.DecimalField() mg = forms.DecimalField() pH = forms.DecimalField() class Meta: model = Style fields = '__all__' class StyleAdmin(admin.ModelAdmin): form = StyleModelForm # list_display = ['style_name', 'style_desc', 'scales', 'ca', 'color'] fieldsets = ( ('Dados 1', { 'fields': ('style_name', 'style_desc', 'scales',), }), ('Section 1', { 'fields': (('ca', 'pH', 'mg',)), }), ) exclude = ['style_id'] I would like to be able to combine fields ca, mg and pH to a python dict and then use the result to save the object to my Model Style, which has a scale JsonField. I have tried to follow instructions from this post Pseudo-form in Django admin that generates a json object on save , it didn't … -
boto3 file uploading leaks anon inodes and causes 'Too many open files' error
I have python 3.8 script on ubuntu that uploads images to AWS S3 with consecutive calls storage.save(path, f) where storage is S3Boto3Storage(), path is s3 path and f is BytesIO containing image content After each call I see increasing amount of opened anon inodes related to my process: $ ls -l /proc/3036326/fd total 0 lrwx------ 1 ubuntu ubuntu 64 Apr 27 13:55 0 -> /dev/pts/2 lrwx------ 1 ubuntu ubuntu 64 Apr 27 13:55 1 -> /dev/pts/2 lrwx------ 1 ubuntu ubuntu 64 Apr 27 13:55 10 -> 'socket:[158453777]' lrwx------ 1 ubuntu ubuntu 64 Apr 27 13:55 11 -> 'socket:[158453778]' lrwx------ 1 ubuntu ubuntu 64 Apr 27 13:55 12 -> 'socket:[158453779]' lrwx------ 1 ubuntu ubuntu 64 Apr 27 13:55 13 -> 'socket:[158453789]' lrwx------ 1 ubuntu ubuntu 64 Apr 27 13:55 14 -> 'socket:[158453795]' lrwx------ 1 ubuntu ubuntu 64 Apr 27 13:55 15 -> 'socket:[158542709]' lrwx------ 1 ubuntu ubuntu 64 Apr 27 14:23 16 -> 'anon_inode:[eventpoll]' lrwx------ 1 ubuntu ubuntu 64 Apr 27 14:23 17 -> 'anon_inode:[eventpoll]' lrwx------ 1 ubuntu ubuntu 64 Apr 27 14:23 18 -> 'anon_inode:[eventpoll]' lrwx------ 1 ubuntu ubuntu 64 Apr 27 14:23 19 -> 'anon_inode:[eventpoll]' lrwx------ 1 ubuntu ubuntu 64 Apr 27 13:55 2 -> /dev/pts/2 lrwx------ 1 ubuntu … -
Docx Document is not generated python-docx
The bottom line is that there is a form in the html code that asks for what period records will be fetched from the database. And when you click the "Generate" button, a docx document should be generated. But for some reason it is not generated, the selection is successful, there are no errors. html <form action="" method="get" class="my-4 "> <input type="date" name="date_from" value="{{ date_from }}" id="date_from"> <input type="date" name="date_until" value="{{ date_until }}" id="date_until"> <input type="submit" value="Generate" class="btn btn-primary"> </form> views class DirectorOrdersReportView(TemplateView): template_name = 'director/orders_report_director.html' model = OrderStorage def get(self, request, *args, **kwargs): date_from = request.GET.get('date_from') date_until = request.GET.get('date_until') records = OrderStorage.objects.filter(created_at__range=[date_from, date_until]) return super().get(request, *args, **kwargs, records=records) def gen_report_(self): current_datetime = datetime.now() str_current_datetime = str(current_datetime) document = Document() docx_title = "report" + str_current_datetime + ".docx" document.add_paragraph() document.add_paragraph("%s" % date.today().strftime('%B %d, %Y')) document.add_paragraph('Orders report') qs2 = self.get().records() qs2count = qs2.count() + 1 table = document.add_table(rows=qs2count, cols=8) table.style = 'Table Grid' table.cell(0, 0).text = 'ID' table.cell(0, 1).text = 'User' table.cell(0, 2).text = 'Size' table.cell(0, 3).text = 'Status' for order in self.kwargs: qs2 = self.get().records() row = qs2.count() table.cell(row, 0).text = str(order.pk) table.cell(row, 1).text = str(order.user) table.cell(row, 2).text = str(order.size) table.cell(row, 3).text = str(order.status) document.add_page_break() f = BytesIO() document.save(f) length = … -
TransactionManagementError and IntegrityError in Django tests even if atomic context is used
I'm trying to handle an Integrity Error in the Django tests (using TestCase), and while it seems to work for almost all tests I have, only one fails. I overrode the save method on my model: def save(self, *args, **kwargs): self.clean() try: return super().save(*args, **kwargs) except IntegrityError as e: if len(e.args) >= 1: if "constraint_name_1" in str(e): raise ValidationError(_('Error message 1')) elif "constraint_name_2" in str(e): raise ValidationError(_('Error message 2')) raise e and I wrap the test with transaction.atomic context to handle the error but it still fails. -
How to track changes to user groups and permissions in Django
According to the requirements of information security, it is necessary to track changes in user groups and permissions in the Django admin panel! Using signals I catch creation and deletion of the user. How can I track changes in user fields, changes in his groups and permissions? from django.db.models.signals import post_save, post_delete from app.utils import write_message_to_logger user = get_user_model() @receiver(post_save, sender=user) def create_user(sender, instance, created, **kwargs): if created: write_message_to_logger('Created new user') @receiver(post_delete, sender=user) def delete_user(sender, instance, **kwargs): write_message_to_logger('User was deleted') I will be grateful for the answer Signal post_save on creation and change of the user has no information, necessary for me. The instance.get_group_permissions() method gives information about existing groups, not about those currently assigned. -
Can we use OpenCv to detect Nudes object in django
I'm building an educational website forum where users can upload videos. However, some of our users may upload nude content, which is against our terms of use. Therefore, we have decided to create a report feature where users can report a video that violates our rules. However, relying solely on the report feature is not intelligent, as we are expecting more clients. We need to use a system that can read user files before they are uploaded to our database. We want OpenCv to read user files, if there is any nude content, we want to return an error message to the user, and never allowed that content to be uploaded in database. If we can using use OpenCv to read image and Video, I think we can use it to detect a video content. But How can we do this using OpenCv? We are using pure html form for file upload: def create_video(request): if request.method == 'POST': video = request.FILES.get('video') if video: video_type = video.content_type.split('/')[0] if video_type != 'video': raise ValidationError('File is not a video') video_ext = video.name.split('.')[-1] if video_ext not in ['mp4', 'avi', 'mov']: raise ValidationError('Unsupported video format') video_clip = VideoFileClip(video.temporary_file_path()) duration = video_clip.duration video_clip.close() if duration > … -
How to add Kurdish language in Wagtail Localize?
I tried using Kurdish as a new language in wagtail , but it kept redirecting to "/en/ku" perhaps because the only locals accessible are BCP-47 language tags. Is there a way to add Kurdish as a new language in wagtail? i tried wagtail localize and simple translation -
Can someone explain why the Django button.theme_toggle does not work in Chrome? Edge is ok
enter image description here Why does this control not work? It works properly with Edge browser, not Chrome. -
MongoDB vs Postgresql Django online exam website
I want to create an online exam website using Django exam, will have questions and question can have types text, mcq or file submit I'll just create 3 models: Exam, Question and QuestionChoices now for answer, I've ExamAnswer and QuestionAnswer now for question answer, it'll have three types it can be file, text or choice so I created a model for each of them so now I've 5 models: ExamAnswer, QuestionAnswer, TextAnswer, MCQAnswer, FileAnswer QuestionAnswer is related to ExamAnswer and the question it's answering. The last three are related with OneToOne to the QuestionAnswer Is there a better approach? should I switch to nosql db like mongo or redis? If I did so, I might want to add some analytics like how many users choose a specific choice, will that be easy to query using nosql db? -
Setting cookie directly on response returns None in Django
I have written a RegisterView in Django like so: class RegisterView(View): def post(self, request): request_body = parse_request_body(request) email = request_body.get('email') fullname = request_body.get('fullname') password = request_body.get('password') user = self.register_user(email, fullname, password) csrf_token = get_token(request) response = JsonResponse({'user': user.serialize()}) response.set_cookie('csrftoken', csrf_token) return response This code works fine but when I try setting the cookie directly on JsonResponse, a ValueError is raised because the view returns None: class RegisterView(View): def post(self, request): request_body = parse_request_body(request) email = request_body.get('email') fullname = request_body.get('fullname') password = request_body.get('password') user = self.register_user(email, fullname, password) csrf_token = get_token(request) return JsonResponse({'user': user.serialize()}).set_cookie('csrftoken', csrf_token) Why is that? -
Filter on an element of an array will cast the right hand side to array
I am having a hard time with filtering on arrays elements using Django (with a PostgreSQL table) Suppose I have a model MyModel with a field my_array which contains, say, booleans (the type does not really matter) I want to check that the first element of my array is True. For me the natural way was to do MyModel.objects.filter(bool_array__0=True) however this generates the following SQL filter ... WHERE bool_array[1] = true::boolean[] Problem here is that django automatically casts the right hand side to boolean[] and ends up with comparing boolean to boolean[]. I have tried with the __in lookup, and putting [True] instead of True but doesn't work either. Thanks a lot in advance -
cannot import name 'parse_header' from 'django.http.multipartparser'
urlpatterns = [ path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name='example.html/')), ] [Errno 22] Invalid argument: 'C:\Users\Hp\Desktop\CRM-DJANGO\:\example.html' exact error is ='example.html' want to open the example.html in django -
Azure App Service Deployment Asyncio Issue
I am trying to deploy a Django app using an Azure App Service and am running into an issue. The app uses gunicorn for WSGI and is running in python 3.11. I know that asyncio is native to python in 3.11, but even when I have tried to uninstall or specify it in my requirements.txt file, I still get this error. When I deploy the app, I get the following error: File "/tmp/8db47123221a6e2/config/wsgi.py", line 11, in <module> import asyncio File "/tmp/8db47123221a6e2/antenv/lib/python3.11/site-packages/asyncio/__init__.py", line 21, in <module> from .base_events import * File "/tmp/8db47123221a6e2/antenv/lib/python3.11/site-packages/asyncio/base_events.py", line 296 future = tasks.async(future, loop=self) ^^^^^ SyntaxError: invalid syntax I am confused because I am not using asyncio anywhere, but it does seem to be installed as a dependency because it is in my venv/Lib/site-packages directory. Here is my requirements.txt file: django==4.2 djangorestframework==3.14.0 django-cors-headers==3.14.0 environs==9.5.0 django-debug-toolbar==4.0.0 psycopg2-binary==2.9.6 gunicorn==20.1.0 asgiref==3.6.0 whitenoise==6.4.0 And here is my wsgi.py file: import os import asyncio from django.core.wsgi import get_wsgi_application asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') application = get_wsgi_application() Here is my Procfile: web: python gunicorn_starter.py And the gunicorn_starter.py: import os import multiprocessing from subprocess import call workers = (multiprocessing.cpu_count() * 2) + 1 gunicorn_command = f"gunicorn --workers {workers} --bind 0.0.0.0:8000 config.wsgi" call(gunicorn_command.split(), env=os.environ.copy()) I have been … -
Not showing text in html with POST request
Im trying to take a text from a text box and print it on my html file, but it doesn't work. Here is my views.py from django.shortcuts import render from django.http import HttpResponse from .forms import InputForm # Create your views here. def home(request): form = InputForm() return render(request, 'index.html', {'form': form }) def post(request): form = InputForm(request.POST) if form.is_valid(): text = form.cleaned_data['post'] args = {'form': form, 'text': text} return render(request, 'index.html', args) Here is my index.html {% block content %} <h1>Write a sentence</h1> <form method="post" action=""> {{ form }} {% csrf_token %} <button type="submit", name="save">Generate</button> </form> <h2> {{ text }} </h2> {% endblock %} Im doing all stuff by tutorial and getting POST request in terminal, but unfortunately text doesn't appear