Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django Pass URL Parameter To Decorator
trying to redirect user to a page if they're not staff members. how do i pass a url parameter to a django decorator? # categories.urls.py from django.urls import path from categories.views import CategoryInfoView, CategoryDetailView app_name = 'categories' urlpatterns = [ path('<slug:handle>', CategoryDetailView.as_view(), name = 'category'), path('<slug:handle>/info/', CategoryInfoView.as_view(), name = 'category_info'), ] # categories.view.py class CategoryInfoView(LoginRequiredMixin, DetailView): model = Category template_name = 'categories/info.html' context_object_name = 'category' @redirect_if_not_staff(redirect_to = reverse_lazy('categories:category')) # <-- how do i pass the url parameter here?! def get(self, request, *args, **kwargs): return super().get(self, request, *args, **kwargs) def get_object(self): return get_object_or_404(Category, handle = self.kwargs.get('handle')) # decorator.py def redirect_if_not_staff(*setting_args, **setting_kwargs): """ A decorator to redirect users if they are not staff Can be used as: @decorator(with, arguments, and = kwargs) or @decorator """ no_args = False redirect_to = setting_kwargs.get('redirect_to', reverse_lazy('index')) if len(setting_args) == 1 and not setting_kwargs and callable(setting_args[0]): func = setting_args[0] no_args = True def decorator(func): @wraps(func) def redirect_function(self, request, *args, **kwargs): if not request.user.is_staff: return HttpResponseRedirect(redirect_to) return func(self, request, *args, **kwargs) return redirect_function if no_args: return decorator(func) else: return decorator how do i get localhost:8000/categories/sample/info/ to redirect to localhost:8000/categories/sample/ if the user is not a staff using decorators currently getting this error NoReverseMatch at /categories/agriculture/info/ Reverse for 'category' … -
Programmatically generate Django models for legacy databases
I'm trying to find out if there is a way to programmatically generate Django models for legacy databases. So given a list of legacy tables, create a model for each one. Here is an example of what I mean class Person_001(models.Model): id = models.IntegerField(primary_key=True) huge_dataset = models.CharField(max_length=70) class Meta: managed = False db_table = 'person_001' So for example, create this model for person_001, person_002 etc... I realize there may be a more efficient way of storing this data and I am opened to suggestions, but the data has been stored this way because huge_dataset is, well, huge. -
Django - if checkbox is selected, execute function
hey guys I'm trying to implement a feature in the user system where if you click the "is_staff" option another options pops up saying to enter your staff_id number. Is this possible? if so how can I implement it - or do I need to take a completely different approach. thanks! So something like this code from accounts>models.py from datetime import date import email import imp from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Email address is required') if not username: raise ValueError('Username is required') user = self.model( email=self.normalize_email(email), username = username, ) user.set_password(password) user.save(using = self.db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password = password, username = username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using = self.db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) #staff_number = models.CharField(max_length=10, unique=True) is_superuser = models.BooleanField(default=False) #note for self - these fields are required USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username',] objects = MyAccountManager() def __str__(self): return self.email def …