Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django return variable back to user
I'm trying to add a tool to my site that hashes a serial number, and as such I don't require a model for this particular part of the site. What I wanted to do is use if statements in the template to remove the form fields and submit button and display the hash on the same page, however, I can't figure out how to get my result back to the template. The form I have created is the most basic with just two fields. here is my view: def voice_search_view(request): form = VoiceSearchForm() if request.method == 'POST': form = VoiceSearchForm(request.POST) if form.is_valid(): hw_number = form.cleaned_data['hw_number'] ca_serial = form.cleaned_data['ca_serial'] if len(ca_serial) == 16: prehash = hw_number + ca_serial[5:-1] + 'cc_voice' territory = 'DE' elif len(ca_serial) == 11: prehash = hw_number + ca_serial[:-1] + 'cc_voice' territory = 'UKIT' print(hw_number) print(ca_serial) print(prehash) sha_sig = hashlib.sha256(prehash.encode()).hexdigest() print(sha_sig) return redirect('/voice_search/') return render(request, 'voice_search.html', {'form': form}) how can I return the sha_sig back to the user, in an ideal world, I would just add it to the context, but that doesn't seem to be possible. Bearing in mind that I am not even using any css for this, it's a very quick temporary tool. What would … -
Enable subsite on Apache2 with Django
so I have django installed as my main directory django.conf (in Apache2): djanAlias /robots.txt /home/django/NAME/static/robots.txt Alias /favicon.ico /home/django/NAME/static/favicon.ico Alias /media/ /home/django/NAME/media/ Alias /static/ /home/django/NAME/static/ <Directory /home/django/NAME/static> Require all granted </Directory> <Directory /home/django/NAME/media> Require all granted </Directory> WSGIScriptAlias / /home/django/NAME/NAME/wsgi.py WSGIPythonHome /home/django/NAME/venv WSGIPythonPath /home/django/NAME <Directory /home/django/NAME/NAME> <Files wsgi.py> Require all granted </Files> </Directory> Now I want to enable roundcube as mail.NAME.net this is my conf: <VirtualHost *:80> ServerName mail.NAME.net ServerAdmin admin@NAME.net DocumentRoot /var/www/html/roundcube ErrorLog ${APACHE_LOG_DIR}/roundcube_error.log CustomLog ${APACHE_LOG_DIR}/roundcube_access.log combined <Directory /var/www/html/roundcube> Options -Indexes AllowOverride All Order allow,deny allow from all </Directory> RewriteEngine on RewriteCond %{SERVER_NAME} =mail.keyinator.net RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> When disabling Django everything works fine. When enabling it I get a 400 Bad Request error on mail.keyinator.net So my question is: How can I make my subsite mail.keyinator.net available whilst using django? -
How do I display a queryset based on a category linked to a slug that is requested?
I am trying to display querysets linked to a certain category, based on the webpage slug requested. I am in school and trying to learn the Django framework. Here is the view that I have tried: class ProductCategoryListView(ListView): template_name = 'products/product_list.html' def get_queryset(request, *args, **kwargs): if Product.category == ProductCategory.title: instance = ProductCategory.objects.get(title=instance) post = Product.objects.filter(category=instance) return post And here are my models: class ProductCategory(models.Model): title = models.CharField(max_length=200) slug = models.SlugField() parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.PROTECT) class Product(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(ProductCategory, null=True, blank=True, on_delete=models.CASCADE) slug = models.SlugField(blank=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=6) image = models.ImageField(upload_to='products/', null=True, blank=True) This view loaded the webpage, but did not render any queries. -
Issues when define a Django Foreign Key from CharField DataType
i'm new in Django and I am using it for create a small APIrest, the situation is that when defining the application models I got this class Localities(models.Model): id = models.BigAutoField(primary_key=True) field_id = models.CharField(unique=True, max_length=50,db_column='field_id') class Meta: managed = False db_table = 'localities' class Stratigraphy(models.Model): id = models.BigAutoField(primary_key=True) locality = models.ForeignKey(Localities, models.DO_NOTHING, blank=True, null=True, related_name='locality_id') class Meta: managed = False db_table = 'stratigraphy' The model Stratigraphy is related with the model Localities to the chardfield field_id when creating the serializer to create the json with the data i got this class BedSerializer(ModelSerializer): class Meta: model = Stratigraphy fields = '__all__' depth = 1 when I try the api with postman it shows me the following enter image description here but if I remove the depth attribute it shows me the following. class BedSerializer(ModelSerializer): class Meta: model = Stratigraphy fields = ('id','locality') enter image description here What am I doing wrong? -
In Django, how do I return a generated dynamically named document as a download?
I have created a page that takes user input via form fields and then takes that data and generates a document from the information. It saves it to a specified directory and uses form data to create the file name. I am trying to then have it redirect to prompt a download of that file as well. The function inside the page view that indicates the directory and creates the filename is 'makefileandpath()'. I then create a variable 'docname' and call the function. It works perfectly. My problem is then being able to make this variable work with returning the document as a download. I've tried to create different functions internally to handle this as well as tried to create another view and use it as an endpoint (all which can be seen below), but it won't allow me to call the variable name and the document could be called anything. I'm not sure how to solve this problem and I have been at this for almost a week now. Here is the code for my view: views.py import os from django.shortcuts import render from django.conf import settings from django.http import HttpResponse, Http404, FileResponse from docx import Document import mimetypes … -
Concurency celery django bulk create or update
I have a competition problem with django, I have a celery task that updates the number of users in a table. Since there are a lot of lines to update, I use a bulk update, and to avoid creating unnecessary lines, I use a bulk create. all_statistic_user = StatisticsCountriesUser.objects.filter(user__in=all_branch_user,countries=user.country) if all_statistic_user: all_statistic_user.update(total_users=F('total_users') +1) all_statistic_user = StatisticsCountriesUser.objects.exclude(user__in=all_branch_user,countries=user.country) if all_statistic_user: all_statistic_user = [StatisticsCountriesUser(user_id=user.id,countries=user.country) for user in all_statistic_user ] StatisticsCountriesUser.objects.bulk_create(all_statistic_user) else: all_statistic_user = [StatisticsCountriesUser(user_id=user.id, countries=user.country) for user in all_branch_user] StatisticsCountriesUser.objects.bulk_create(all_statistic_user) The problem is that if the task is executed asynchronously, if the tasks are executed at the same time the first task creates the user list, then the second task also retrieves the user list, the first creates or updates the users, but the second task the list no longer has the right information to update. the solution I thought was to put the tasks in a synchronous list and not asynchronously is this possible? Thank you in advance -
How to make whole row unique in Django
So I have a User model and a Community model. Now in order to check if user has joined a commity I have a UserJoinedCommunity model. It has user and community field. Like so: class UserJoinedCommunity(models.Model): """DB Model for users joined communities""" user = models.ForeignKey(User, on_delete=models.CASCADE) community = models.ForeignKey(Community, on_delete=models.CASCADE) def __str__(self): return f"{self.user.username}|{self.community.name}" So what I want is to make a whole row unique so user can't "join community multiple times". So if users id is 3 and he joins community with id 5 it will created a record ex.{user: 3, community: 5}. I want that to be unique so it can't be created again. -
Error: IntegerField should be set to int, not float
I am relatively new to all of this but I have created an IntegerField(). After some time, I noticed that I need a FloatField() for that. However, when I change the IntegerField() to FloatField(), I get the Error: "IntegerField should be set to int, not float". I try to sum up the number of trees (=no_trees) for every round with: self.player.cumulative_donated_trees = sum([p.no_trees for p in self.player.in_all_rounds()]) When I leave the no_trees field as an IntegerField() and type in something like 0.9, I obviously get 0 in return. But I need to get 0.9. self.player.cumulative_donated_trees = float(self.player.cumulative_donated_trees) is giving me the same Error message btw. thanks in advance! -
Save polygon or line to database django/mapbox
I would like to save the drawn polygon in the code below to the postgis database : Assume that mapbox is set correctly and that the polygon drawing and download works (i haven't put everything in the code to focus on the problem at hand) <script type="text/javascript"> map.addControl(draw); map.on('draw.create', updateArea); map.on('draw.delete', updateArea); map.on('draw.update', updateArea); function updateArea(e) { var data = draw.getAll(); var answer = document.getElementById('calculated-area'); if (data.features.length > 0) { var area = turf.area(data); // restrict to area to 2 decimal points var rounded_area = Math.round(area*100)/100; answer.innerHTML = '<p><strong>' + rounded_area + '</strong></p><p>square meters</p>'; var convertedData = 'text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(data)); document.getElementById('export').setAttribute('href', 'data:' + convertedData); document.getElementById('export').setAttribute('download','data.geojson'); } else { answer.innerHTML = ''; if (e.type !== 'draw.delete') alert("Use the draw tools to draw a polygon!"); } } -
django + celery: disable prefetch for one worker, Is there a bug?
I have a Django project with celery Due to RAM limitations I can only run two worker processes. I have a mix of 'slow' and 'fast' tasks. Fast tasks shall be executed ASAP. There can be many fast tasks in a short time frame (0.1s - 3s), so ideally both CPUs should handle them. Slow tasks might run for a few minutes but the result can be delayed. Slow tasks occur less often, but it can happen that 2 or 3 are queued up at the same time. My idea was to have one: 1 celery worker W1 with concurrency 1, that handles only fast tasks 1 celery worker W2 with concurrency 1 that can handle fast and slow tasks. celery has by default a task prefetch multiplier ( https://docs.celeryproject.org/en/latest/userguide/configuration.html#worker-prefetch-multiplier ) of 4, which means that 4 fast tasks could be queued behind a slow task and could be delayed by several minutes. Thus I'd like to disable prefetch for worker W2. The doc states: To disable prefetching, set worker_prefetch_multiplier to 1. Changing that setting to 0 will allow the worker to keep consuming as many messages as it wants. However what I observe is, that with a prefetch_multiplier of … -
Change Sort Grouping For Null Values
When using the sorting feature in the Django Rest Framework, you are given the ability to sort by a particular field, ascending and descending. This sorting groups null values first and then alphanumeric values secondly. (and understandably so because None is less than "a") But is there any way that we can reverse this order to where all of our alphanumeric values are sorted and then grouped after that are all of the null values? Currently when sorting, this is the order of the queryset. First Names: None None Abby Ben But the desired behavior is as follows. First Names: Abby Ben None None Note: I'm not sure if the solution would be in DRF, Django, or simply in the Python language itself. Any would do. -
How do I take input as String and save as Binary in Django using Django REST Framework?
Here is my model: class Example(models.Model): file = S3PrivateFileField() text = models.TextField(null=True, blank=True) binary = models.BinaryField(null=True, blank=True) and here is the serializer: class ExampleSerializer(ModelSerializer): class Meta: model = Example fields = ['file', 'text', 'binary'] First of all, in the Browsable API, I can see the file and text fields but not the binary fields. How do I see that field? Secondly, the input data type for the binary field is string and I would like to save it as binary data in the database. How can I get it to work? -
How do I add an external Javascript library to Django?
I would like to add a Javascript library to be used by my template files in Django (which is snap.svg). Where should I include the library in the project structure, and how do I make it usable in my template HTML file? Regards, -
I got the permission error at admin login
i am new at django.. .I try to create superuser in django . i did all step and they show me in terminal as i created superuser successfully. but when i go to server its show permission error . i re install django without cache. but still same problem coming. first they show template not find then i created one file loging.html. but again they show permission error.. this code from admin.py from django.contrib import admin from .models import Destinations admin.site.register(Destinations) PermissionError: [Errno 13] Permission denied: 'C:\Users\abc\projects\amar\templates\admin\login.html' -
Django + postgreSQL set up
This is my first time deploying a django project. I am following this (https://jee-appy.blogspot.com/2017/01/deply-django-with-nginx.html) as an outline. Everything is good up section 5. where I configure the database. This is what I have currently. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django_db', 'USER': 'db_user', 'PASSWORD': '******', 'HOST': 'localhost', 'PORT': '', } } But this is an existing project and I also have the below in my settings.py and I think they are conflicting since I am not seeing any content populating in my project. What am I doing wrong? STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' CRISPY_TEMPLATE_PACK = 'bootstrap4' LOGIN_REDIRECT_URL = 'login' LOGIN_REDIRECT_URL = 'music:index' LOGIN_URL = 'login' -
I am having problem in setting primary key for a list view
I am getting the error:- Reverse for 'grievant_complaint_list' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['grievant_complaint_list/(?P[0-9]+)/$'] I am trying to provide a list of complaints posted by a particular user, based on the user logged in but having a problem in providing the primarykey views.py @method_decorator([login_required, grievant_required], name='dispatch') class GrievantComplaintListView(ListView): login_url = '/login/' model = Complaint def get_queryset(self): grievant = Grievant.objects.get(student=self.request.user) return Complaint.objects.filter(grievant=grievant) @method_decorator([login_required, grievant_required], name='dispatch') class CreateComplaintView(CreateView): login_url = '/login/' redirect_field_name = 'complaint_detail.html' form_class = ComplaintForm model = Complaint def set_grievant(self): form.save(commit=False) person = Grievant.objects.get(Registeration=self.request.user) Complaint.grievant = person form.save() class ComplaintDetailView(LoginRequiredMixin,DetailView): login_url = '/login/' model = Complaint models.py class Grievant(models.Model): student = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) Registeration = models.IntegerField(default=0000) Room = models.CharField(max_length=50) Hostel = models.CharField(max_length=100) def __str__(self): return self.Registeration` class Complaint(models.Model): grievant = models.ForeignKey('grievance_app.Grievant',on_delete=models.CASCADE,related_name='complaintee',primary_key=True) department = models.ForeignKey('grievance_app.Department',on_delete=models.CASCADE) text = models.TextField() heading = models.CharField(max_length=200,blank=False,null=False,default='Problem') media = models.ImageField(upload_to='media') created_date = models.DateTimeField(default=timezone.now()) status_choices = [('D','Done'),('P','Pending'),('N','Not Accepted')] status = models.CharField(choices=status_choices,max_length=1,default='N') class Meta(): verbose_name_plural = 'Complaints' def change_status(self,choice): self.status = choice self.save() def __str__(self): return self.heading def get_absolute_url(self): return reverse("complaint_detail",kwargs={'pk':self.pk}) forms.py class ComplaintForm(forms.ModelForm): class Meta(): model = Complaint fields = ('department','heading','text','media') urls.py path('student_view/',views.StudentView.as_view(),name='student_view'), path('grievant_complaint_list/<int:pk>/',views.GrievantComplaintListView.as_view(),name='grievant_complaint_list'), path('complaint/new/',views.CreateComplaintView.as_view(),name='create_complaint'), path('complaint_detail/<int:pk>/',views.ComplaintDetailView.as_view(),name='complaint_detail') student_view.html {% extends 'base.html' %} {% block title %} StudentView {% endblock %} {% block body_block %} <h1>You … -
Django, form not rendering in the template
Form not rendering in template. There is NO model for this view, and i know that, this is a quick tool to hash a serial number. As a result, I am using form.Forms, not ModelForms. So instead of going through the rigmerole of creating a form from scratch, and as I'm adding this to my current site, using a form made sense, but I can't get it to render, it's real simple with two fields and a submit button. For some reason the form fields are not displaying, but the submit button is. Form class VoiceSearchForm(forms.Form): hw_number = forms.CharField(max_length=6) ca_serial = forms.CharField(max_length=16) view def voice_search_view(request): form = VoiceSearchForm(request.POST) if request.method == 'POST': form = VoiceSearchForm() if form.is_valid(): hw_number = form.cleaned_data['hw_number'] ca_serial = form.cleaned_data['ca_serial'] # Do stuff with the data collected. return render(request, 'voice_search.html', {}) template <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Voice Search</title> </head> <body> <h1>Hashing tool</h1> <form action="." class="voice_search"method="POST"> {{ form.as_p }} {% csrf_token %} <input type="submit" class="btn" value="Submit"> </form> </body> </html> I have followed the docs to get this far, but I must have copied something wrong and can't find anything on google for this, so I suspect on this incredibly rare occasion, this is the … -
Which orm for a python application
I have a python cli application that runs periodically and collects data from api. Data should be stored on database, then processed and results stored again on database. In a furhter step, data will be used to provide web-api (consumed by webpage or mobile app). To make web-api, I think I use Django. To make cli, I think to don't use any fullstack framework, but I need just an orm framework. I search about python orm, and I found two possible solutions, django-orm and sqlalchemy. Based on my research, I read that django-orm is not the best solution for complex query and scenario. So I'm thinking the sqlalchemy could be the best approach. Usually I'm developing with c# and I use repository pattern. Sqlalchemy provides Session (that for my understood is a similar approach). Could be Sqlalchemy the best choice? If yes, I have to use sqlalchemy core and orm? What can I use for web-api? Is it possible to use easly sqlalchemy with django? Please may you help me to clarify the right approach about which orm is better to use? Thanks a lot Cheers -
How do i initialize a django admin entity form
I am trying to make a meetingnote application where some points of the previous note are re-used in the current note. I am using the admin module of django to fill in the new note and i want the points of the previous note to be the standard value of the fields of the new note. They need to be retrieved from the database. The question is: how do i do this? This is what i've tried so far: class ActionListPointInline(admin.TabularInline): model = ActionListPoint extra = 1 def get_changeform_initial_data(self, request): return {'what' : 'test'} I tried using the get_changeform_initial_data to set the ' what' field to the value 'test' when opening a new add form, but it doesn't work. Can anyone tell me how i can achieve what i want? Thank you -
Django Unit tests fail over domain socket
I have Django configured to use the database with peer authentication over the local Unix Domain socket, instead of user/password authentication. Here's the settings.DATABASES: {'default': {'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mcps', 'PORT': 5433, 'TEST': {'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mytestdb', 'PORT': 5433, 'USER': 'mcp'}, 'USER': 'mcp'} } The port is correctly configured, the application itself has no problem working correctly. Yet, when I try to run pytest, with the environment variable DJANGO_SETTINGS_MODULE set to the above settings, a database is created - with the correct owner 'mcp' - but before tables are created I get an error: django.db.utils.OperationalError: FATAL: Peer authentication failed for user "mcp" What are unit tests doing differently anmd how can I fix this please? -
Multistep file validation, using dropzone and django (with ajax call?)
I have a Django site where I am using dropzone.js. What I am trying to do is pass the filename to a python function to validate it, and send back the responses to the browser to be displayed to the user. When Attempting to use an ajax call within a function that happens on dropzone addedFile event (within the dropzone init function, I get an error saying SCRIPT438: Object doesn't support property or method 'ajax'. Am I going about doing this wrong? does anybody have any tips on other ways to accomplish filename validations before uploading? $.ajax({ url: '/validateFile/', type: 'POST', data: filename, dataType: 'text', success: function(data, status, xhr) { console.log(data) }, error: function(xhr, status, err) { console.log(err) } }) Any help would be greatly appreciated! -
How do I pass an object image linked by foreign-key into a template?
I'm having trouble getting urls for the images attached to Car model objects in my Django project. The goal is to fetch a single image from the uploaded set (perhaps by a pk, or the first one to be uploaded) to use as a thumbnail in the list view. I've uploaded the images through the admin, but I can't fetch a single one from the template. I've tried using the <img src="{{ car.image.url }}"> (which is what worked when my image field was part of the Car model). When looking at this in the rendered template, it's just the alt-text. Looking through developer tools shows src(unknown) models.py class Car(models.Model): manufacturer = models.ForeignKey('Manufacturer', on_delete=models.SET_NULL, null=True) car_model = models.CharField('Model', max_length=50, null=True) description = models.TextField(max_length=4000) vin = models.CharField('VIN', max_length=17, help_text='Enter the 17 character VIN number.', blank=True, null=True) mileage = models.IntegerField(verbose_name='Mileage') date_added = models.DateTimeField(auto_now_add=True) engine_displacement = models.CharField(default=2.0, max_length=3, help_text="Engine displacement in Liters (E.g. 2.0, 4.2, 6.3)") price = models.IntegerField(default=0) seller = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this car") ... class Image(models.Model): car = models.ForeignKey(Car, on_delete=models.SET_NULL, null=True) image = models.ImageField(upload_to=image_directory_path) Template render {% for car in most_recently_uploaded %} <div class="col-xs-3 product-item" style="width:400px"> <figure class="figure"></figure> <a href="{{ car.get_absolute_url }}"><img src="{{ … -
How to select only questions not yet answered by a user in Django
I am creating a quiz and would like to appear to the user only questions that were not answered by the user. How do I do that? models.py class Questao(models.Model): idQuestao = models.CharField(max_length=7,primary_key=True,null=False,verbose_name="ID da questão") class Resposta(models.Model): idQuestao = models.ForeignKey(Questao,on_delete=models.CASCADE,verbose_name="ID da questão") usuario = models.ForeignKey(User,on_delete=models.CASCADE,verbose_name="Usuário") views.py questao=Questao.objects.filter(tipoQuestao=1,resposta__usuario=request.user).exclude(idQuestao=Resposta.objects.filter()).order_by("?").first() -
How/ what is wrong in my first view Django
please, tell me what is wrong in my first view Django because not working https://github.com/Fgregorio1/ftgtraderexample.git -
Relate Foreign Key id fields without Migrations
I'm currently trying to figure out how to relate two id fields of two different models from an existing database without migration scripts. I've pored over many, many different solutions; models.ForeignKey fields, models.ManyToOneRel fields, hyperlinked fields in the serializer, PrimaryKeyRelatedField in the serializer, every one seems to match a model to another model or another session and not match between two specific id fields in two different models. This is the code I'm currently working with; its using rsinger86 drf-flex-fields to allow designed expandable fields. class Cats(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid3, editable=False) hatId = models.UUIDField(primary_key=False, default=uuid.uuid3, editable=False) name = models.TextField() class Hats(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid3, editable=False) name = models.TextField() class CatsSerializer(FlexFieldsModelSerializer): hat = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Cats fields = [ 'id', 'hatId', 'name' ] expandable_fields = { 'hat': (HatsSerializer, {'source': 'hat', 'fields': ['name']}) } class HatsSerializer(FlexFieldsModelSerializer): class Meta: model = Hats fields = [ 'id', 'name' ] My hope is that I can eventually query a cat and use the expandable fields expand param to include that cats corresponding hat in the response.s