Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I implement action={% url '......' %} in django-form
What would be the equivalent of using <form action={% url '......' %}> in django-form, if I don't want to directly use HTML form? -
Programmatically Assign an Existing Animated GIF Image from Static Directory to a Model Instance's ImageField
OK. Let's say I have this GIF located at: static/myproject/img/coming-soon.gif A Django model named "Note" with an ImageField. class Note(models.Model): featured_image = models.ImageField(upload_to=my_irrelevant_function, blank=True, max_length=155) My goal is to say: If the Note model's featured_image does not exist, I want to assign the "coming-soon.gif" file to the instance. Note: I can't set the default="some/path/to/my/coming-soon.gif for reasons I don't want to get into. Please just assume I can't. Here's the coming-soon.gif: It's 12 frames: >>> img.n_frames 12 Current code situation: from django.core.files.images import ImageFile from django.core.files.base import File, ContentFile from django.conf import settings from django.views.generic import CreateView from PIL import Image from io import BytesIO ... class NoteCreateView(CreateView): def create_featured_image_if_none(self): if (self.object.pk is not None) and (not self.object.featured_image): img = Image.open(settings.COMING_SOON_IMAGE) self.object.featured_image.save(f'{self.object.slug}.gif', content=File(open(settings.COMING_SOON_IMAGE, 'rb'))) self.object.save() This code produces a non-animated gif. I've seen examples like this: gif[0].save('temp_result.gif', save_all=True, append_images=gif[1:], loop=0) but I'm not clear on: Do I even NEED to loop through each frame to compile a list of frames to pass to append_images when I already have the actual GIF image I want to assign to my model's instance? How would I even loop through? I've seen seek(#) and tell() but wouldn't I just be recreating the entire GIF from … -
Open charge point protocol (OCPP) server implementation using Python Djago or Java Spring boot
I am programming a a PoC of OCPP server which can communicate with an EV charger using OCPP protocol, in Python Django and Java Spring boot. I was using a OCPP python package given in the link here and I was able to create a OCPP center system using Python and make connections. My server should be able to have the method to list all connected chargers, but I could not find any documentation about this. Is this method available on the Python OCPP package here. If not, can anyone tell me how to implement this method? Any help will be appreciated. -
Django api call function asynchronously
I have three servers. Server A: call server B when some event happened (send info to B) Server B (Django API Server): Use the info from A, call the api of server C. Server C (Machine API Server): Will create task following the info server B send to it. I'm working on server B, because we need an api server and data in the middle of server A and our machine(server C) The work my Django api server(server B) does is that async def check_status(token, taskUuid): def call(): res = requests.get(URL+"task/"+taskUuid, headers={ "accessToken": token }, verify=False) return res.json() while True: time.sleep(1) res_json = call() if res_json['status'] != 'RunningTask': print(res_json) # # do something that store info in the database # break @list_route(methods=['post']) def post_api(self, request): task_config = { 'info': request.data['info'] } if 'optionInfo' in request.data: task_config['optionInfo'] = request.data['optionInfo'] USERNAME="username" PASSWORD="password" URL="https://{machine_ip}/" login_res = requests.post(URL+"auth", json={ "username": USERNAME, "password": PASSWORD }, verify=False) login_json = login_res.json() token=login_json['AccessToken'] ## token task_res = requests.post(URL+"task", headers={ "contentType": "application/json", "accessToken": token }, json=task_config, verify=False) task_json = task_res.json() if task_json['status'] == 'RunningTask': taskUuid = task_json['uuid'] ## My question is here asyncio.run(check_status(token, taskUuid)) result = { task_created: 'success' } return Response(result, status=status.HTTP_200_OK) else: result = { task_created: 'failed' … -
dynamic user list consumer in Django channels
I'm using Django(3.2.11) with the Postgres database. I'm creating a chat app with Django channels. so I created a message consumer and save it into the database. and also created a message history consumer by room. now I want to create a user list consumer which has dynamic messages with the user name. for that I made a consumer who returns infinite data. like:- class ChatListConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.room_group_name = 'chat_list_%s' % self.scope['user'].user_id self.connection = True await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): self.connection = False await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) def get_serializer(self, obj): return {'data': ProductQueryUsersSerializer( instance=obj.order_by('-updated_at'), many=True ).data, 'type': "chat_list"} async def receive(self, text_data): while self.connection: try: self.query = await database_sync_to_async( ProductQueryUsers.objects.filter )(Q(seller__user=self.scope['user']) | Q(user=self.scope['user']) ) data = await database_sync_to_async(self.get_serializer)(self.query) except EmptyPage: data = {'data': [], 'type': "chat_list"} await self.send(text_data=json.dumps(data)) and call this in javascript like:- <div id="message"></div> <script> const chatSocket = new WebSocket('ws://192.168.29.72:8000/ws/chat-list/?user=VXNlcjo4Mg=='); chatSocket.onopen = function(e){ chatSocket.send(JSON.stringify({})); console.log("open", e); }; chatSocket.onmessage = function(e) { const data = JSON.parse(e.data); console.log(data) data.data.forEach(function (item, index, arr) { var element = document.getElementById(item.room_id); if (typeof(element) != 'undefined' && element != null){ document.getElementById(item.room_id).innerHTML = item.last_message.message } else { document.getElementById('message').innerHTML += `<h1 id="${item.room_id}">${item.last_message.message}</h1>` } }); }; chatSocket.onerror = function(e){ … -
How i convert my python code in multi-user mode. Multi-user mode means more than one person to work on my django web applcaton at the same time
how to Convert/change python Django web application from single to multi-user? How I convert my python code in multi-user mode. Multi-user mode means more than one person to work on my Django web application at the same time. I don't have any idea how I change my code to multi-user. In my web application user upload their file, in return, my python code generates 11 files for the user but if two users upload their files at the same time from different browsers the code s not execute properly and show an error. -
Find pk in queryset Django
I have a problem in obtaining a single id from a queryset. I post my models and views in order to be more clear: models.py class MissionEntry(models.Model): student = models.ForeignKey( Student, on_delete=models.DO_NOTHING, blank=True, null=True) mission = models.ForeignKey( Mission, on_delete=models.DO_NOTHING, null=True, blank=True) log_entry = models.ForeignKey( LogEntry, on_delete=models.DO_NOTHING, blank=True, null=True) learning_objective = models.ForeignKey( LearningObjective, on_delete=models.DO_NOTHING, blank=True, null=True) grade = models.CharField( max_length=10, choices=GRADING_VALUE, blank=True, null=True) note = models.TextField(blank=True, null=True) debriefing = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.mission) + ' ' + str(self.log_entry) class Meta: verbose_name_plural = 'Mission Entries' class MissionEntryStatus(models.Model): mission = models.ForeignKey( Mission, on_delete=models.PROTECT, null=True, blank=True) student = models.ForeignKey(Student, on_delete=models.PROTECT) is_completed = models.BooleanField(default=False) is_failed = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class StudentMission(models.Model): mission = models.ForeignKey(Mission, on_delete=models.PROTECT) student_training_course = models.ForeignKey( StudentTrainingCourse, on_delete=models.PROTECT) mission_status = models.ForeignKey( MissionEntryStatus, on_delete=models.PROTECT, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['mission__name'] def __str__(self): return self.mission.name class LogEntry(models.Model): aircraft = models.ForeignKey(Aircraft, on_delete=models.DO_NOTHING) adep = models.ForeignKey( Aerodrome, on_delete=models.PROTECT, related_name='adep') ades = models.ForeignKey( Aerodrome, on_delete=models.PROTECT, related_name='ades') date = models.DateField() etd = models.TimeField() ata = models.TimeField() eet = models.TimeField() function_type = models.ForeignKey(FunctionType, on_delete=models.PROTECT) student = models.ForeignKey( Student, on_delete=models.PROTECT, blank=True, null=True) instructor = models.ForeignKey( Instructor, on_delete=models.PROTECT, blank=True, null=True) student_mission = models.ForeignKey( … -
OperationalError at /admin/app/question/ no such table: app_question (django)
Im new to this and Im tryna make a q&a type of app, I was just starting then when I went to admin/ to try it out I got OperationalError at /admin/app/question/ no such table: app_question Request Method: GET Request URL: http://127.0.0.1:8000/admin/app/question/ Django Version: 4.0.1 Python Version: 3.10.1 Installed Applications: ['app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'crispy_forms', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Exception Type: OperationalError at /admin/app/question/ Exception Value: no such table: app_question here is the models.py from django.db import models from django.contrib.auth.backends import ModelBackend from users.models import CustomUser # This is the question model class Question(models.Model): user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE) title = models.CharField(max_length=30) detail = models.TextField() add_time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title # This is the answer model class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) detail = models.TextField() add_time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.detail I'd appreciate if its explained in a beginner friendly manner, thank you! -
How do I pass primary key of the entry created by a django-form, to the next page after that
My Models.py contains 2 models, each Project can have multiple Role (i.e. one-to-many relationship): class Project(models.Model): title = models.CharField(max_length=2000) state_of_project = models.CharField(max_length=10, default='ongoing') introduction = models.TextField(blank=True) class Role(models.Model): role_name = models.CharField(max_length=30) project = models.ForeignKey(Project, on_delete=models.SET_NULL, null = True) def __str__(self): return self.role_name After submitting a form for model Project, I wanted to redirect user to fill the next form for model Role. The new roles added there should automatically have their foreign key project point towards the project created just before. How can I make that happen? I am specifically having problem adding mechanism of passing the primary key of model Project to the next form. -
How to statically add an image in django
Any one could help to add an image on the following view function, I tried adding the following way Category.objects.create( name='Others', slug='others', image='home/xxx/xx/static/assets/images/xxx.png' ) also tried Category.objects.create( name='Others', slug='others', image=static('home/xxx/xx/static/assets/images/xxx.png') ) image is not getting saved in both the ways -
The best way to optionally create accounts for the added employee
in my app the admin can add different employees and in my 'add employee' page i want to ask them if they want to also create a user account for them (so they will be able to login using a username and password). my employees has their own model, i want to know whats the best way to handle this in the models -
How to update 12k records in 1 minute in Django
I'm using Django(3.2.11) with the Postgres database. and we have 12k stocks symbols stored in a database. now we are updating their price in the database frequently with https://cloud.iexapis.com/stable/stock/{symbols}/intraday-prices?token={iex_api_key}&chartIEXOnly=true. now I required to update all 12k stocks price in 1 minute. for now im using celery periodic task. but I a task took more then 1 minute for completing. so how to update this all stocks in 1 minute -
How to access a value in a table connected by a Foreign Key
Currently I have a table called Load that has a relationship to a table called Container through a Foreign Key called Container_ID (the FK is just an integer). The foreign key lives in the Load table. Each row in the Load table has a Container_ID. The table Container has a column called Container_Name. What I want to do is to grab all rows from the Load table, and be able to tell what the actual container name is. Not the Container_ID, but the Container_Name that's in the Container table. I tried doing something like var = Load.objects.values_list('container_ID') but that only returns the actual foreign key integer, and I'm not sure how to take it that one step further to dive into the actual Container table to grab that Container_Name field. -
Getting an Error as "decoding to str: need a bytes-like object, int found" while tried to return id and field value in django models
model #1 class Add_Job(models.Model): job_name=models.CharField(max_length=254) client=models.ForeignKey(Client,on_delete=CASCADE,related_name='client') #client=models.ManyToManyField(Client) project=models.ForeignKey(Project,on_delete=CASCADE,related_name='project') #project=models.ManyToManyField(Project) user=models.ForeignKey(Users,on_delete=CASCADE) Hours=models.TimeField(null=True) start_Date = models.DateTimeField(max_length=10) end_Date=models.DateTimeField(max_length=10) def __str__(self): return str(self.id, self.job_name) model #2 class Add_Timelog(models.Model): project=models.ManyToManyField(Project) client=models.ManyToManyField(Client) Job=models.ManyToManyField(Add_Job) #Date = models.DateField(max_length=100 ,auto_now_add=True,editable=True) Date= models.DateField(default = datetime.date.today) Hours=models.TimeField(null=True) def __str__(self): return str(self.Date) while I tried to return the 'id' and 'job_name' from the 'Add_Job' model it is getting reflected in the database table. But the 'Add_timelog' model is getting an error as "TypeError at /api/Add_Timelog/ decoding to str: need a bytes-like object, int found". Don't know why it is getting an error. kindly help to solve this issue. -
How do I make django-form's foreign-key point to a model that is being currently created
My Models.py contains 2 models, each Project can have multiple Role (i.e. one-to-many relationship): class Project(models.Model): title = models.CharField(max_length=2000) state_of_project = models.CharField(max_length=10, default='ongoing') introduction = models.TextField(blank=True) class Role(models.Model): role_name = models.CharField(max_length=30) project = models.ForeignKey(Project, on_delete=models.SET_NULL, null = True) def __str__(self): return self.role_name And they have their respective forms in the forms.py file, which are accesed in two different html file: class ProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) class Meta: model = Project fields = ['title', 'state_of_project', 'introduction'] class RoleForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(RoleForm, self).__init__(*args, **kwargs) project = forms.ModelChoiceField(queryset=Status.objects.all()) class Meta: model = Role fields = ['role_name', 'project'] While filling up ProjectForm from an html page, I wanted to make it possible to go to another link that allows you to fill RoleForm for it on the other tab. But the role you add there should only be linked to current project (i.e. foreign key of that role should point to the project that is being created by the user now, but is not yet in the database). But in my current implementation through django-form, user is able to just select any past project for a new role, instead of only being allowed to select project that is … -
Error during template rendering with django-formtools
I'm following the django-formtools documentation, and curiously when I add this part: <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button> <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button> {% endif %} <input type="submit" value="{% trans "submit" %}"/> </form> I get the Tag start is not closed error right here: <input type="submit" value="{% trans "submit" %}"/> And I do get an error in Pycharm but I can't find why, I only removed trans because I won't be using it at the moment. I also have my doubts that the "first step" and "prev step" buttons are ok -
CORS Issue - DJANGO rest_framework
I have been facing the "CORS policy" issue in my API for few days and I cannot fix it. I have used the following middleware in settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware' ] ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True Am i missing something? I am currently using Python 3.6.5 and DJANGO (3.1.7) Thanks. -
NOT NULL constraint failed: dashboard_profile.user_id
I'm trying to save the last IP of User to the Profile module in Django but I get always NOT NULL constraint failed I know that last_ip should be set tonull=True and I run this commands:py .\manage.py makemigrations, py .\manage.py migrate. Thanks in advance. #models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(blank=True, max_length=150) last_ip = models.GenericIPAddressField(null=True, blank=True) avatar = ContentTypeRestrictedFileField(max_upload_size=10485760, null=True, verbose_name="",default='default.jpg', blank= True, content_types=['image/png', 'image/jpeg']) def __str__(self): return self.user.username #forms.py class UpdateUserForm(forms.ModelForm): username = forms.CharField(max_length=150, required=True) first_name = forms.CharField(max_length=150, required=False) last_name = forms.CharField(max_length=150, required=False) email = forms.EmailField(required=True) class Meta: model = User fields = ['username','first_name','last_name','email'] class UpdateAvatarBio(forms.ModelForm): avatar = forms.ImageField() bio = forms.CharField() class Meta: model = Profile fields = ['avatar', 'last_ip', 'bio'] #views.py def ip_client(request): return ( x_forwarded_for.split(',')[0] if (x_forwarded_for := request.META.get('HTTP_X_FORWARDED_FOR')) else request.META.get('REMOTE_ADDR') ) def profile(request): ip = ip_client(request) model = Profile(last_ip=ip) model.save() # Traceback suppose here is the issue if request.method == 'POST': ... ... return render(request, 'profile.html', {'user_form': user_form, 'profile_form': profile_form}) -
i got error 500 on production when i read filefield in django
hello everyone please help me i have recently maked a website but i got 500 error when i put it in production but strangly all is working well in my computer i am trying to read the buffer of a filefield inside a model and itson local but not in production class post(models.Model): titre=models.CharField(unique=True,null=True,max_length=100) description=models.TextField(null=True,blank=True,max_length=400) T=models.CharField(default="image",blank=True,max_length=50) image=models.FileField(null=True) cat=models.ForeignKey(categorie,on_delete=models.CASCADE,null=True) datepost=models.DateTimeField(auto_now_add=True,blank=True) user=models.ForeignKey(myuser,on_delete=models.CASCADE,null=True) vue=models.IntegerField(default=0,blank=True) def __str__(self): return self.titre def save(self, *args ,**kwargs): #cette partie permet de generer un identifiant unique f=self.image.readline() mime=magic.from_buffer(f,mime=True) if "video" in mime : self.T="short" super(post,self).save(*args,**kwargs) sorry for my english and thank you for your help -
Unknown string showing up in rendered HTML code
A random string "b b b b b" gets inserted between two HTML components which doesn't exist in my code to begin with. I currently have a js script to find this garbage string and just remove it manually. Was wondering if anyone knew why this was happening so I could actually fix it instead of this workaround This is how the relevant part of the code looks - HTML Code This is how the rendered HTML Code looks - Rendered Website code This is a Python-Django project being run on Chrome. I tested the same with firefox and this string shows up there too. So, I doubt it's a browser issue. Any help would be appreciated! Thanks :) -
How to setup Django with NPM?
I am very new to Django (and NPM for that matter) so please bear with me. I would like to use Django as my framework, but having NPM setup would make it a lot easier. For example, I wish to install TailWindCSS, Bootstrap, Font Awesome, and more which can be either run by CDN or manually downloaded and put into my Django project to work. However, if I just got npm installed then I can easily manage versions and install these packages at once. Therefore, right after I have my Django environment setup, how can I install and use NPM? Thanks! -
How to properly create User with allauth and custom user model in Django 4.0
I have a custom User model, subclassed from django AbstractUser: class User(AbstractUser): alias = models.CharField( "Alias", max_length=50, unique=True, null=True ) account_uuid = models.UUIDField(blank=True, null=True) I have installed allauth library, and all the signup/login mechanisms are working fine. The problem I'm facing is when I want to import Users instances from a different environment. from apps.users.models import User user, created = User.objects.update_or_create( email=account_info.get('contact').get('email_address'), defaults={ 'username': email, 'account_uuid': account_uuid, 'alias': alias } ) When a user had logged in previously with a social connector, this update/create raises an Integrity error for a constraint on User/email. Is there a proper way for creating a User instance so that it wouldn't break any underlying relations created with allauth models? -
Using query strings in django GET
I've a GET request in django rest framework that fetches data using kwargs. class FetchUser(APIView): def get(self, request, **kwargs): try: email = kwargs.get('email') user = User.objects.get(email=email) return Response(UserSerializer(user).data, status=status.HTTP_200_OK) except(KeyError, User.DoesNotExist) as e: return Response(str(e), status=status.HTTP_404_NOT_FOUND) Here's my url path(r'fetch/<str:email>', FetchUser.as_view(), name='fetch_user'), However I want to fetch the data using a query string, Something like http://base/fetch?email=something How do I modify my urls and views to do this? -
Django + React App in Azure gives a server error - 500 everytime
I have deployed a Django app to Azure through Github actions to Azure app service. But it gives a Server error 500 everytime. I have configured the static files and react template properly. In the Diagnose tab there's no error is displaying. How can I troubleshoot and find the error or Is there any other things to configure in Azure? I hosted a same copy in Heroku and it works there. -
django urls without a trailing slash show Page not found
in django urls without a trailing slash in the end i get this result "Page not found 404" the same project and the same code in one pc i get different result. this code is when i get the page without slash: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('about', views.about, name='about'), ] and this the same code but i should to add slash from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('about/', views.about, name='about'), ] what i am waiting in the frontend its my views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def about(request): return HttpResponse('about page') i am waiting for your help guys