Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems to display the Form in the Template using CreateView
What happens is that I am using CreateView and I find it curious that the code works when I put {{form}}, it displays all the fields and saves in the database (everything works very well) but when I break down the values one by one for example: {{form.plates}}, {{form.type}}, it does not send anything to the database and it stays on the same page. Why is that? I just need it broken down clientes-add.html <form enctype="multipart/form-data" method="post"> {% csrf_token %} <div class="row mb-3"> <div class="col-md-3"> <div class="mb-3"> <label>Customer type</label> <br> <div class="form-check form-check-inline"> {{ form.tipo }} </div> </div> </div> </div> <div class="row mb-3 only-corp hide-item"> <div class="col-md-12"> <div class="mb-3"> <label>Corporation name</label> {{ form.corporacion }} </div> </div> </div> <button class="btn btn-primary mb-3" type="submit" value="Post">Save</button> </form> -
Django pasar parametros por url
a través de una etiqueta y href paso parametros por url. Las etiquetas son del navbar y funcionan como filtro el problema esta en que al seleccionar una segunda opción la url no se maxaca y vuelve a insertar la ruta a la view. Esto como se puede solucionar? views.py: def pueblo(request, pueblo): activo = establecimientos.objects.filter(pueblo=pueblo) context = {'establecimientos_objects':activo} return render(request, 'orders/establecimientos.html', context) urls.py: path('pueblo/<str:pueblo>',views.pueblo, name='pueblo'), template: <ul class="nav nav-pills flex-column mb-auto"> <li class="nav-item"> <a href="pueblo/opcion1" class="nav-link link-dark" aria-current="page"> opcion1 </a> </li> <li> <a href="pueblo/opcion2" class="nav-link link-dark"> opcion2 </a> </li> <li> <a href="pueblo/opcion3" class="nav-link link-dark"> opcion3 </a> </li> </ul> -
Django background_task results in BrokenPipeError
I'm using django 3.1.4, django-background-tasks 1.2.5. I have a task registered which runs to completion successfully when I perform updateProducts.now() from the shell, but for some reason when it's automatically ran, it results in BrokenPipeError at different parts of the code. Often it refers to a collection not being undefined in a dictionary which is in the constructor of the GClient class. All collections are defined in the GClient class constructor. @background(schedule=timezone.now()) def updateProducts() -> None: client = GClient() db_client = DBClient() total_products = 0 collections = ["collection1", "collection2", "collection3", "collection4"] for collection in collections: products = client.getProductOfCollection(collection) if products is None: continue total_products += len(products) for product in products: db_client.addProduct(product) if "inventoryQuantity" in product and product["inventoryQuantity"] > 0: notify_restock(product["id"], db_client) print(db_client.updateErrors) db_client.updateErrors = {} print(f"Done Updating {total_products} Products") if not Task.objects.filter(verbose_name="Update Products").exists(): updateProducts(verbose_name="Update Products", repeat=7200, repeat_until=None) getProductOfCollection - Performs a GraphQL request for an array of products which can take anywhere between 3secs to 1min to fulfill, it checks periodically whether it's been fulfilled. Once fulfilled, it receives a link with a json to download, it downloads the json, parses it, stores all the products in an array and returns it. -
ERROR code 1452 mysql in windows and but not in linux
I have a django project that creates tables after manage.py migrate. I use some LOAD DATA LOCAL INFILE MySQL queries for both. I have 7 tables. All the first 6 tables are populated the same way in both Linux and Windows. Except for the last table that has some foreign keys in previous ones. Linux MySQL Output Windows MySQL Output Both Windows and Linux tables are in InnoDB and the parent table has exactly the same data. Table information in Linux Table information in Windows Section Table keys in Linux Section Table keys in Windows INSERT INTO `seas_database`.`section_t` (`eSession`,`eDays`,`dYear`,`nSectionNumber`,`nSectionCapacity`,`nEnrolled`,`bIsBlocked`,`tStartTime`,`tEndTime`,`cCoffCode_ID`,`cFaculty_ID`,`cRoom_ID`) VALUES ("Spring","F",2009,1,250,43,0,"14:00","15:30","AAT101","T001","C10210-S"); Proof that AAT101 exists in Windows Yet i get this error in Windows ONLY. Not in Linux. Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`seas_database`.`section_t`, CONSTRAINT `section_t_cCoffCode_ID_ade53504_fk_cooffered` FOREIGN KEY (`cCoffCode_ID`) REFERENCES `coofferedcourse_t` (`cCoffCode_ID`)) Linux MySQL version : mysql Ver 8.0.27 for Linux on x86_64 (MySQL Community Server - GPL) Windows MySQL version: C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql.exe Ver 8.0.27 for Win64 on x86_64 (MySQL Community Server - GPL) If it helps, the csv for which the LOAD DATA INFILE was ran, it was modified and created by Pandas from an xlsx file. -
how to search table by QR code scanning in django admin
Lookup Records with Qr code scanning in Django how we can add search option by QR scanning in django on the table.i wanna create the table .every item has unique QR code and i wanna search by scanning QR code (using mobile ) and show the matching data can i do in Django admin ??? -
How to Share single App to Django Developer?
I am developing a big application. How to share only single app to a developer. For Example there are 5 developers working on a Project. I want each developer to see only single app. Not complete code. Problem i am facing is with Django ORM. Since we import Django models inside the views. So other apps should be present in Django project to work. Approach which i found → Instead of Django ORM use Sqlalchemy. Here i can give access to specific app to developer. If he require some other table then i give him permission from Postgres to that corresponding table. I am confused in this method. Do big companies like Instagram provide code to every developer? Any blog or any answer is appreciated. -
Is it possible to create related objects on parent creation automatically in Django?
I have a Profile model and NotificationSettings model with OneToOne relation. There is more than one way to create Profile, but NotificationSettings must be created with all of them. I don't want to write same code for every view that creates Profile. So i was hoping that there is some event that i can track so NotificationSettings would be created automatically. Something similar to RubyOnRails' after_create callback -
Django NGINX uswsgi custom admin site permission
Just found out this tutorial for gunicorn https://codyparker.com/protect-django-admin-nginx-gunicorn/ Is there a way to add the same filterin case of proxying uwsgi? server { listen 80; server_name myserver; charset utf-8; location / { uwsgi_pass localhost:9876; include /opt/uwsgi_params } location /admin/ { allow 192.168.1.0/24; allow 10.1.1.0/16; deny all; proxy_pass http://myserver; } result in: 502 Bad Gateway -
Why won't my icons load in a django environment(or what ever its called)?
Good evening everyone. I had been coding outside a virtual environment for quite some time, so i decided it was finally time to put my project on a django app/environment/server/whatever lol. However, my fontawesome icons did not load when i did so. I tried everything i could possibly do -- I tried using both internal and external links to fontawesome. My icons are still loading perfectly outside the virtual environment, so I'm not sure what the problem is. -
ImportError: Could not import 'rest_framework.pagination.LimitOffsetPagination'
I am going to use latest django 4.0 with djangorestframework. After command: python manage.py runserver ImportError: Could not import 'rest_framework.pagination.LimitOffsetPagination' for API setting 'DEFAULT_PAGINATION_CLASS'. ModuleNotFoundError: No module named 'pytz'. -
How to fetch axios GET response to FullCalendar Vue.Js
Hello I'm traying to fetch my GET response axios to FullCalender events to make the events display dynamically -
ProgrammingError at /sign-up/ relation "auth_user" does not exist LINE 1: SELECT (1) AS "a" FROM "auth_user" WHERE "auth_user"."userna
so i just hosted my django app on Heroku and everytime i try to create an account i keep getting this error my views.py register function def register(request): if request.user.is_authenticated: return redirect('home') form = registerform() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.username = user.username.lower() user.save() login(request, user) return redirect('home') else: messages.error(request, 'User does not exist') return render(request, 'register.html', {'form' : form}) help, thanks -
Django AWS Elastic Beanstalk .ebextensions cronjob
I have successfully set up a cron in AWS extensions to run a Django command at a certain time. Although, I have unsuccessfully been able to run/add multiple commands at different times. Question: if I wanted to run multiple Django commands as cron jobs, would I add new duplicate config files (like below) within in my .ebextensions folder OR is it possible to add a new Django command (w/ different time) to the one below? .ebextensions -cron_job.config files: /usr/local/bin/cron_activity_use.sh: mode: "000755" owner: root group: root content: | #!/bin/bash source /opt/python/run/venv/bin/activate source /opt/python/current/env cd /opt/python/current/app docker exec `docker ps --no-trunc -q | head -n 1` python manage.py cron_activity_use /etc/cron.d/m_cron: mode: "000644" owner: root group: root content: | */10 * * * * root /usr/local/bin/cron_activity_use.sh commands: rm_old_cron: command: "rm -fr /etc/cron.d/*.bak" ignoreErrors: true -
How we use Recommendation System in Django?
I am working on a project (Recommendation for Clothes of E-commerce Site for Online Shopping) in which we almost done module 1 and in module 2 I use recommendation system. Requirements are : The system should be able to recommend the products to the user based on his/her buying history. For implementing the recommendation functionality in your Project you have to use AI (Machine Learning) based Approach. So how I'll perform this task ? -
DJANGO - Add/update/delete row in table with backup in sqlite database
Hi everyone :) (sry for my bad english you will have a french accent x) ) I'm stuck in my project because i need to update data already display by model (database objects). So, i need to add a row, delete a row with confirmation of user, and modify data ( i can already modify data but only into the table (with contenteditable="true" into the td ), it don't save it into the database). I really need you help to solve this problems, thanks in advance everyone :) Here my models (i use tableau): from django.db import models class Intervenants(models.Model): name = models.CharField(max_length=3, null=True) def __str__(self): return self.name class tableau(models.Model): Statut = models.CharField(max_length=1, null=True) Facturation = models.CharField(max_length=1, null=True) Commande = models.CharField(max_length=1, null=True) Num_d_affaire = models.CharField(max_length=100, null=True) Projet = models.CharField(max_length=120, null=True) Localisation = models.CharField(max_length=120, null=True) Descriptif = models.CharField(max_length=120, null=True) Archi = models.CharField(max_length=120, null=True) Date_Marqueur = models.CharField(max_length=10, null=True) BBIO_RT = models.CharField(max_length=10, null=True) DIAG_FAISA = models.CharField(max_length=10, null=True) APS = models.CharField(max_length=10, null=True) APD = models.CharField(max_length=10, null=True) PRO = models.CharField(max_length=10, null=True) DCE = models.CharField(max_length=10, null=True) ACT = models.CharField(max_length=10, null=True) VISA = models.CharField(max_length=10, null=True) DET = models.CharField(max_length=10, null=True) AOR = models.CharField(max_length=10, null=True) Charge_d_affaire = models.CharField(max_length=3, null=True) Second = models.CharField(max_length=3, null=True) Intervenant3 = models.CharField(max_length=3, null=True) Intervenant4 = … -
DRF: Share data between multiple SerializerMethodFields in ListSerializer
I have a DRF project with the following view: class AssetViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet, ): queryset = Asset.objects.all() serializer_class = AssetSerializer def get_serializer_class(self): if self.action == "list": return AssetListSerializer if self.action == "retrieve": return AssetSerializer return AssetSerializer # For create/update/destroy My problem is within the AssetListSerializer: class AssetListSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() name = serializers.ReadOnlyField() block_count = serializers.SerializerMethodField("get_block_count") requirement_count = serializers.SerializerMethodField("get_requirement_count") open_requirements = serializers.SerializerMethodField("get_open_requirements") in_progress = serializers.SerializerMethodField("get_in_progress") measure_count = serializers.SerializerMethodField("get_measure_count") All these methods call the same internal (expensive) method and then work with the result: def _get_asset_requirements(self, asset_id): req = do_some_expensive_method(asset_id) return req def get_requirement_count(self, instance): requirements = self._get_asset_requirements(instance.id) blablabla def get_open_requirements(self, instance): requirements = self._get_asset_requirements(instance.id) blablabla def get_in_progress(self, instance): requirements = self._get_asset_requirements(instance.id) blablabla So what I would like to do is to only to the expensive method once per object and then access the result from the SerializerMethodField-methods. I have found this part in the documentation: https://www.django-rest-framework.org/api-guide/serializers/#customizing-listserializer-behavior However I am clueless on how to implement it. My idea was something like: @classmethod def many_init(cls, *args, **kwargs): cls.req = cls._get_asset_requirements(cls.instance.id) return super().many_init(*args, **kwargs) but this does not work as I can't access the instance this way and the documentation is really incomplete here. Does anyone have an idea how to solve … -
python subprocess command (javac "Main.java") is not working on production
i am trying to compile java file from python(django). when i run my code on local sever then my java file compiled sucessfully but when i upload the files on heroku,Javac not found error showing def method1(request): code=request.data.get('code') len1=request.data.get('len') if os.path.isfile("Main.java"): os.remove("Main.java") f = open("Main.java", "x") f.write(code) f.close() file = 'Main.java' # codes[compile(file,len1)] std="" try: output = subprocess.check_output( "javac "+file, stderr=subprocess.STDOUT, shell=True, timeout=3, universal_newlines=True) except subprocess.CalledProcessError as exc: std="Status : FAIL", exc.returncode, exc.output else: # std="Output: \n{}\n".format(output) std="compiled sucess" context={ 'msg':'we got data', 'code':code, 'len':len1, 'std':std } return Response(context) This is my view.py file. response on local server "msg": "we got data", "code": "public class Main{\n public static void main(String[]args){\n \n System.out.println(\"HELLO Sid\");\n \n }\n}", "len": "java", "std": "compiled sucess" } response on heroku server "msg": "we got data", "code": "public class Main{\n public static void main(String[]args){\n \n System.out.println(\"HELLO Sid\");\n }\n}", "len": "java", "std": [ "Status : FAIL", 127, "/bin/sh: 1: javac: not found\n" ] }``` -
Chatting platform with django
I built a real-time chatting platform with Django framework using channels, but I don't understand why it's not saving the chat history to the database. So I added a few lines of codes, but now it showing undefined. Can anybody show me how to fix the code on my consumers.py? from django.contrib.auth import get_user_model from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync from .models import Message import json User = get_user_model class ChatConsumer(WebsocketConsumer): def fetch_messages(self, data): messages = Message.last_10_messages() content = { 'messages': self.messages_to_json(messages) } self.send_messages(content) def new_message(self, data): author = data['from'] author_user = User.objects.filter(username=author)[0] message = Message.objects.create( author=author_user, content=data['message']) content = { 'command': 'new_message', 'message': self.message_to_json(message) } return self.send_chat_message(content) def messages_to_json(self, messages): result = [] for message in messages: result.append(self.message_to_json(message)) return result def message_to_json(self, message): return { 'author': message.author.username, 'content': message.content, 'timestamp': str(message.timestamp) } commands = { 'fetch_messages': fetch_messages, 'new_message': new_message } def connect(self): self.room = self.scope['url_route']['kwargs']['room'] self.room_group_name = 'chat_%s' % self.room async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): data = json.loads(text_data) self.commands[data['command']](self, data) def send_chat_message(self, message): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) def send_messages(self, message): self.send(text_data=json.dumps(message)) def chat_message(self, event): message = event['message'] … -
DetailView in Django, keyword 'slug'
I recently started learning Django. I want to display one news item, but when I open on the link I get an error message: Cannot resolve keyword 'slug' into field. Choices are: NewsTitles, NewsContent, NewsSlug Request Method: GET Request URL: http://127.0.0.1:8000/news/nam-gravida-purus-non/ Django Version: 4.0 Exception Type: FieldError views.py from django.views.generic import DetailView from .models import News class GetNews(DetailView): model = News slug_url_kwarg = 'NewsSlug' template_name = 'news/single_news.html' context_object_name = 'single_news' allow_empty = False urls.py from django.urls import path from .views import GetNews urlpatterns = [ path('news/<str:NewsSlug>/', GetNews.as_view(), name='news'), ] models.py from django.db import models from django.urls import reverse_lazy class News(models.Model): NewsTitles = models.CharField(max_length=120) NewsContent = models.TextField(max_length=255) NewsSlug = models.SlugField(max_length=255) def __str__(self): return self.NewsTitles def get_absolute_url(self): return reverse_lazy('news', kwargs={'NewsSlug': self.NewsSlug}) What am I doing wrong? -
populate an excel with data from a django model
I populated a Django model with a pandas dataframe. In order to do this is had I used the to_dict() function in order for JSONField() Django model to accept the data. Is fine and works well. No what I am trying to do is to populate an excel file with this data. So I am accessing the data in the Django model and trying to use openpyxl to populate an excel with this data. However I am running into problems as I am getting the error saying that it cannot convert to excel. Anyway around this? My model: class myvalues(models.Model): items_list = models.JSONField() function that’s trying to populate excel: values_to_go_into_excel_obtained_from_model = myvalues.objects.values_list(“items_list”, flat=True) path = file_for_download.my_file.path wb = load_workbook(path) ws = wb["Sheet1"] pd.read_excel(path, engine='openpyxl', sheet_name="Sheet1") for row, v in enumerate(values_to_go_into_excel_obtained_from_model, 2): ws.cell(row, 4, v) wb.save(path) Any ideas why I am getting the error. Basically what Im trying to do is: Step 1: pandas df -> Django model of type Json Step 2: Access Django model values Step 3: put values from Django model into excel file I have step 1 and 2 but for cant get step 3. -
TypeError: Object of type Vehicle is not JSON serializable
when I try to filter my model I got this error TypeError: Object of type Vehicle is not JSON serializable my model class Vehicle(models.Model): driver_id = models.ForeignKey(Driver,on_delete=CASCADE,unique=True,null=True, blank=True) make = models.CharField(max_length=150) model = models.CharField(max_length=150) plate_number = models.CharField(max_length=10,validators = [validate_plate_numberLATIN,validate_plate_numberCYRYLLIC], unique=True) created_at = models.DateTimeField(default=NOW) updated_at = models.DateTimeField(default=NOW) def __str__(self): return self.make -
what causes Unhandled exception in wfastcgi.py: Traceback (most recent call last) in django +IIS
I create web app by django and IIS 10 web service on windows serevr 2019. I have problem in log file of wfastcgi log file that configured in web.config. text of log and problem is: 2021-12-10 16:26:35.568572: Unhandled exception in wfastcgi.py: Traceback (most recent call last): File "c:\python37\lib\site-packages\wfastcgi.py", line 774, in main record = read_fastcgi_record(fcgi_stream) File "c:\python37\lib\site-packages\wfastcgi.py", line 158, in read_fastcgi_record data = stream.read(8) # read record OSError: [Errno 22] Invalid argument 2021-12-10 16:26:35.615397: Running on_exit tasks 2021-12-10 16:26:35.646693: wfastcgi.py 3.0.0 closed 2021-12-10 16:59:42.309400: wfastcgi.py will restart when files in C:\inetpub\wwwroot\ are changed: .*((\.py)|(\.config))$ 2021-12-10 16:59:42.340650: wfastcgi.py 3.0.0 initialized each 1 hour wfastcgi raise OSError: [Error 22] and run exit task and after minutes restart again. I added follow line to web.config but no any impact on this error: <add key="SCRIPT_NAME" value="/Music_backend" /> whole web.config text is as bellow: <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> </system.webServer> <appSettings> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\Music_backend" /> <add key="WSGI_HANDLER" value="Music_backend.wsgi.application" /> <add key="DJANGO_SETTINGS_MODULE" value="Music_backend.settings" /> <add key="SCRIPT_NAME" value="/Music_backend" /> <add key="WSGI_LOG" value="c:\wfastcgi.log"/> </appSettings> <location path="" overrideMode="Deny"> <system.webServer> </system.webServer> </location> <location path="" overrideMode="Allow"> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\python37\python.exe|c:\python37\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> </location> </configuration> in addition i active Django.server , Django.request, Django.db.Backend LOGGING … -
Django migration- How to fix uniqueness=True on migration (backwards)?
A field in my model used to have no constraints. But in order to avoid problems in the future i need to make the field unique=True. This will obviously raise a Key (field)=(foo) is duplicated What is the best practice to fix that migration backwards in order to not raise an error? -
comparing forloop variables to a number
<ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="/">Home </a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'store' %}">Products</a> </li> {% for x in cat %} <li class="nav-item"> <a class="nav-link" href="#">{{x.name}}</a> </li> {% if forloop.counter >3%} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#">More</a> <div class="dropdown-menu"> <a class="dropdown-item" href="#">{{x.name}}</a> </div> </li> {% endif %} {% endfor %} </ul> So what i want here is the objects in the for loop counter be more that three then all should come in the dropdown menu which but it is not working as of now and giving me this error what is the best way to handle this problem Could not parse the remainder: '>3' from '>3' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.0 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '>3' from '>3' Exception Location: C:\Users\saran\OneDrive\Desktop\e-com-test\core\hienv\lib\site-packages\django\template\base.py, line 692, in __init__ Python Executable: C:\Users\saran\OneDrive\Desktop\e-com-test\core\hienv\Scripts\python.exe Python Version: 3.9.6 Python Path: ['C:\\Users\\saran\\OneDrive\\Desktop\\e-com-test\\core', 'C:\\Users\\saran\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\saran\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\saran\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\saran\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\saran\\OneDrive\\Desktop\\e-com-test\\core\\hienv', 'C:\\Users\\saran\\OneDrive\\Desktop\\e-com-test\\core\\hienv\\lib\\site-packages'] Server time: Fri, 10 Dec 2021 13:32:32 +0 -
How to relate multiple same models related_name in django
I have two models Movie and Actor class Actor(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(name="name", max_length=2000, blank=True, null=True) class Movie(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(name="name", max_length=2000, blank=True, null=True) actors = models.ManyToManyField(Actor, related_name='movie_actor') Now I would like to let the users to add their favourite actors like class MyUser(AbstractUser): actors = models.ManyToManyField(Actor, related_name='user_actor') Now, I would like to make the response for each movie so that the movie can tell that this movie has one/more of their favourite actors or not?