Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allauth social_account_added signal not sent
views.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(social_account_added) def after_social_account_added(request, sociallogin, **kwargs): profile = Profile.objects.filter(user=request.user).first() sc = sociallogin.account if DEFAULT_PP in profile.avatar.url: if sc.provider == 'facebook': profile.avatar = f"http://graph.facebook.com/{sociallogin.account.uid}/picture" else: profile.avatar = sc.extra_data[ALL_AUTH_IMAGE_KEYS[sc.provider]] profile.save() The create_profile is fired when a user is created, it creates a new Profile. When a user add their social account, the after_social_account_added is fired, it updates the avatar of the Profile and sets it to the image provided by the Provider. The create_profile works fine, but the after_social_account_added does not run. Any help is highly appreciated. Thank you -
How to Create an object of model A with two random objects of a model B in Django?
I'm trying to create an app that meets two random users in Django. my question is how to create an object Meeting out of 2 random users from my User model, I want something like a for loop so that every 2 users in my database have a meeting! ps: I have only one day left to submit my work i will be so thankful if u help me -
drf-spectacular's extend_schema not working
I recently migrated from drf-yasg to drf-spectacular on my project, but the @extend_schema decorator does not seems to add any information to my generated schema : views.py class SearchView(GenericViewSet): serializer_class = serializers.CriterionSerializer @extend_schema( methods=['post'], summary="Find patients according to search query.", description="Search for patients related to Documents found with the given query.", request=PolymorphicProxySerializer( component_name='Criterion', serializers=[ serializers.TextCriterionSerializer, serializers.GroupCriterionSerializer, ], resource_type_field_name='type', ) ) @action(detail=False, methods=['POST']) def fetch(self, request): serializer = serializers.CriterionSerializer(data=request.data) if not serializer.is_valid(raise_exception=True): return Response(serializer.errors, status=400) return serializers.PatientDocumentSerializer( serializer.create(serializer.validated_data).fetch(), context={'request': request}, many=True ).data And here's the relevant part of the generated schema : /search/fetch/: post: operationId: searchFetchCreate description: '' tags: - search security: - jwtAuth: [] responses: '200': description: No response body Here some additional information for context : urls.py router = routers.DefaultRouter() router.register(r'search', views.SearchView, basename='search') urlpatterns = [ path('', include(router.urls), name="search"), ] SPECTUACULAR_SETTINGS SPECTACULAR_SETTINGS = { 'TITLE': 'API', 'VERSION': '1.0.0', 'CAMELIZE_NAMES': True, 'COMPONENT_SPLIT_REQUEST': True, 'SERVE_PERMISSIONS': ['rest_framework.permissions.AllowAny'], 'SWAGGER_UI_SETTINGS': { 'deepLinking': True, 'filter': True, 'displayRequestDuration': True, 'syntaxHighlight.activate': True, 'syntaxHighlight.theme': 'monokai', }, } Versions : $ pip3 show django drf-spectacular Name: Django Version: 2.2.13 [...] --- Name: drf-spectacular Version: 0.17.1 [...] -
my form not updating database, it sends GET instead of POST
i'm new trying to learn Django by building my e-commerce website. In my terminal i'm getting GET and POST, although i specified action to POST image result in my terminal this code works great before i add translation to my website, but after adding Internationalization to my project, the form is no longer working(the form is not translated because it is comment section) models.py: class Comment(models.Model): STATUS = ( ('New', 'New'), ('True', 'True'), ('False', 'False'), ) product = models.ForeignKey(Product, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=50, blank=True) comment = models.CharField(max_length=250, blank=True) rate = models.IntegerField(default=1) ip = models.CharField(max_length=20, blank=True) status = models.CharField(max_length=10, choices=STATUS, default='New') create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subject class CommentForm(ModelForm): class Meta: model = Comment fields = ['subject', 'comment', 'rate'] views.py: def addcomment(request, id): url = request.META.get('HTTP_REFERER') # get last url # return HttpResponse(url) if request.method == 'POST': # check post form = CommentForm(request.POST) if form.is_valid(): data = Comment() # create relation with model data.subject = form.cleaned_data['subject'] data.comment = form.cleaned_data['comment'] data.rate = form.cleaned_data['rate'] data.ip = request.META.get('REMOTE_ADDR') data. product_id = id current_user = request.user data.user_id = current_user.id data.save() # save data to table messages.success(request, "Your review has ben sent. Thank you for your interest.") return … -
I have a table in Django with ManyToManyField. Can't figure out how to update a table entry
I have a table with posts that can have multiple categories, and a table with categories that can have multiple posts. models.py: class Category(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=25) body = models.TextField() image = models.ImageField(blank=True) created_on = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) categories = models.ManyToManyField('Category', related_name='posts', blank=True) profile = models.ForeignKey('Profile', verbose_name='User', on_delete=models.CASCADE, related_name='profile') def __str__(self): return self.title views.py Сlass ListCategoryView(generic.ListView): def get(self, request, *args, **kwargs): category = kwargs['category'] posts = Post.objects.filter(categories__name__contains=category).order_by('-created_on') context = { "category": category, "posts": posts } return render(request, "list_category.html", context) class ListPostView(generic.ListView): model = Post context_object_name = 'posts' template_name = 'list_post.html' def get_queryset(self): queryset = super().get_queryset() queryset = queryset.order_by('-created_on') return queryset class CreatePostView(LoginRequiredMixin, generic.CreateView): model = Post template_name = 'create_post.html' form_class = PostDocumentForm def post(self, request, *args, **kwargs): blog_form = PostDocumentForm(request.POST, request.FILES) if blog_form.is_valid(): categories = Category.objects.create(name=blog_form.cleaned_data['categories']) title = blog_form.cleaned_data.get('title') body = blog_form.cleaned_data.get('body') profile = request.user.profile image = self.get_image(blog_form) instance = Post.objects.create(title=title, body=body, profile=profile, image=image) instance.categories.set([categories]) return HttpResponseRedirect('/blog/') return render(request, 'create_post.html', context={'form': blog_form}) def get_image(self, form): image = form.cleaned_data.get('image') return image class EditPostView(generic.UpdateView): form_class = PostDocumentForm model = Post template_name = 'edit_post.html' success_url = '/blog/' I can't figure out how to update the post so that the categories are updated as … -
get() returned more than one Log -- it returned 2! in class based views django
I am trying to get a blog post where each post has its unique url with the title views.py: from .models import Log, Comments, Like, Solutions from django.views.generic import ListView, DetailView class LogListView(ListView): model = Log template_name = 'log/home.html' context_object_name = 'item' ordering = ['-created'] class LogDetailView(DetailView): model = Log slug_url_kwarg = 'question' slug_field = 'slug' home.html: {% extends 'log/base.html' %} {% block content %} <title> Error logger - Home</title> {% if item %} {%for i in item %} <div class='m-4'> <div class="container main" style="width: 50vw;"> <a class='link' href="{% url 'log-detail' i.slug %}"><h2 >{{ i.title }}</h2></a> <p>{{ i.content }}</p> <p class='small'>{{ i.created }}</p> </div> </div> {% endfor %} {% else %} <h3 class='container mt-4'>No questions to show</h3> {% endif %} {% endblock content %} urls.py: from django.urls import path from .views import LogListView, LogDetailView urlpatterns = [ path('', LogListView.as_view(), name='home'), path('question/<slug:question>', LogDetailView.as_view(), name='log-detail'), ] I am getting an error stating get() returned more than one Log -- it returned 2! Why am I getting this error and what should I do to fix it? It works fine if I use <int:pk> instead of <slug:question> Edit: I found out that there were two slugs with the same title and hence creating … -
How impact to do request on internal API
please need to know how impact to do request by using Requests on an internal API that returns a JSON response. if it has bad impact on the code could you share with me a better approach? views.py class BookingIndex(TemplateView): def get_context_data(self, **kwargs): account = self.request.user.account context = super().get_context_data(**kwargs) response = requests.get(self.request.build_absolute_uri(reverse('booking:list-appointment')) + f'?farmer_id={account.farmer_id}&account_type={account.account_type}') if response.status_code == 200: data = response.json() if data['appointments']: context['appointments'] = data['appointments'] else: context['appointments'] = [] context['message'] = data['message'] return context class ListUserAppointments(View): def get(self, *args, **kwargs): farmer_id = self.request.GET.get('farmer_id') account_type = self.request.GET.get('account_type') payload = {'farmerid': farmer_id} return JsonResponse({'appointments': appointments}) urls.py path('list-appointment', views.ListUserAppointments.as_view(), name='list-appointment') -
Django: Grouping form fields
I would like to group different formfields like in this example: forms.py a = SelectField() a.group = "Testgroup1" b = CheckboxField() b.group = "Testgroup1" c = IntegerField() c.group = "Testgroup2" d = IntegerField() d.group = "Testgroup2" e = CheckboxField() e.group = "Testgroup3" f = IntegerField() f.group = "Testgroup3" And then in the template something like that: {% for group in form %} {{ group }} {% for field in form %} <div> {{ field }} </div> {% endfor %} {% endfor %} I would like to have a result like that: enter image description here Could someone give my alittle advise how to do that? Thank you in advance. -
Django ORM - How to optimize query for aggregating SUM from different models?
I need to fetch data which contains the total earnings of users within a given date range (from_date and end_date). For example, given from_date=2020-01-01 and end_date=2020-01-07, user 'A' user has a total earnings of 1,000 on 2020-01-01, and then user 'A' has a total earnings of 20,000 on 2020-01-07, the output should be 19,000 since 20000 - 1000 = 19000. In my system, a User model is foreign key with Account model, and a user can have multiple accounts. An AccountModel is foreign key (one is to one) with AccountBonus model, which contains different bonuses that needs to be aggregated in order calculate the total earnings of each user. AccountBonus model inherits the package django-simple-history (https://django-simple-history.readthedocs.io/en/latest/), which creates a new row of data whenever AccountBonus is updated with datetime. Another model is foreign key with Account model which also needs to be aggregated for the total earnings which is AdsCommission model. This is what I'm currently using as a query for this, but it seems like it is too slow even if I have paginator class LIMIT and OFFSET implemented. How can I optimize this query further more? users = User.objects.exclude(groups__name__in=[UserGroups.Admin]) earnings_start = Subquery(AccountBonus.history.filter( Q(history_date__date__gte=from_date) & Q(account__user__pk=OuterRef('id')) ).order_by("history_date")[:1].annotate( total_earnings=Sum(F('itoken_plus_bonus') + … -
Merge two Querysets in django that get annotated
I have a model "Shift" for guards schedule program I do annotation on two django queryset to create status column for night and day shifts night_shift=Shift.objects.filter(nightـguard__guards__pk=self.request.user.pk).annotate(status=Value("night", output_field=CharField())) day_shift=Shift.objects.filter(dayـguard__guards__pk=self.request.user.pk).annotate(status=Value("day", output_field=CharField())) but when i merge this two queryset with code below my_shift=(day_shift | night_shift).distinct() The annotation field "status" that i create did not work very well and all status get to "day" what is the solotion ? -
Django - Check if file entry exists at one of X tables
I need to check if a file field is given at one of 5 different models, how can I do that (preferably in one statement)? file = models.CharField(verbose_name=_("Filename Descriptor"), blank=False, null=False, editable=False, max_length=255, unique=True) So basically I want to check if the file already exists in one of these 5 models/tables Thanks in advance -
How to pass the value of console.log to django views?
I have seen so many responses but none of those correspond to my needs. Basically I am trying to get the value of an href through JavaScript and I need to pass that to my django views, when I do a console.log this is the output that I am getting http://localhost:8000/#vert-tabs-Personal localhost:8000:316:21 #vert-tabs-Personal localhost:8000:317:21 http://localhost:8000/#vert-tabs-Career localhost:8000:316:21 #vert-tabs-Career localhost:8000:317:21 http://localhost:8000/#vert-tabs-Finances localhost:8000:316:21 #vert-tabs-Finances And here is the script that triggered the output so far <script> $(".nav-link").on('click', function(e){ console.log(e.target.href); console.log(e.target.hash); }); </script> Now What is the best way to get the e.target.hash value passed to my django views. I am thinking of jquery or ajax but honestly I don't know. Any help would be appreciated. Thank you in advanced... -
Raw query not returning any results using Django MySQL
I'm trying to run a query in Django. For this project, I use two different connectors: MariaDB and Django's MySQL default connector In the local server, I use the MariaDB connector (everything works fine) and in the staging server, I use MySQL (everything works ok except this query). I guess that the error will be in the syntax, but checking the official Django documentation I have not seen anything unusual. MariaDB -> Works ok and returns results. MySQL -> Does not return any results (the database is the same for both local and staging servers, same content, same table, exactly identical copies of each other). MySQL (not returning any results): from django.db import connection def get_data(variant): results = [] cursor = connection.cursor() cursor.execute("SELECT b.spec_id, b.h_loss, c.gen_type FROM `db-dummy`.spec_gen_data c JOIN `db-dummy`.gen_info a ON a.record_id = c.gen_id JOIN `db-dummy`.spec_data b ON b.record_id = c.spec_id WHERE b.h_loss = 1 AND (a.ref_gen = %s OR a.detail_ref_gen = %s) AND c.gen_type BETWEEN 1 AND 5 ORDER BY a.gen_name;", ('{}%'.format(variant),'{}%'.format(variant),)) columns = [column[0] for column in cursor.description] results = [] for row in cursor.fetchall(): results.append(dict(zip(columns, row))) return results MariaDB (working): import mariadb def get_data(variant): results = [] conn = mariadb.connect( user="user", password="password", host="localhost", database="db-dummy") cursor … -
Can I access others MySQL database in Python Django without having access to its models?
I have this connection to MySQL Workbench database. The thing is, the database and tables isn't made by my django project so I don't have any access to its class models. Is there any way I can add, update or delete in the database tables? tables: TestTable1, TestTable2, TestTable3 `` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': 'root', 'PASSWORD': '1234', 'PORT': 3306, 'HOST': '127.0.0.1', 'OPTIONS': { 'charset': 'utf8mb4', 'use_unicode': True, }, } } `` -
Django TimeField Widget change on admin panel
I'm working with models.TimeField model which will be shown in admin panel and django time fields is uncomfortable. It offers Now, Midnight, Noon keywords. how can i change that, how can i change them to detailed timedeltas? Like this -
Getting an Aggregate Value from a Many-to-Many Field inside a Serializer
We have an API endpoint that generates a response. However, we would like to aggregate some of the data and add an additional field to the serializer. { "id": 61, "not_owned_value": # This is what we're trying to get (Aggregate best_buy_price from not_owned_inventory PlayerProfiles) "not_owned_inventory": [ # PlayerProfile objects "29666196ed6900f07fc4f4af4738bffe", "0ff73ca20cd787c5b817aff62e7890da", "99d4eaef9991695d7ad94b83ad5c5223", "6fcabe9f9c8a95980923530e7d7353a7", "80b34c84a6e5ed25df112c11de676adc", "0a4c5b96474f0584519d1abc4364d5a2", "9ed1f55ac4f3b402b1d08b26870c34a6", ] } Here is the models.py class PlayerProfile(models.Model): card_id = models.CharField(max_length=120, unique=True, primary_key=True) name = models.CharField(max_length=120, null=True) class PlayerListing(models.Model): player_profile = models.OneToOneField( PlayerProfile, on_delete=models.CASCADE, null=True) best_buy_price = models.IntegerField(null=True) class InventoryLiveCollection(models.Model): not_owned_inventory = models.ManyToManyField(PlayerProfile, related_name="not_owned_inventory") Here is the serializer.py class InventoryLiveCollectionSerializer(serializers.ModelSerializer): not_owned_inventory = PlayerProfileAndListingForNesting(read_only=True, many=True) class Meta: model = InventoryLiveCollection fields = ( 'id', 'date', 'not_owned_value', # Trying to get this 'not_owned_inventory', ) How can I aggregate the best_buy_price of the player_profile objects that belong to a specific InventoryLiveCollection__not_owned_inventory? -
Not getting correct PRIMARY KEY
After going to the profile link: http://127.0.0.1:8000/basic_app/profile/3/ Then trying the link: http://127.0.0.1:8000/basic_app/profile/2/ It is working. So there must be some issue with primary key. And I figured out that this is happening after creating a superuser. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. BLOOD_CHOICES = ( ('o+', 'O+'), ('o-', 'O-'), ('a+', 'A+'), ('a-', 'A-'), ('b+', 'B+'), ('b-', 'B-'), ('ab+', 'AB+'), ('ab-', 'AB-'), ) class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # additional last_date = models.DateField(blank=False) contact_no = models.CharField(max_length=15, blank=True, null=True) blood_group = models.CharField( max_length=4, choices=BLOOD_CHOICES, default='o+') def __str__(self): return self.user.username forms.py from django import forms from django.contrib.auth.models import User from .models import UserProfileInfo class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('first_name', 'last_name', 'username', 'email', 'password') widgets = { 'first_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder':'First Name'}), 'last_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Last Name'}), 'username': forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Choose an Username'}), 'email': forms.EmailInput(attrs={'class': 'form-control', 'placeholder':'Your Email'}), 'password': forms.PasswordInput(attrs={'class': 'form-control', 'placeholder':'Your Password'}) } class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('contact_no', 'blood_group', 'last_date') widgets = { 'contact_no': forms.NumberInput(attrs={'class': 'form-control', 'placeholder':'Your Personal Phone Number'}), 'blood_group': forms.Select(attrs={'class': 'form-control', 'placeholder':'Your Blood Group'}), 'last_date': forms.DateInput(attrs={'class': 'form-control', 'placeholder':'The last date you donated blood'}), } basic_app/urls from django.urls import path from … -
How to implement multiple filters Django?
I want to add such filters to my internet shop: Color: red blue green Material: plastic wood metal where each of points is a checkbox, color and material are fields of some Django model. For example if i'm looking for red or blue toys with plastic material, i'll find it in such way: filtered = SomeModel.objects.filter(material=plastic, color=red, color=blue) But how to filter it dynamically?(if i have many filters) -
Python application on server [closed]
I have a question: I work mostly with java and with servers such as jboss or weblogic and now I would need some advice on which server would be optimal for building an application with python. Which server is the best and why? Thank you in advance. -
How to trigger Django signals only once on multiple receivers
I am looking for a way to do the following (keep in mind, if this is not possible with signals, I'm happy if you know any alternatives) But let's say we have a signal defined as follows: from django.dispatch import receiver @receiver(post_save, sender=Model1) @receiver(post_save, sender=Model2) @receiver(post_save, sender=Model3) def my_signal_handle(sender , **kwargs) # some code here Now, all 3 models (Model1, Model2, Model3) are related. So when creating a new resource, one can provide all informations, which results in all 3 tables being saved with a new row. I would love to only trigger my_signal_handle once in that case. So basically per transaction. Also, when updating for example, one could only update, let's say Model3, and in that case I still want this signal to run. So goal is -> No matter how many models are affected, I want to run this signal once. Hope it makes sense, happy to clarify better if needed. I was looking at adding a signal per transaction or something, but couldn't find exactly what I need. -
how to use drf-yasg to import a swagger.yml file?
I tried django-swagger-ui but not work python 3.9.5 django 3.2.3 drf-yasg 1.20.0 -
Problem with Google OAuth and Django: "Credentials in post body and basic Authorization header do not match"
I tried to arrange auth via Google in my Django app following this guide (there other identical examples over the internet). It didn't work and I tried to debug as suggested here. That gave me error as follows: {'provider_id': 'google', 'error': 'unknown', 'exception': 'Error retrieving access token: b\'{\\n "error": "invalid_request",\\n "error_description": "Credentials in post body and basic Authorization header do not match"\\n}\'', 'extra_context': {}} I have a feeling that this is somehow related to the fact that before I used default auth that comes with Django with this app. Any clue to further debug would be appreciated. -
Python Django API task
I need help to build API using django and DRF. API for an online bookstore with the ability to place an order for registered users. An hour after order completed send 'Thanks for purchase' email to that user -
Django validating time slot
This is my models to store availability of particular time when a new booking there class TimeSlot(models.Model): day = models.ForeignKey( Day, on_delete=models.CASCADE, related_name="time" ) booking = models.ForeignKey( Booking, on_delete=models.CASCADE, related_name="time" ) start_hour = models.TimeField() end_hour = models.TimeField() class Meta: unique_together = [('end_hour', 'start_hour',)] def clean(self): pass Currently it's allowing booking even those are considered as duplicate in terms of end_hour and start_hour. I want to prevent the slot, so that no new booking shouln't placed between a range that already booked. Can anyone know how to do it with the range? -
How to get the domain name of my React frontend which is making a request to my Django backend?
I want Django to print the domain name of the React frontend which is making a request to my Django server. get_current_site gives the domain name of the Django server. So how can I get the domain name of the site, making a request to the Django server?