Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
admin panel django not showing chart
I implemented the chart in the admin panel and I want to show the number of sales of each product in this chart. I display the number of sales on the y axis and the product name on the x axis. The problem I have is that the number of sales for the same product is not displayed (for example, the guitar maker has sold three but shows two, or jazz has sold 5 but has shown 3 so far). The number of sales does not match the name of that product. The photo is the attached diagram. [![admin panel photo][1]][1] [1]: https://i.stack.imgur.com/BpJUJ.jpg my template : {% extends "admin/change_list.html" %} {% load static %} {% block extrahead %} <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script> <script> var options = { responsive: true, maintainAspectRatio: true, legend: { position: 'left' }, title: { display: true }, animation: { animateScale: true, animateRotate: true } }; window.onload = function () { var ctx = document.getElementById("gender-chart"); {% regroup cl.queryset|dictsort:"sell" by sell as sell_list %} {% regroup cl.queryset|dictsort:"name" by name as name_list %} var lineChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for category in name_list %}'{{ category.grouper }}',{% endfor %}], datasets: [{ label: '# … -
Django set two fields with unique values in a model
Here is my problem, I want to create an school administration site so I need to register the student data. The students have two fields that need to be unique, for example:## Student A: 'enrollment_id: 123', 'other_field: ABC' Student B: 'enrollment_id: 234', 'other_field: CDE' ## Those two fields can't have the same values. If I already have an student with ABC in the 'other_field' and I want to register an student with the same value, the app shouldn't allow that. I'm using Django 3.1.1 and so far I have already tried UniqueTogether and UniqueConstraint(fields = ['enrollment_id', 'other_field'], name='some_name') in my Student Model and as PK I have the enrollment_id. But that doesn't work. I can still register the same value in "other_field" if "enrollment_id" is different. I need to mention that I'm using SQLITE to test the app before migrating the DB to another Engine. Also I'm using CBV to create the forms. Thank you very much, any help is appreciated! EDIT: Yes, I've already made the migrations -
Example of clean architecture with Python
I'm trying to create a web application based in Python. Now I'm at the point of defining the architecture, and I've found a lot of literature about Clean Architectures, Onion Architecture, Hexagonal Architecture... But it would be really helpful a good example of a real web project that follows these kind of designs. Do any of you know about a good public example in order to see a real implementation? Thanks in advance. -
What is the point of specifying Integer Choices in django models?
The official django docs give the following example for specifying integer choices for a column: class Card(models.Model): class Suit(models.IntegerChoices): DIAMOND = 1 SPADE = 2 HEART = 3 CLUB = 4 suit = models.IntegerField(choices=Suit.choices) However, I find that if I open 'python manage.py shell' and simply do something like: c = Card() c.suit = 5 c.save() it saves the card with no problems, even though 5 isn't included in my choices. so what is the point of specifying my integer choices? -
PyCharm Pro dont let me start Django project, yesterday everything was fine
I am trying to start a Django project, but pycharm wont let me do it. Yesterday everything was fine. I have already reinstalled pip3 and python3. What should i do? Here are the screenshots: image 1 image 2 image 3 image 4 The following command was executed: pip install Django The exit code: 2 The error output of the command: Usage: /home/nikita/PycharmProjects/djangoProject4/venv/bin/python -m pip install [options] <requirement specifier> [package-index-options] ... /home/nikita/PycharmProjects/djangoProject4/venv/bin/python -m pip install [options] -r <requirements file> [package-index-options] ... /home/nikita/PycharmProjects/djangoProject4/venv/bin/python -m pip install [options] [-e] <vcs project url> ... /home/nikita/PycharmProjects/djangoProject4/venv/bin/python -m pip install [options] [-e] <local project path> ... /home/nikita/PycharmProjects/djangoProject4/venv/bin/python -m pip install [options] <archive url/path> ... no such option: --build-dir Non-zero exit code (2) -
Obtaining to fetch data from the form using GET Method
I want to fetch a list of data using ajax function which is called in views.py for the ajax function using GET Method in views.py. But my submit button is not functioning nor it is fetching any data and displaying the result. Any help will be appreciated. My codes are: views.py def home(request): majors = Major.objects.filter(percentages__isnull=False).distinct().order_by("pk") if request.is_ajax() and request.method == 'POST': form = request.GET.get('major1') form = request.GET.get('major2') form = request.GET.get('major3') form = request.GET.get('major4') form = request.GET.get('major5') line_chart = pygal.Line(width=1500) line_chart.title = 'Budget Estimation' context = { "chart": line_chart.render_data_uri(), 'majors': majors } return render(request, "website/index.html" , context ) -
Return two field values from one SerializerMethodField
I have following serializer: class SampleSerializer(serializers.ModelSerializer): status = serializers.SerializerMethodField() label = serializers.SerializerMethodField() field3 = serializers.SerializerMethodField() field4 = serializers.SerializerMethodField() field5 = serializers.SerializerMethodField() class Meta: model = Sample fields = ( 'status', 'label', 'field3', 'field4, 'field5' ) The problem is, the conditions used to obtain the first two fields are same. So I don't want to run the same codes again in two serializer method fields. I want to get both of the values from the same serializer method. How can I efficeintly get values of both of the fields from only one serializer method field? -
save multiple check box values insert update and delete in django
save multiple check box values insert update and delete in Django I am trying to update the multiple check box values in django -
RawPostException: You cannot access body after reading from request's data stream
I am trying to get the data from ajax to django post view, I create the cart with items now I need to get the cart to backend My js code is: $.ajax({ url: url, type: "POST", data: JSON.stringify({'order_data':order}), contentType: 'application/json; charset=UTF-8', success: function (data) { if (data['success']) { alert(data['success']); } }, error: function (request, error, status) { if (request) { } } }); My View code that I am using in Django view: if request.method == "POST": data = json.loads(request.body) cart = data['order_data'] Then I am getting that error RawPostException: You cannot access body after reading from request's data stream your suggestions will be preferred -
django template variable in <a>
How can i add a django template variable to href attribute of tag?something like this <a href="{{meeting.meeting.url}}">{{meeting.meeting_url}}</a> meeting.url stores a link to another website such as google etc and it is saved in database Thanks in advance -
PayPal integration in Django web applications
I'm working on a project in which I'm using Python(3.9) & Django(3.1.2) and I need to implement the Paypal payment method in this project. Can somebody help me with the source code to integrate PayPal? -
Django ORM can't get value from specific field
My old project uses django 2.1.7, drf 3.9.2, psycopg2==2.7.7, and postgresql in AWS RDS. I found a strange thing that orm couldn't get some values from database. Actually, there were real values in my database. ORM works well in other values in other columns, but some in specific value, it weren't work. the field looks like this: - models.CharField(max_length=5000, null=True) the value in DB looks like: character varying(5000) in postgres 0_ 46 46 .... 52 53 50 43 41 54 52 / the result in my server or shell is just None. other values work well... -
Understanfding the `initial` argument of the form in Django (Form.initial)
Here are my functions in views.py. But I am interested in last, edit_entry function's behavior: class AddForm(forms.Form): title = forms.CharField(label="Enter the title", max_length=100) content = forms.CharField(widget=forms.Textarea, label="Enter your text") def entry(request, title): if title not in util.list_entries(): return render(request, "encyclopedia/error.html", { "error": "Page Not Found", "query": title }) else: return render(request, "encyclopedia/entry.html", { "entry": markdown2.markdown(util.get_entry(title)), "title": title }) def add_entry(request): if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] if util.get_entry(title) is None: util.save_entry(title, content) return redirect('entry', title) else: return render(request, "encyclopedia/add_entry.html", { "form": AddForm(), "title": title }) return render(request, "encyclopedia/add_entry.html", { "form": AddForm() }) def edit_entry(request, title): content = util.get_entry(title) if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] util.save_entry(title, content) return redirect('entry', title) return render(request, "encyclopedia/edit_entry.html", { "form": AddForm(initial={'title': title, 'content': content}), "title": title, "content": content }) Even if I delete the initial argument of my AddForm, it gives the same result, like this: "form": AddForm({'title': title, 'content': content}). It shows me the initial content, I can add some words and save it, and it works. Then why we need this initial if we can do it without it? Just in case, here is my edit_entry.html … -
Dynamically check value and display alarm popover
I want to validate user input so he only provides number from a certaint range with 0,5 step. But I want my website to do it every time user swaps to another input form, not after he sends the data to my view. Can you give a hint of how should it be done? I don't know Javascript but I know there is onfocusout DOM event. Is it correct approach to use it, check whether or not value is valid and display alarm based on that? -
How can we upload multiple files and store address of file as json using Django and Javascript
I want to know how can we upload file dynamically( meaning there will be one filefield on frontend and one add button) if user will click on add button new file field will be generated there using javascript. I want to upload file(without refreshing page) and get the address of that image(to store that in jason format). So by this way I will be able to upload multiple files. I am using Django, jquery and Javascript, Django-rest-framework. -
How to Encrypt the data of djanog.ckeditor Richtextfield?
Hi There actually i am creating a notes taking app using django. For better ux i have used django ckeditor for providing a good editor to write beautiful and informative notes. I have used django.ckeditor richtextfield for this purpose. Now i want to encrypt the data of this text field so it can be stored safefly. I have used djanog-cryptography package and used encrypt method. Problem -: When i am retreiving the note_contents in my template its showing nothing. I am attaching my views and models and settings.py views.py from django.shortcuts import render,redirect,get_object_or_404 from django.http import HttpResponse from django.contrib.auth.decorators import login_required from . models import UserCreatedNote from . forms import AddNoteForm # Create your views here. @login_required def notes(request): if request.method=='POST': form = AddNoteForm(request.POST) if form.is_valid(): form_data = form.save(commit=False) form_data.user = request.user form_data.save() notes = UserCreatedNote.objects.filter(user=request.user) form = AddNoteForm() context = {'notes': notes,'add_note_form':form} return render(request,'usernotes.html',context) notes = UserCreatedNote.objects.filter(user=request.user) form = AddNoteForm() context = {'notes': notes,'add_note_form':form} return render(request,'usernotes.html',context) @login_required def edit(request,id): note = get_object_or_404(UserCreatedNote, pk=id) if request.method == 'POST': form = AddNoteForm(request.POST, instance=note) if form.is_valid(): form_data = form.save(commit=False) form_data.user = request.user print(form_data.id) form_data.save() form = AddNoteForm(instance=note) context={'note':note,'u_form':form} return render(request,'edit_note.html',context) form = AddNoteForm(instance=note) context={'note':note,'u_form':form} return render(request,'edit_note.html',context) @login_required def delete(request,id): note = UserCreatedNote(id=id,user=request.user) … -
How to deploy Django app to heroku for production
I have deployed Django apps to heroku before but I am having a bit of trouble understanding why one of my applications is not being deployed. My Procfile has the following web worker web: gunicorn project_name.wsgi I have my requirements.txt and in my root directory a staticfiles directory with an empty txt file to collect all static files when running heroku local. Everything works as expected but when actually trying to start the production server after pushing to heroku master my app does not work. I have in my ALLOWED_HOST the url for my local server and production. also, I have the following settings... MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] STATIC_URL = '/static/' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' I am using whitenoise in order to be able to serve static files in production directly using gunicorn. -
inner function raise in Django rest API
How can I catch a 4XX series raise in inner function of an API in Django rest framework? from rest_framework.exceptions import ValidationError class DummyView(APIView): def get(self, request, id): if id==something: dummy_function_1(id) else: dummy_function_2(id) return Response() def dummy_function_1(): try: validate_1(id) except: raise ValidationError() #do something with id Return id When I send a HTTP GET request, I receive a 5XX series error if exception occurs. I want to get 400 Bad Request error in response. -
Ensure unique objects for get_or_create without unique, unique_together in django
Is it possible to use get_or_create for an object where the kwargs are not defined as unique/unique_together and still achieve atomicity in the face of concurrency? The django documentation explicitly states that get_or_create ensures atomicity when the database ensures atomicity. I am kind of in a situation where; forcing uniqueness using unique, unique_together is out of the question. I need to use the get_or_create. What options do I have. I have come across a duplicate record LUCKILY during testing and I need to find a fix. I am using postgres, if that can be helpful. -
Is there anyway to create a view like in the Django admin site?
i'm now making a job portal website. When an applicant registered to a certain job posted by a certain company, the company can see the applicants and update their status such as accepted or rejected. Now, i'm currently is dealing on how to view the status in the applicant site. Do you guys have any idea on how to do that? I will insert the code for the company who updates the status, but i have no clue at all on how to view those status in the applicant site. I'm a beginner so please help me guys.. models.py class StatusForm(forms.ModelForm): applicant = forms.ModelChoiceField( queryset=Applicants.objects.all(), widget=forms.Select(attrs={'class': 'form-control input-sm'}), required=False ) class Meta: model = ApplicantsJobMap fields = ['applicant','status', 'feedback'] views.py class job_applicants(ListView): model = ApplicantsJobMap template_name = "jobs/job_applicant.html" context_object_name = "assign_job" paginate_by = 1 def dispatch(self, request, *args, **kwargs): return super().dispatch(self.request, *args, **kwargs) def get_queryset(self): return ApplicantsJobMap.objects.filter(job_id=self.kwargs["id"]).order_by("id") def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["job"] = Job.objects.get(id=self.kwargs["id"]) return context def update(request, applicant_id): applicants = ApplicantsJobMap.objects.get(id=applicant_id) #obj = get_object_or_404(ApplicantsJobMap, id=pk) formset = StatusForm(instance=applicants) if request.method == 'POST': formset = StatusForm(request.POST, instance=applicants) if formset.is_valid(): formset = formset.save(commit=False) formset.save() messages.success(request, 'Applicant status update successful') return redirect('home') else: formset = StatusForm(instance=applicants) context = {'formset': formset} … -
Can I change the verbose_name for a field inherited from the parent class in Django?
There is a parent class class Category(models.Model) category = models.CharField('category', max_length=255, blank=True, help_text='Specified category') Can I change the verbose_name for the category field in the descendant class? And also help_text? Something like this: class TableCategory(Category) class Meta: verbose_name__category = 'table category' help_text__category = 'Specified table category' class ChairCategory(Category) class Meta: verbose_name__category = 'chair category' help_text__category = 'Specified chair category' -
How do I package the templates from react frontend into a Django app?
I'm trying to package a Django+react app into a reusable app to be installed into another Django project. I followed the tutorial here to package it but after installing in a new project, I get a TemplateDoesNotExist error. I tried moving the build files out of the react app to a folder named templates inside the Django app and recursively including it in the Manifest. But when I install the app elsewhere, it keeps throwing a TemplateDoesNotExist error. Here's my directory structure: ├── app ├── migrations ├── static │ ├── css │ ├── js │ └── media ├── templates └── tests ├── ui ├── public ├── src Here's my MANIFEST.in: include LICENSE include README.rst recursive-include ui * recursive-include app/templates * recursive-include app/static * I've added the app in the new project's INSTALLED_APPS and ran migrations. I've also edited the urls in the new project's urls.py to include: path('app/', include('app.urls')), path('', TemplateView.as_view(template_name='index.html')) But when I run the server and try to send a GET request to any APIs within the installed app, I get a TemplateDoesNotExist with the following traceback. Internal Server Error: /app/ Traceback (most recent call last): File "/home/test_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/test_env/lib/python3.8/site-packages/django/core/handlers/base.py", line … -
ckeditor outside admin panel - django 3.1
I'm trying to use CKEditor based on instructions in Django CKEditor — Django CKEditor 5.3.1 documentation. it works just fine in the admin panel. But outside the admin panel, I want to add it to a message section. settings.py: INSTALLED_APPS = [ ... 'ckeditor_uploader', 'ckeditor', ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'cms/static') ] # MEDIA Folder Settings MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # CKEditor path CKEDITOR_UPLOAD_PATH = "uploads/" AWS_QUERYSTRING_AUTH = False CKEDITOR_ALLOW_NONIMAGE_FILES = False CKEDITOR_IMAGE_BACKEND = "pillow" urls.py: url(r'^ckeditor/', include('ckeditor_uploader.urls')), base_site.html: {% extends 'admin/base_site.html' %} {% load static %} {% block extrahead %} <script>window.CKEDITOR_BASEPATH = '/static/ckeditor/ckeditor/';</script> {{ block.super }} {% endblock %} To use it outside the admin panel I added the following configs. models.py: from ckeditor.fields import RichTextField class Contact(models.Model): message = RichTextField(blank=True) in base.html: {% load static %} <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.3/styles/default.min.css"> {% block content %} {% endblock %} <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.3/highlight.min.js"></script> <script>hljs.initHighlightingOnLoad();</script> <script src="//cdn.ckeditor.com/4.15.1/basic/ckeditor.js"></script> In a html file(contacts.html): {% load static %} <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script> <div class="col-md-8" > <h3 class="mt-3"> New Message </h3> <hr> <form action="{% url 'contact' %}" method="POST"> … -
Django Channels with NGINX and SSL
I have a django channels Chat app hosted using Nginx, Gunicorn and Daphne. After adding SSL from Cloudflare the sockets are unable to connect and giving error 502 in the browser console. My nginx/sites-available/my-site file is as follows: and my daphne.service file is as follows: And Upon checking nginx error logs i get the following: Everything was working fine before SSL but as soon as I used SSL from cloudflare. The connections stopped. After checking from multiple forums and youtube videos, I am still unable to run websockets with active SSL. Any help is appreciated. Thanks -
Ensure that there are no more than 0 digits before the decimal point
When I fill the bathroom field in my model with a value like 1.1, 2.5 anything with a digit before decimal it shows an error that no more than 0 digits before decimal point. If I give a value like .2, .3 then Django does not show any error. Same problem with the lot field. class listing(models.Model): realtor = models.ForeignKey(Realtor,on_delete=models.DO_NOTHING) title = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=100) state = models.CharField(max_length=100) state = models.CharField(max_length=20) description = models.TextField(blank=True) price = models.IntegerField() bedrooms = models.IntegerField() bathrooms = models.DecimalField(max_digits=2, decimal_places=2) garage = models.IntegerField(default=0) sqft = models.IntegerField() lot_size = models.DecimalField(max_digits=2, decimal_places=2) photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/') photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank = True) photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank = True) photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank = True) photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank = True) photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank = True) photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank = True) is_published = models.BooleanField(default= True) list_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return f'self.date'