Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
DJANGO REST FRAMEWORK perform_create dont work
The code in the perform_create function isn't working. It says that POST method is done, but nothing saves. Maybe create or validate functions in serializer confronts with it? class SaveStats(CreateAPIView): queryset = Stats.objects.all() serializer_class = StatisticsSerializer def perform_create(self, serializer): print("checking") serializer.save() def post(self, request, *args, **kwargs): if (int(request.POST['views']) < 1) or (int(request.POST['clicks']) < 0) or (int(request.POST['cost']) < 0): return JsonResponse({"wrong input": "try again"}, status=status.HTTP_400_BAD_REQUEST) return JsonResponse({"status": "Stats saved"}, status=status.HTTP_200_OK) class StatisticsSerializer(serializers.Serializer): date = serializers.DateField() views = serializers.IntegerField() clicks = serializers.IntegerField() cost = serializers.IntegerField() def create(self, validated_data): return Stats(**validated_data) def update(self, instance, validated_data): instance.date = validated_data.get('date', instance.date) instance.views = validated_data.get('views', instance.views) instance.clicks = validated_data.get('clicks', instance.clicks) instance.cost = validated_data.get('cost', instance.cost) return instance def validate(self, attrs): if (attrs['views'] < 1) or (attrs['clicks'] < 1) or (attrs['cost'] < 1): raise serializers.ValidationError({"wrong input": "try again"}) print(attrs['views']) return attrs -
Date math with Django SQL Explorer
I have implemented Django SQL Explorer on a project and am attempting to build a query that will pull entries between today's date and 12 months prior to today's date, but I'm having a difficult time figuring out how SQL Explorer does date math. So far, about the only thing I've been able to discover is that SQL Explorer uses current_date for today's date. So: SELECT current_date; returns: 2021-10-02 I've tried using the MySQL implementation (since that's the database my project is using): SELECT current_date - INTERVAL 12 MONTH; returns: near "12": syntax error About the closest I've been able to come is some very simple math that just work on the year and strips all the rest of the date information away: SELECT current_date - 1; returns: 2020 Can anyone please help me figure out how to return the date 12 months prior to today's date in Django SQL Explorer? SELECT current_date SELECT current_date - [12 MONTH]; should return: 2021-10-02 2020-10-02 Thanks in advance! -
Why I am getting Django page not found error?
I am not understanding why I am getting this Page not found (404) Raised by:django.views.static.serve here is my code: app views.py: class SESmail(TemplateView): template_name = 'mail/account_confirmation.html' app urls.py urlpatterns = [ path('confirmmail/',SESmail.as_view(), name='confirmmail'), ] root urls.py urlpatterns = [ path('admin/', admin.site.urls), #my others url.... path('', include('sesmail.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py: INSTALLED_APPS = [ .... 'sesmail', ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) I am not understanding why I am getting this error? I added app name in my settings.py and also added url configuration properly in app urls.py and root urls.py. Where I am doing wrong? -
How to get data from views.py
There is one table called Option, and in order to save the value of Option 1, Option 2, views designated Option 2 and saved it to the table. What should I do to retrieve this saved data? There is one table called option, and it is difficult to recall because option 2 is not a table name. How can I solve this problem? views.py if request.method == "POST": form = OptionForm(request.POST) if form.is_valid(): option2 = Option() option2.name = form.cleaned_data['second_option'] option2.product_code = product option2.save() I wrote it in this way and received it from the view. {% for option in option_object %} {% if option.option_code.option_code == value.option_code %} {% if option.product_code == product %} <select type="text" class="form-control" id="optionSelect"> <option value="none">옵션을 선택하세요.</option> <optgroup label="{{option.name}}"> {% endif %} Here, I want to receive the value of option 2 stored in the option table. -
Django raiting for shop-item
I have a model in which I have a field rait = models.PositiveIntegerField (default = 0). Maximum 5 stars. For example, I now have a product that has 4 ratings, ie 4 gold stars 1 white. This should be done in the template django. How to do it? -
Unexpected keyword argument
Here is my model Model from Account.models import User from django.db import models class Seller(models.Model): seller = models.OneToOneField(User, on_delete = models.CASCADE) email = models.EmailField(max_length = 90, unique = True) country = models.CharField(max_length = 60) phone = models.CharField(max_length= 20, unique = True, blank = True, null = True) address = models.TextField() zipcode = models.CharField(max_length = 10) form from django import forms from django.contrib.auth.forms import UserCreationForm from django.db import transaction from .models import Seller from Account.models import User class SellerCreationForm(UserCreationForm): name = forms.CharField(required = True) email = forms.EmailField(required = True) phone = forms.CharField(required = False) country = forms.CharField(required = True) address = forms.CharField(required = True) zipcode = forms.CharField(required = True) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_seller = True user.name = self.cleaned_data.get('name') user.save() seller = Seller.objects.create(user=user) seller.email = self.cleaned_data.get('email') seller.phone = self.cleaned_data.get('phone') seller.country = self.cleaned_data.get('country') seller.address = self.cleaned_data.get('address') seller.zipcode = self.cleaned_data.get('zipcode') seller.save() return user views from django.shortcuts import render, redirect from django.views.generic import CreateView from .forms import SellerCreationForm from django.contrib.auth.forms import AuthenticationForm from Account.models import User class RegisterSeller(CreateView): model = User form_class = SellerCreationForm template_name = 'registration/registerseller.html' def form_valid(self, form): user = form.save() login(self.request, user) return redirect('/') I tried to create a project with multiple users types … -
Is ther any way to split the uploaded file name extension and display it in diffrent html element?
I uploaded files from the index.html page and extensions are .jpg, .pdf, Docx, and mp4 into my project and able to display only jpg files and used scr for that and I need to use if else condition according to extension and display in HTML elements. so that I need to split the file name and get that extension and accordingly used if-else condition. I am not able to split files for the index.html page using split(). please help and all code included below index.html {% for i in phone %} <!-- <img src="{{i.document.url}}" alt="Girl in a jacket" width="200" height="200; display: flex;"> --> <h1>{{i.document.url}}</h1> <h2>{{i.document.path}}</h2> {% endfor %} views.py def Home(request): if request.method == 'POST': if len(request.FILES) == 0: return redirect("/drive") else: photo = request.FILES['doc'] Upload.objects.create(document = photo) return redirect("/drive") if request.method == "GET": photo = Upload.objects.all() context = { 'phone': photo } return render(request, 'Home.drive.html', context) modles.py from django.db import models # Create your models here. class Upload(models.Model): document = models.FileField(upload_to='documents') Note: Waiting for positive response and please i am beginner so that i need full code instead of hint. -
redirect to created object after form submission
Goal: To redirect to the 'build log' after the form is submitted view: @login_required def buildLogCreate(request, pk): post = Post.objects.get(pk=pk) if request.user.id != post.author_id: raise PermissionDenied() currentUser = request.user form = BuildLogForm() if request.method == 'POST': form = BuildLogForm(request.POST, request.FILES) if form.is_valid(): formID = form.save(commit=False) formID.author = request.user formID.post_id = pk formID.save() return redirect('build-log-view', formID.pk) context = { 'form':form, } return render(request, 'blog/buildlog_form.html', context) The url structure setup is post->buildlog(subpost) ie: /post/118/build-log/69/ The form gets successfully submitted but I get the error NoReverseMatch at /post/118/build-log-form/ Reverse for 'build-log-view' with arguments '(69,)' What confuses me is the url is still on the post form and not build log view but the argument 69 is the correct build log id so it should be working. url to be redirected to path('post/<int:pk>/build-log/<int:pkz>/', views.BuildLogDisplay, name='build-log-view'), -
Best Practice to run Django/Vue application on Production
I have a Django/Vue app and when I am developing, I run two different servers, one for Django on port 8082 and one for Vue with yarn serve on port 8080. I want to deploy this application to AWS. I created dist files with npm run build and I configured Django to access templates in this dist directory and in my views.py I routed to this static html files generated by build process. Is it a good practice to run Django/Vue apps on production or should I be running two different servers for production as well? -
How to change user based on their personal value using python
I have a table in my models named as Referralcode ReferralActiveUser class ReferralActiveUser(models.Model): user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True) user_active = models.BooleanField(default=False) referral = models.ForeignKey( User, related_name='comp_active_user', on_delete=models.SET_NULL, null=True, blank=True) I want to loop over this table and change the status of user based on their pv(personal value) but I'am confused or I don't know how to do this. What I want is assume this is a users in my table [ { "id": 1, "user": 2, "user_active": "0", "referral_by": 1 }, { "id": 2, "user": 3, "user_active": "0", "referral_by": 2 }, { "id": 3, "user": 4, "user_active": "0", "referral_by": 2 }, { "id": 4, "user": 5, "user_active": "0", "referral_by": 2 } ] here "user":1 is first user who started this program and all other users are child of "user":1 it's like tree structure and I want to loop over user and check each user pv and change it's status like this referral_users = ReferralActiveUser.objects.all() min_value=20 for user in referral_users: if user.pv >= min_value: user.status = True user.save() else: # Find users referred by this user inactive_users = referral_users.filter(referral_by=user.user) for j in inactive_users: j.referral_by = # want to add parent of this user j.save() user.status = False user.save() INFO … -
Change chunk_vendors/app js file import urls in public index.html in a Django/Vue application
I want to serve my chunk vendors or app js files under static/js/chunk_vendors.js rather than /js/chunk_vendors.js because I want to point to the dist directory generated for production build by npm run build and my static url in Django is /static so every static file should be access via a url starting with /static. But npm run build generates an html file with chunk_vendors.js url /js/chunk_vendors.js. How can I tell Vue Cli to generate html files with /static prefix?