Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django OAuth Authentication
I built an app (Django backend, React frontend) that whenever a client login it will generate JWT authentication. React will store the access token and client can use it to access Django backend database. Then I want to add in social login feature (Google) so I will get back access token from that as well. However, this access token is different from the JWT access token generated before, so I wonder how can I integrate both ways of logging in a user smoothly on both Django and React? For JWT I use djangorestframework-simplejwt For social login I use django-allauth I can run each individual way perfectly on React, but I don't know how to keep both the installations of JWT and allauth in Django settings. -
Django Template changing html attribute based on slug and current request
When I tried to iterate through a list of post titles to create links in a django template the urls never match the requested path (matching the current web page should alter the formatting on the page for that list item). When I try and change things, Django spits out a 404 error which doesn't let me diagnose the problem or it "works" but not as expected. the relevant url patterns: path('<slug:post>', views.blog_post, name='entries') the relevant views function: def blog_post(request, post): try: return render(request, 'blog/post.html', { 'post_title':post, 'post_content':blog_posts[], 'posts':blog_posts.keys }) except: raise Http404() the template: <ul> {% for post in posts %} {% url "blog:entries" "{{post}}" as blog_entry %} <li><a href="/blog/{{post}}" {% if request.path == blog_entry %} class="active"{% endif %}> <span class="item">{{post}}</span> </a></li> {% endfor %} </ul> I suspect the {% url "blog:entries" "{{post}}" as blog_entry %} in the template is not resolving correctly as when I replace the href with {% blog_entry %} it causes a 404 error. I have tried hard coding it in, I have tried different ways of writing the url, I have tried changing the syntax (in case I am doing it incorrectly. I have checked the page source when I have run tests. I … -
Django: how to write django signal to update field in django?
i want to write a simple django signal that would automatically change the status of a field from live to finished, when i check a button completed. I have a model that looks like this\ class Predictions(models.Model): ## other fields are here user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) status = models.CharField(choices=STATUS, max_length=100, default="in_review") class PredictionData(models.Model): predictions = models.ForeignKey(Predictions, on_delete=models.SET_NULL, null=True, related_name="prediction_data") votes = models.PositiveIntegerField(default=0) won = models.BooleanField(default=False) when i check the won button that is in the PredictionData model, i want to immediately changes the status of the Prediction to finished. NOTE: i have some tuple at the top of the model. STATUS = ( ("live", "Live"), ("in_review", "In review"), ("pending", "Pending"), ("cancelled", "Cancelled"), ("finished", "Finished"), ) -
How to save Request URL from inspector in Django Model
I'm trying to implement a web application in which the user fills out a form and separately there is a form that the user fills out and selects a route on the map. I use Mapbox for this. In HTML it looks like I have a separate form in the form element and a separate map in the div element. When I built a route in the inspector, I find a processed request with the GET method and the Request URL. My question is how to save this URL request together with the form, or at least separately? How do I even save this URL request to the Django Model. Part from my model.py:: class Route(models.Model): route_name = models.CharField(max_length=50) lvl = models.IntegerField(default=0) about = models.TextField(max_length=1500) total_distance = models.IntegerField(default=0) country = models.ForeignKey(Country, on_delete=models.CASCADE) def __str__(self): return self.route_name def __str__(self): return self.about class RoutesURL(models.Model): url = models.CharField(max_length=1000) def __str__(self): return self.url And my views.py: def getForm(request): form = RouteForm() if request.method == 'POST': form = RouteForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('home') return render(request, 'routes_form/route_form.html', {'form': form}) -
Select related is not returning all the values from the relation in Django
I'm doing this query SELECT [User].[User_Id], [User].[Client_id], [User].[EMail], [User].[First_Name], [User].[Family_Name], [User].[Telephone], [Clients].[Client_Id], [Clients].[Name], [Clients].[Organization_type] FROM [User] INNER JOIN [Clients] ON ([User].[Client_id] = [Clients].[Client_Id]) WHERE [User].[EMail] = 'birna@athygli.is' In the SQL server is working fine even when I print in django the queryset looks good, but, when getting the results is not getting it from the Clients` table, It has to be something with the relation between tables in Django but I really don't know where Here are my two models class V2_Clients(models.Model): Client_Id = models.CharField(primary_key=True, max_length=50) Name = models.CharField(max_length=255, null=True) Organization_type = models.CharField(max_length=128, null=True) class Meta: managed = True db_table = "[Clients]" class V2_Users(models.Model): User_Id = models.CharField(primary_key=True, max_length=50) Client = models.ForeignKey(V2_Clients, on_delete=models.CASCADE) EMail = models.CharField(max_length=250) First_Name = models.CharField(max_length=50, null=True) Family_Name = models.CharField(max_length=50, null=True) Telephone = models.CharField(max_length=50, null=True) class Meta: managed = True db_table = "[User]" This is where I do the query, even when I do print(v2_user.query) I get the same SQL shown at the top, but is not getting the values from the Clients table only the results from the User v2_user = V2_Users.objects.using('sl_v2').filter(EMail=jsonData['Client']['Client_Email']).select_related() What could be the issue? -
How do I use multi tag filters in Django REST Framework API response?
first of all I apologize if I did not ask a question using better words. I am building a DRF App, I have Products Model, ProductSerializer and ProductsSummaryView. Furthermore, I have Workspace Model (not going to talk about it as it is not related to the issue). Now, I want to return those products details in success response which are attached with a specific Workspace, filtered on some parameters. What I have done: I defined filterset_fields and filter_backends. It works fine. For example, if I go to this URL {{domain}}/path/?country__title=Japan, it filters the data for Japan and show me. But the problem is, I want to filter using multi-tag, such as let's say if I want to see details for Japan and Korea, so I want something like this {{domain}}/path/?country__title=Japan&country__title=Korea, but it is not working and it just returns all the details. I even tried adding empty list format in the URL and tried this URL {{domain}}/path/?country__title[]=Japan&country__title[]=Korea, but it still did not work. Can anybody help me in this? My Product Model is: class Product(BaseModel): """Product model to store all prices of a product and related brand and countries it's available in""" product = models.CharField(max_length=255) country = models.ForeignKey(Country, null=True, on_delete=models.DO_NOTHING) … -
Unexpected pylance behaviour with Django vscode
I have Django project written with VScode When I open it on another machine I'm starting to receive errors from pylance. I compared all settings. Example of mistake: "user" is not a known member of "None" "GET" is not a known member of "None" "ingredient" is possibly unbound All the packages from requirements.txt, the same version of python as original etc. screenshot I've reinstalled IDE, python and extensions. It didn't work, so I have no idea what's the reason. -
I am not able to export image in CSV file in Django Admin
Everytime I export the data all of it gets exported but for the image which is there I am only getting the url of the image and not actual image. Image of exported CSV file Database fields from where I export it I want the actual image to be exported in CSV file and not the image storage path. If anyone knows how to do it kindly help. -
Model Form not displaying
So I created a model form but it's not showing in the page but it's registered on the django admin site.views.py[forms.py (https://i.stack.imgur.com/Z3qud.png)models.py the error I keep getting I tried creating the models using django shell -
how can I rate and give review about doctor services?
I'm trying to give a rate and review for a doctor service and that rate will come from the patient which means I have two types of users so how could be the view my models.py class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) class Doctor(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) number_phone = models.CharField( _('االهاتف :'), max_length=50, blank=True, null=True) last_login = models.DateTimeField(auto_now_add=True, null=True) class Patient(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=50, verbose_name="الاسم ") last_login = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s' % (self.user.username) class Comments(models.Model): created_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name='comment') # co_email = models.ForeignKey( # User, on_delete=models.CASCADE, related_name='comment') co_body = models.TextField(max_length=400, verbose_name='التعليق') rate = models.IntegerField(default=0) created_dt = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) post = models.ForeignKey( User, on_delete=models.CASCADE, related_name='comments') def __str__(self): return 'علق {} على {}'.format(self.created_by.username, self.post) forms.py class Commentair(forms.ModelForm): co_body = forms.CharField(widget=forms.Textarea( attrs={'rows': 3, 'placeholder': 'ما هو تعليقك عل الدكتور ؟'}), label='التعليق') class Meta: model = Comments fields = ('co_body','rate') html <div class="col-md-12"> <form action="" method="POST"> <div class="rate"> <input type="radio" name="rate" id="rate10" value="5" required /><label for="rate10" title="5"></label> <input type="radio" name="rate" id="rate8" value="4" required /><label for="rate8" title="4"></label> <input type="radio" name="rate" id="rate6" value="3" required /><label for="rate6" title="3"></label> <input type="radio" name="rate" id="rate4" value="2" required /><label for="rate4" title="2"></label> <input type="radio" name="rate" … -
Why am I getting the "Key error" in this code Django Rest Framework?
Well, I am trying to show ads after every 10th post in my feed in Django rest framework with both ad and post model separate. I'm actually stuck and will really appreciate anyone that will help me solve this problem. Here's my code: My Post & Ad Model class Post(models.Model): question = models.TextField(max_length=500) image = models.ImageField(upload_to='posts/', blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) # tags = models.ManyToManyField(Tag, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) upvote = models.ManyToManyField(User, related_name="like", blank=True) downvote = models.ManyToManyField(User, related_name="dislike", blank=True) is_ad = models.BooleanField(default=False) ordering = ["-created_at"] def __str__(self): return self.question class Ad(models.Model): # unique identifier for the ad id = models.AutoField(primary_key=True) # name of the ad name = models.CharField(max_length=255) # image for the ad image = models.ImageField(upload_to='ads/images/', blank=True, null=True) # additional images for the ad image_2 = models.ImageField(upload_to='ads/images/', blank=True, null=True) image_3 = models.ImageField(upload_to='ads/images/', blank=True, null=True) image_4 = models.ImageField(upload_to='ads/images/', blank=True, null=True) image_5 = models.ImageField(upload_to='ads/images/', blank=True, null=True) # URL that the ad should redirect to when clicked url = models.URLField() # start and end dates for the ad start_date = models.DateField() end_date = models.DateField() # targeting information for the ad targeting = models.TextField() # budget for the ad budget = models.DecimalField(max_digits=10, decimal_places=2) # ad delivery type (standard … -
How to append string in the end of Django redirect in view?
I have a product on my platform and when a specific user does an action, I want to redirect them to example.com/product/product-slug/#SectionInWebsite. However, I am not able to find a way to append "#SectionInWebsite" to the end of the redirect function. return redirect('ProductSingle', product.slug, "#SectionInWebsite") -
How to use gzip in django?
I wanna know how to use gzip for founctional views and class_based views in django? and where do I know the spped pages defference after and befor gzip from? -
TypeError: Object of type User is not JSON serializable
I am quite new to Django and I am building a simple referral system where a code is autogenerated for the user and when this code is called, the API should return the user by which this code was referred. However I am experiencing some difficulties to return the username, getting the error TypeError: Object of type User is not JSON serializable. Below I am posting my code (please ignore the unused imports, I was trying many things and I need to clean the code later) views.py ` from rest_framework.decorators import api_view from rest_framework.response import Response import json, requests from rest_framework.views import APIView from django.http import JsonResponse, HttpResponse from django.core import serializers from django.core.serializers import serialize import ast from rest_framework.parsers import JSONParser class MainView(APIView): def post(self, request): code = request.data["ref_code"] print(str(code)) try: profile = ReferralSys.objects.get(code=code) print(profile) request.session["ref_profile"] = profile.user username = profile.user.username print(username) print(type(username)) # return HttpResponse("user is here", user) except: pass print(request.session.get_expiry_date()) return Response(f"{profile.user.username}") models.py from django.db import models from django.contrib.auth.models import User from .utils import generate_ref_code # Create your models here. class ReferralSys(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(blank=True) code = models.CharField(max_length=12, blank=True) recommented_by = models.ForeignKey( User, on_delete=models.CASCADE, blank=True, null=True, related_name="ref_by" ) updated = models.DateTimeField(auto_now=True) created = … -
Django's ModelMultipleChoiceField failing to add foreing keys ids
I'm trying to save a model from the Django's admin using forms: Here are the models.py: class Availability(models.Model): """Model for the availability table.""" availability_id = models.AutoField(primary_key=True) schedule = models.ForeignKey( AdventureSchedule, on_delete=models.CASCADE ) available_guests = models.PositiveIntegerField(null=True, blank=True) date = models.DateField(auto_now=False, auto_now_add=False) price = models.DecimalField(max_digits=6, decimal_places=2, null=True) discount = models.DecimalField(max_digits=6, decimal_places=2) status = models.CharField(max_length=50, default='Available') created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) class Meta: """Availability model Meta.""" verbose_name_plural = "2.3 - Availability" def __str__(self): return self.date.strftime("%B %d, %Y") class Reservations(models.Model): """Model for the reservations table.""" reservation_id = models.AutoField(primary_key=True) availability = models.ManyToManyField(Availability) user = models.ForeignKey(BaseUser, on_delete=models.PROTECT) num_guests = models.IntegerField() num_military = models.IntegerField() num_youth = models.IntegerField() price = models.FloatField() status = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) class Meta: """Reservations model Meta.""" verbose_name_plural = "Reservations" The forms.py: class ReservationsAdminForm(forms.ModelForm): """ModelForm for the reservations model.""" class Meta: model = Reservations exclude = [] availability = forms.ModelMultipleChoiceField( queryset=Availability.objects.all(), required=False, widget=FilteredSelectMultiple('availability', False) ) def __init__(self, *args, **kwargs): # Do the normal form initialisation. super(ReservationsAdminForm, self).__init__(*args, **kwargs) # If it is an existing reservation (saved objects have a pk). if self.instance.pk: # Populate the availability field with the current reservation. self.fields['availability'].initial = self.instance.availability_set.all() def save_m2m(self): # Add the availability to the reservation. self.instance.availability_set.set(self.cleaned_data['available_dates_select']) def save(self, *args, **kwargs): # … -
How to get the response of Firebase Messaging in django (FCM-DJANGO)
I'am trying to get the response errors from Firebase_Admin in my django application, because some users are not reciving the notifications, but when I use the code below I only recive a FirebaseResponseDict() with a batchResponse, the registration_ids_sent and deactivated_registration_ids inside for example: FirebaseResponseDict(response=<firebase_admin.messaging.BatchResponse object at 0x053E124>, registration_ids_sent=['...','...','...'],deactivated_registration_ids=[] I need the error detail to know why some users are not reciving push notifications I need the error detail to know why some users are not reciving push notifications This is my Code: ` devices.send_message(Message(webpush=WebpushConfig(notification=WebpushNotification(title=noticia.titulo, body=noticia.resumo, image=noticia.capa.url, icon=icone), fcm_options=WebpushFCMOptions(link='https://site/'+str(id))))) ` any help will be helpfull -
How to save history from django-simple-history in different database?
i'm new with django and currently i'm trying to implement django-simple-history in my project, but i found a problem, i want to save my object in the default database and the history in a different database, i found that i can indicate the history model to not use the main database like this: history = HistoricalRecords(use_base_model_db=False) But i can't find any information about how to achive that I know that I can save the object in a specific database like this: obj.save("database_name") or select which database to use: poll = Poll.objects.using('other').create(question='Question 1') I know that only calling save() will store the object in the default database but i don't know how to save only the historical object in a different database. Anyone can help me with this? -
Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
I want to see that some data will come from an array through the checkbox. But when I select such an error is showing! {groupList && groupList.length > 0 && ( <div className="form-check form-check-inline"> {groupList.map((group) => ( <div> <input className="form-check-input" type="checkbox" id={group.id} value={group.id} onChange={(e) => { setGroups( Array.from( e.target.options, (item) => item.value ) ); }} /> <label className="form-check-label" htmlFor={group.id}> {group.name} </label> </div> ))} </div> )} How to solve? Thanks in advance. -
How to translate this dataframe using Pandas [duplicate]
I have a panda DataFrame that looks like this: Name Time Court 0 Smith 08:00 AM 1 1 Smith 08:30 AM 1 2 Smith 09:00 AM 1 3 Smith 09:30 AM 1 4 Smith 10:00 AM 1 5 Smith 10:30 AM 1 6 Smith 08:00 AM 2 7 Smith 10:30 AM 2 8 Kissinger 12:00 PM 3 9 Kissinger 09:30 AM 4 10 Kissinger 10:00 AM 5 11 Kissinger 09:30 AM 6 etc I want it to look like this, where the Court# is the header and times are the index: 1 2 3 4 5 6 08:00 AM Smith Smith 08:30 AM Smith 09:00 AM Smith 09:30 AM Smith Kissinger Kissinger 10:00 AM Smith Kissinger 10:30 AM Smith Smith 11:00 AM 11:30 AM 12:00 PM Kissinger 12:30 PM etc I've tried many things but this is beyond my knowledge level. Thanks for your help in solving this problem! -
Regex for URL with specified Domain or a signed URL
I want to match a url to replace it on demand in Python. the url looks like: https://storage.googleapis.com/icontent/media/2022-12-21%2.jpg?Expires=16344&AccessId=icontent-web.gservice.com&Signature=[alplanumeric characters] anyother url that isnt this way should not match. For now, I'm using a general url regex and filtering based on the domain name. regex I'm using is : https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*) i want to replace this inside the src attributes and update the expired url on demand. Any help would be appreciated. Thanks . -
Celery beat PeriodicTask max executions
Im trying to put max executions to my PeriodicTask with IntervalSchedule. I know total_run_count but, ¿how can use it to put max executions to my PeriodicTask? @receiver(post_save, sender=AutoTask) def create_periodic_task(sender, instance, **kwargs): interval = IntervalSchedule.objects.get_or_create(every=instance.every, period=instance.periodicity)[0] PeriodicTask.objects.create(name=instance.title, task="create_autotask", start_time=instance.creation_date, total_run_count=instance.repetitions, interval=interval) I coded this, but, in this case, I can configure the interval (example : each 2 days ), but... how can I limitate the repetitions? Ty -
Getting a django.utils.datastructures.MultiValueDictKeyError using ajax
I am trying to use the ajax post function to post data from my contact form in one of my templates. However, I am getting a 'django.utils.datastructures.MultiValueDictKeyError' when I make the request. The error is a server error and it is displayed as shown django.utils.datastructures.MultiValueDictKeyError: 'name' It is being triggered in the view.py folder on the line with the code name = request.POST['name'] Here is my model for the message: class Message(models.Model): name = models.CharField(max_length=255) email = models.CharField(max_length=255) content = models.TextField(max_length=10000) created_at = models.DateTimeField(auto_now_add=True) This is my view.py: def save_message(request): if request.method=='POST': name = request.POST['name'] email = request.POST['email'] content = request.POST['content'] Message.objects.create( content = content, name = name, email = email ) messages.success(request, f'Your message has been sent. Expect a response soon!') return JsonResponse({'bool':True}) This is the form in the index template {% csrf_token %} <form class="contactForm" id="contactForm"> <div class="form-floating"> <input class="form-control" class="message-name" id="name" type="text" placeholder="Enter your name..." /> </div> <div class="form-floating"> <input class="form-control" class="message-email" id="email" type="email" placeholder="Enter your email..." /> </div> <div class="form-floating"> <textarea class="form-control" id="message" class="message-text" placeholder="Enter your message here..."></textarea> </div> <br /> <button class="btn btn-primary text-uppercase save-message" id="submitButton" type="submit">Send</button> </form> And this is my ajax: {% block script %} <script> $(document).ready(function(){ // This is for the post … -
How to save Mapbox routes in Django Model
I have an html page with a form and Mapbox. Below is a picture of what it looks like. I want the user to fill out a form and then plot a route on the map (see screenshot). Both the data of this form and the route itself were saved to the database. When filling out the form on the left, everything is successfully saved to the database. But I have a question, how to save the routes that I build on the Mapbox map. I checked through the Network in the browser inspector, and the API itself creates the Mapbox request. But here's how to save it to my table... For example I have a table Route and the columns are id, latitude and longitude. Perhaps tell me in which direction to think, tk. I broke my head that how to pull this data. Maybe some project code will help you. django views.py: def getForm(request): form = RouteForm() if request.method == 'POST': form = RouteForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('home') return render(request, 'routes_form/route_form.html', {'form': form}) This question is rather for those who have worked with Mapbox or know something about it. P.S. I'm still just learning and I just … -
How to specify postgres DB parameters during Github Action Python build for Azure?
I have a Django web application I'm trying to deploy to Azure. I'm following this tutorial on how to set up the project. During the build I'm trying to run migrations on the DB, with the following command: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python version uses: actions/setup-python@v1 with: python-version: '3.10' - name: Create and start virtual environment run: | python -m venv venv source venv/bin/activate - name: Install dependencies run: pip install -r requirements.txt - name: Make migrations and run migrations run: python ./appname/manage.py migrate However, this step fails with the following error: django.db.utils.OperationalError: could not translate host name "$.***.database.azure.com" to address: Name or service not known I have inserted the DBNAME, DBHOST, etc. values shown on the screenshot as app secrets into github, so I'm really not sure why it is not finding them. Can anyone point out please what am I missing here? -
WebSocket connection error when creating a chat application with Django
I am working on a chat application which is like a whatsapp web clone. I have been stuck dealing with websocket connection as it cannot connect to the specified address. I am getting the error WebSocket connection to 'ws://127.0.0.1:8000/ws/2/' failed:. The url specified is because I am using the user id to create a room name in the consumers.py file. Here is part of the consumers.py file: class PersonalChatConsumer(AsyncWebsocketConsumer): async def connect(self): my_id = self.scope['user'].id other_user_id = self.scope['url_route']['kwargs']['id'] if int(my_id) > int(other_user_id): self.room_name = f'{my_id}-{other_user_id}' else: self.room_name = f'{other_user_id}-{my_id}' self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) Also here is part of the javascript file handling the websocket connection: const id = JSON.parse(document.getElementById('json-username').textContent); const message_username = JSON.parse(document.getElementById('json-message-username').textContent); const socket = new WebSocket( 'ws://' + window.location.host + '/ws/' + id + '/' ); The error message in the console of VsCode states Not Found: /ws/2/. Also here is the urls file: urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include(('accounts.urls', 'accounts'), namespace='accounts')), path('', index, name='home'), path('<str:username>/', chatPage, name='chat'), ] Any help will be highly appreciated. Thanks