Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use Bootstrap by link or install in enviroment (pip install django-bootstrap3) in Django
I'm newbie of Django. I just find out there is 2 ways of loading bootstrap in Django with: 1. <link rel="stylesheet" href="" crossorigin="anonymous">: For CDN or local file. 2. Installing in enviroment with (pip install django-bootstrap3): Loading by {% load bootstrap3 %} Which way do you prefer in this case? Thank you so much. -
unsupported operand type(s) for -: 'decimal.Decimal' and 'float' | Django
Sometimes it works fine and sometimes it displays the error. ADMIN models.py class BarterAdminWallet(models.Model): admin_wallet_id = models.BigAutoField(primary_key=True) admin_wallet_balance = models.DecimalField(max_digits=60, decimal_places=2, default = 0.00) admin_tokens_assigned = models.DecimalField(max_digits=60, decimal_places=2, default = 0.00) admin_tokens_earned = models.DecimalField(max_digits=60, decimal_places=2, default = 0.00) admin_tokens_bought = models.DecimalField(max_digits=60, decimal_places=2, default = 0.00) class BarterAdminActionsTokens(models.Model): action_tokens_id = models.BigAutoField(primary_key=True) account_activation_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) newsletter_subscription_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) name_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) surname_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) add_languages_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) mobile_phone_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) avatar_image_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) profile_description_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) dob_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) linkedin_profile_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) facebook_profile_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) address_1_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) address_2_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) USER views.py adminwallet = BarterAdminActionsTokens.objects.get() registration_tokens = adminwallet.account_activation_tokens adminwallet = BarterAdminWallet.objects.get() adminwallet.admin_wallet_balance = adminwallet.admin_wallet_balance - float(registration_tokens) adminwallet.admin_tokens_assigned = adminwallet.admin_tokens_assigned + float(registration_tokens) adminwallet.save() token_status.user_account_activation_token_status = "Awarded" token_status.save() CODE EXPLANATION All fields related to maths are of the decimal. Same code, When calculating sometimes calculates perfectly and show error on some occasion. Also this code is working absolutely fine in other … -
Is this possible: Django TestCase + async + db calls?
I have a problem when use db calls in async methods of Django TestCase. I have an error: "psycopg2.InterfaceError: connection already closed". I know that I can use TransactionTestCase, but it's slow. Is there solution for this using Django TestCase? -
Django Rest Frame work, "Method \"GET\" not allowed.", but in the code, POST is requested
I was watching a tutorial to create a web app, using React in frontend and Django in backend therefore using Django Rest Framework I copied everything and even my code looked the same, but I am getting this HTTP 405 status and prompting that GET method is not allowed, I know it's not allowed because I haven't requested GET method, I requested POST method Here's my views.py : from django.shortcuts import render from rest_framework import generics, status from .serializers import RoomSerializer, CreateRoomSerializer from .models import Room from rest_framework.views import APIView from rest_framework.response import Response class RoomView(generics.ListAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer class CreateRoomView(APIView): serailizer_class = CreateRoomSerializer def post(self, request, format=None): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() serializer = self.serailizer_class(data=request.data) if serializer.is_valid(): guest_can_pause = serializer.data.get('guest_can_pause') votes_to_skip = serializer.data.get('votes_to_skip') host = self.request.session.session_key queryset = Room.objects.filter(host=host) if queryset.exists(): room = queryset[0] room.guest_can_pause = guest_can_pause room.votes_to_skip = votes_to_skip room.save(update_fields=['guest_can_pause', 'votes_to_skip']) return Response(RoomSerializer(room).data, status=status.HTTP_200_OK) else: room = Room(host=host, guest_can_pause=guest_can_pause, votes_to_skip=votes_to_skip) room.save() return Response(RoomSerializer(room).data, status=status.HTTP_201_CREATED) return Response({'Bad Request': 'Invalid data...'}, status=status.HTTP_400_BAD_REQUEST) And here's my urls.py : from django.urls import path from .views import RoomView, CreateRoomView urlpatterns = [ path('room', RoomView.as_view()), path('create-room', CreateRoomView.as_view()), ] I read somewhere that it has something to do with the URL so here's … -
DsTProductAttributes.product must be a DsTProductCompany instance Django
this would be my first post ever on Stack Overflow, I am asking a question that apparently has been already answered but I can't find the solution for my specific case. I am a beginner in Django so please don't be too hard. Thank you very much in advance even for reading my post. Any advice or directions will be highly appreciated. A. I am getting this error: Cannot assign "2": "DsTProductAttributes.product" must be a "DsTProductCompany" instance. Here is the relevant code from models.py class DsTProductAttributes(models.Model): product_attribute_id = models.BigAutoField(primary_key=True) product = models.ForeignKey('DsTProductCompany', models.DO_NOTHING) attribute = models.ForeignKey(DsTAttribute, models.DO_NOTHING) value = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) dw_load = models.DateTimeField(blank=True, null=True) dw_deleted = models.IntegerField(blank=True, null=True) dw_deleted_time = models.DateTimeField(blank=True, null=True) dw_last_touch = models.DateTimeField(blank=True, null=True) dw_last_touch_by = models.CharField(max_length=200, blank=True, null=True) class Meta: managed = False db_table = 'ds_t_product_attributes' class DsTProductCompany(models.Model): product_id = models.BigAutoField(primary_key=True) product_code = models.CharField(max_length=200, blank=True, null=True) description = models.CharField(max_length=200, blank=True, null=True) ean_code = models.CharField(max_length=200, blank=True, null=True) dw_load = models.DateTimeField(blank=True, null=True) dw_deleted = models.IntegerField(blank=True, null=True) dw_deleted_time = models.DateTimeField(blank=True, null=True) dw_last_touch = models.DateTimeField(blank=True, null=True) dw_last_touch_by = models.CharField(max_length=200, blank=True, null=True) class Meta: managed = False db_table = 'ds_t_product_company' Here is the relevant code from forms.py class ProductAttributesForm(ModelForm): def __init__(self, *args, **kwargs): super(ProductAttributesForm, self).__init__(*args, **kwargs) attribute = DsTAttribute.objects.all() … -
Django model UniqueConstraint problem, I want category parent not to be the current instance
Hey i have problem with the categories parent. As you can see in the code i have category with a foreign key pointing to it self. Now i dont want a instance of category to be a child of itself. So far i have tried unique_together and UniqueConstraint but that didn't work. class Category(models.Model): parent = models.ForeignKey('self', related_name="children", on_delete=models.CASCADE, blank=True, null=True) #'self' to indicate a self-reference. title = models.CharField(max_length=100) slug = AutoSlugField(populate_from='title', unique=True, null=False, editable=True) logo = models.ImageField(upload_to="catlogo", blank=True, null=True, help_text='Optional') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: #enforcing that there can not be two categories under a parent with same slug verbose_name_plural = "categories" constraints = [ models.UniqueConstraint(fields=['slug', 'parent'], name='unique_parent') ] -
Css file not loading on Python Anywhere
I have recently begun making a Django project on PythonAnyhwere. I have followed the entire tutorial provided by Django for including static files on the project. I have observed the programs work fine on a site with http, but does not work on a site with https. What could be the reasons and how can I overcome this problem? -
This backend doesn't support absolute paths
please I need urgent help on this: I am having This backend doesn't support absolute paths when trying the login. bellow is my codes models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') role = models.CharField(default='user', max_length=20) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.width > 280 or img.height > 280: output_size = (280, 280) img.thumbnail(output_size) img.save(self.image.path) settings.py STATICFILES_DIRS = [ BASE_DIR / "static", ] STATIC_ROOT = BASE_DIR / "staticfiles-cdn" # in production, we want cdn MEDIA_ROOT = BASE_DIR / "staticfiles-cdn" / "media" from .cdn.conf import * # noqa in django-project folder>cdn i have backends.py from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticRootS3Boto3Storage(S3Boto3Storage): location = 'static' class MediaRootS3Boto3Storage(S3Boto3Storage): location = 'media' conf.py import os AWS_ACCESS_KEY_ID=os.environ.get("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY=os.environ.get("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME=os.environ.get("AWS_STORAGE_BUCKET_NAME") AWS_S3_ENDPOINT_URL="my digitalocean endpoint" AWS_S3_OBJECT_PARAMETERS = { "CacheControl": "max-age=86400" } AWS_LOCATION = "https://{AWS_STORAGE_BUCKET_NAME}.fra1.digitaloceanspaces.com" DEFAULT_FILE_STORAGE = "appname.cdn.backends.MediaRootS3Boto3Storage" STATICFILES_STORAGE = "appname.cdn.backends.StaticRootS3Boto3Storage" Thank you -
How to undo changes in a model in Django-oscar
I tried adding a field in AbstractProduct model and in doing so, I was successful, but now that field is being presented whenever I go to product detail view as an empty field and which is not desirable. and in the following image the state of the origin is the issue which I am facing..which can't be left blank so no one can place order.. How to solve this ?? -
reduce the time complexity of the this Django queryset parse function
This function takes a Django QuerySet table, fields (the column names of the table as a list), and a name (string). It checks to see if the name is in the column fields. if the name is in the fields, it will add the sum of the field to a list of sums and return that list as a dictionary after enumerating it. I noticed that it's running in o(n^2) (I think) and would like to reduce its time complexity. #returns an enumerated dict of sums of the fields in the table #table is a Django QuerySet, fields is a list of fields, name is a string def fieldSum_to_list(table, fields, name) -> dict: sum = [] name = name.lower() for field in fields: if name in field.name: if (None in table.aggregate(Sum(field.name)).values()): # value = 0 # sum.append(value) -> what I was doing before pass pass else: col_sum = table.aggregate(Sum(field.name)).get( str(field.name) + '__sum') sum.append(col_sum) diction = dict(enumerate(sum)) if (len(diction) == 1): return diction[0] return dict(enumerate(sum)) The program slowed down after adding this line: if (None in table.aggregate(Sum(field.name)).values()): is what slowed down the program as it was much faster before, I think that this condition is acting as a loop. In essence, … -
response returning null for no reason rest framework
I getting null in return when in fact i have data in the database, I don't where the problem lies, pretty frustrated by this, if I am not calling is_valid then it throws an assertion error but anyways data is still empty class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' View @api_view(['GET']) def get_data(request): product_data = Product.objects.all() print(product_data) serialized_data = ProductSerializer(data = product_data, many =True) data = {} if serialized_data.is_valid(): data['status']='valid' else: data['status']='not valid' return Response(data) -
Issue with trying to upload single images across multiple different HTML form inputs in Django without Django Forms
I am trying to create digital business cards creating a custom visual editor with different html form inputs to upload different images like profile, background, logo etc., without Django Forms. I am able to get one working with the Django backend that uses to fields one for the image name and the other is image url. I was hoping to replicate this process for each image until I get to the slider section. I am still working on it so the design is not complete and using test data. I have included an image for reference of what I am trying to accomplish as silly as the test data is on there. urls.py from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ url(r'^icards/icard/list/$', views.icard_list, name='icard_list'), url(r'^icards/icard/add/', views.icard_add, name='icard_add'), url(r'^icards/icard/edit/(?P<pk>\d+)/$', views.icard_edit, name='icard_edit'), # url(r'^icards/icard_details/(?P<pk>\d+)/$', views.icard_details, name='icard_details'), url(r'^icards/icard/delete/(?P<pk>\d+)/$', views.icard_delete, name='icard_delete'), # url(r'^icards/editor_base/', views.editor_base, name='editor_base'), url(r'icards/', views.icards, name='icards'), views.py def icard_edit(request, pk): print("Icard Edit Loaded") if len(Icard.objects.filter(pk=pk)) == 0: error = "Icard Not Found" return render(request, 'back/error.html', {'error': error}) icard = Icard.objects.get(pk=pk) print("Icard get function works") if request.method == 'POST': print("func: Get Data Works") name = request.POST.get('name') category = request.POST.get('category') style = request.POST.get('style') title = request.POST.get('title') logo … -
How to change the default labels of a ForeignKey field whose form's widget is a RadioSelect
In my Django app, I have this form: from django import forms from main.models import Profile class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['picture'] widgets = { 'picture': forms.RadioSelect(), } By default, the labels of the picture field within the template are generated according to the __str__() method of the Picture model. That's because the picture field on my Profile model is actually a ForeignKey field to a Picture model. However, the value returned by that __str__() method doesn't make much sense in this particular template, and changing it is not possible because it's being used elsewhere. Therefore, is there a way I might change the default labels for the picture field of my ProfileForm? For instance, changing from the __str__()'s default picture.src + ' (' + picture.description + ')' to something like picture.description only? I have checked what the docs had to say regarding the label_from_instance, but I didn't understand how to apply it. In fact, I couldn't even understand if that would be a solution for this case. Some similiar questions here on Stack Overflow also mentioned that link of the docs, but the questions's forms were slightly different than mine, and I ended up not … -
I'm get a report of error ') expected' in django
I have a django website, and in my html I get these in my visual studio editor, I don't know why. Basically everything works, but I have some problem with flex, sometimes it doesn't work, also I don't know if it is connected. Any idea what is this? This is home.html <section class="welcome_area clearfix" id="home" style="background-image: url({% static 'img/bg-img/welcome-bg.png' %})"> Same in base.html <div class="mosh-breadcumb-area" style="background-image: url({% static 'img/core-img/breadcumb.png' %})"> -
Django-allauth Password Reset Email not sending
I have a weird problem where my allauth email will send to verify new user email address but no email will send for resetting the password. I have checked the gmail account from which the email should be sent but it only shows the verification emails as sent, its as though nothing is being done when the user clicks the reset password button on the template side. I'm not sure what I am missing.. My template <body class="login-page container-fluid"> <div class="row vygr-login"> <div class="user_card"> <div class="container-fluid h-100"> <div class="row h-100"> <div class="form_container col vygr-signup-container"> {% load i18n %} <form class="signup" method="POST" action="{% url 'account_login' %}"> {% if user.is_authenticated %} {% include "account/snippets/already_logged_in.html" %} {% endif %} <p class="registration-element" style="font-size: 2rem;">{% trans "Trouble Logging In?" %}</p> <p class=" registration-element">{% trans "Enter your email and we'll send you a link to get back into your account." %}</p> <form method="POST" action="{% url 'account_reset_password' %}" class="password_reset"> {% csrf_token %} {% for field in form %} {{ field }} {% endfor %} <input class="signup-button" type="submit" value="{% trans 'Reset My Password' %}"> <p class="" style="text-align: center;">{% blocktrans %}Please contact us if you have any trouble resetting your password.{% endblocktrans %}</p> </form> </div> </div> </div> </div> </div> … -
Can't respond to AJAX call on context processor
I'm developing a website on DJANGO and I'm facing a problem: I have a button in my website that, when triggered, sends an AJAX POST request. Since this button is in multiple places of my website, i've decided to receive the AJAX request on the context processor file of my backend. This is what the request in the frontend looks like: $.ajax({ method: 'POST', headers: {'X-CSRFToken': csrftoken}, data: { "requested_item": requested_item }, dataType: "json", success: function() { // Handle success } }); And this is what the request handling looks like in the backend: requested_item = request.POST.get('requested_item') if requested_item != None: # Handle valid request return JsonResponse({'success': True}) The thing is, the return JsonResponse({'success': True}) isn't working, it throws this error: File "*path*\virtual-env\lib\site-packages\django\template\context.py", line 244, in bind_template updates.update(processor(self.request)) ValueError: dictionary update sequence element #0 has length 17; 2 is required The data arrives without any trouble from the frontend to the backend, but I can't seem to respond. I'm handling multiple AJAX requests the same way in my backend and responsing without problems, but this is the only one I handle in the context processor, so I'm sure there's something I'm missing. Thanks! -
different permissions in viewset, is it possbile?
If we have ModelViewSet, can we set different permissions per action? List for all, Create only for authenticated users, Update for Owners and Delete only for Admin? Or it's better to have some separated generics views? -
Django Unsubscribe with EmailMultiAlternatives
I'm trying to create an unsubscribe link for a newsletter and I have an email address and a unique uuid to use to identify each subscriber. My question is how can I pass the unsubscribe link to the template to be rendered without rendering the template over and over again for each subscriber. I'd like to render the template once and then send the same rendering to each subscriber, but still include the unique unsubscribe link (unsub_link below) in the template. What's the best way to do that? What I have so far is: def send_email(request): email_subs_query = Subscriptions.current.filter(sub_type="thisnewsletter").values('sub_email', 'sub_uuid') if request.method == "POST": message_html = get_template('newsletter/email-template.html') message = message_html.render( { 'email_content': email_content, 'more_content': more_content } ) for d in daily_subs_query: subscriber_email = [d.get('sub_email')] sub_id = [d.get('sub_uuid')] unsub_link = 'https://www.website.com/unsub_email/{}/{}/'.format(subscriber_email, sub_id) email = EmailMultiAlternatives( 'Today's Newsletter', 'template text', 'Newsletter Sender <admin@website.com subscriber_email, ) email.attach_alternative(message, "text/html") email.send() -
Uncaught TypeError: Cannot read properties of undefined (reading 'forEach')
I want to use Youtube API on my project where user can search for videos and it displays search results as the user is typing. I am only familiar with python and django. So, I am using a tutorial to do the JS part to add ajax. Everything in my code is exactly as shown in the tutorial but mine is not working. So my javascript for ajax is: <!-- javascript for ajax--> <script> var delayTimer; $("#div_id_search_form").keyup(function() { clearTimeout(delayTimer); $('#search_results').text('Loading...'); delayTimer = setTimeout(function() { var text = $("#div_id_search_form").val(); $.ajax({ url: '/video/search', data: { 'search_term': text }, dataType: 'json', success: function(data) { var results = ''; $('#search_results').text(''); data['items'].forEach(function(video){results += video['snippet']['title']}); $('#search_results').append(results); } }); }, 1000); }); </script> and this is my views.py file where I use my API: def video_search(request): search_form = SearchForm(request.GET) if search_form.is_valid(): encoded_search_term = urllib.parse.quote(search_form.cleaned_data['search_term']) response = requests.get(f'https://youtube.googleapis.com/youtube/v3/search?part=snippet&maxResults=6&q={ encoded_search_term }&key={ YOUTUBE_API_KEY }') return JsonResponse(response.json()) return JsonResponse({'error': 'Not able to validate form'}) My goal here is not to display youtube videos rightnow. My goal is to simply display 'Loading...' when the user is typing and if the user stops typing for one second it displays whatever the user has typed in the searchbar. So, i guess the problem is … -
Create django user with firebase User UID as id
I use django as a custom backend for firebase project. I want to create users in my django database from firebase credentials and have firebase UUID as my primary key for user in django db. So I have a model for my custom user in django: class CustomUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) UUID from firebase seems to be a random string composed of letters and numbers, while python UUID has so many different formats, that I am confused what format should I use in my case. My goal is to create a user in django with something like that: CustomUser.objects.create( id=uuid.UUID('<<uuid from firebase>>'), username="mikhail", email="email@example.com",...) How do I do that? -
Django / DRF: Serializing QuerySet leads no "No attribute found error"
When I serialize a multi-item queryset, it throws id not found error. Serializing: json_data = SampleSerializer(Sample.objects.all(), many=True) Serializer: class SampleSerializer(serializers.ModelSerializer): sample_id = serializers.SerializerMethodField() class Meta: model = Sample fields = ["sample_id",] def get_sample_id(self, obj): return encoded_id(obj.id) # not found error Model: class Sample(models.Model): objects = SampleManager() id = models.AutoField(primary_key=True) vector_column = SearchVectorField(null=True) class Meta: indexes = (GinIndex(fields=["vector_column"]),) -
URL pattern not being identified by Django
I followed a tutorial by a youtuber known as Mosh, I followed along with his Django tutorial but whenever I enter the URL pattern, it gives me error 404, page not found. This is a screen shot of the explorer tab. I only edited the views.py, products.urls.py and pyshop.urls.py files. views.py: from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse("Welcome to the new products page!") def new(reqest): return HttpResponse("New Products") products.urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index), path("new", views.new) ] pyshop.urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("products/", include("products.urls")) ] -
django ManyToManyField unique
class Building(models.Model): address = models.CharField(max_length=20, primary_key=True) employers = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="employers", blank=True) Suppose n users of model type User and m buildings of model type Building (m << n). I would like in the Admin page to be able to put users into building in the unique way: a user can be in maximum one building. a building can have many employers. It can be empty too. in the Admin page, in the Employers selection widget, in the UPDATE mode, exclude users that belong to another building. In the CREATE mode, show only users without a building. Stack: Django, MySQL. -
Django beginning project admin login error 2021
I have just created my first django project. I was successfully able to make templates and run the server so that I can go on my localhost and view my hello world project! However when going to localhost:8000/admin and logging in (yes I created a super user, also I am using windows 10) it brings me to a page with an error: 'RuntimeError: Model class django.contrib.sessions.models.Session doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.' It also says the same thing in my visual studio debug console. The error only comes up after running the admin page and trying to login which makes sense. I AM AWARE this question is on here from a while go and the solution of adding INSTALLED_APPS = [ ... 'django.contrib.sites', ] SITE_ID = 1 Did not work. Not sure if this is an issue with newer versions of django, but nothing online that I have checked currently has helped resolve this issue. My goal is to use the SQLite database to start actually getting my basic project going, but for the sake of consistency with other users and tutorials I would prefer if this part of the beginner programmed worked. Any … -
Django order by vote percentage
I currently have a post that has upvotes and downvotes. the model looks something like this class Word(models.Model): name = models.CharField(max_length=250) upvotes = models.ManyToManyField(User, blank=True, related_name='threadUpVotes') downvotes = models.ManyToManyField(User, blank=True, related_name='threaddDownVotes') in my views.py I have so far gotten this far from django.db.models import F, Sum words = Word.objects.filter(name__iexact='test').annotate( total_votes=Sum(F('upvotes') + F('downvotes'))).order_by('total_votes') But I'm unsure what to do next to get it to rank by say the one with most upvotes vs downvotes.