Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to check if a manytomany field object exist in detailview template
I want to search in a ManyToManyField in the DetailView. It works fine if a user with the same query exist, but if there isn't a user, i get page not found error. models.py: class agents(models.Model): agent_type = models.ForeignKey(types, on_delete=models.SET_NULL, blank=True, null=True) name = models.CharField(max_length=100) users = models.ManyToManyField(user_models.users, through='user_agent') views.py: class AgentDetailView(LoginRequiredMixin, generic.DetailView): model = models.agents template_name = 'agent/agent_detail.html' def get_queryset(self): query = self.request.GET.get('q') if query: return models.agents.objects.filter(Q(users__user__first_name__contains=query) | Q(users__user__last_name__contains=query) | Q(users__id_number__contains=query) | Q(users__mobile__contains=query)) else: return models.agents.objects.all() agent_detail.html: <h1>name: {{ agents.name }}</h1> <form method="GET" action="" id="searchform"> <input class="searchfield" id="searchbox" name="q" type="text" placeholder="Search..."/> <button name="search" type="submit" value="{{ request.GET.q }}">Search</button> </form> {% if agents.users %} <p><strong>Users:</strong> <br> {% for users in agents.users.all %} <li>{{ users }}</li> <hr> {% endfor %} </p> {% else %} <p>There are no user for this agent in database.</p> {% endif %} -
Cannot oversave model imagefield DJANGO
I'm encountering weird problem with updating image. I do not receive any error, it just doesn;t get saved to the MEDIA_ROOT folder. If I do it manually via admin_site it works. When i'm using the forms, the above happens. views.py: if request.method == "POST": pass_change_form = UserUpdatePasswordForm(data=request.POST, user=request.user) avatar_change_form = UserUpdateAvatar(data=request.POST, files=request.FILES, instance=request.user.profile) if avatar_change_form.is_valid(): avatar_change_form.save() print(avatar_change_form) messages.success(request, 'The avatar has been changed') return redirect('profile') else: messages.warning(request, 'Please fill the fields correctly') return redirect('password-change') forms: class UserUpdateAvatar(forms.ModelForm): class Meta(): model = Profile fields = ["avatar"] models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default="default.jpg", upload_to="profile_avatars") def __str__(self): return f'{self.user.username} Profile' -
Overriding default django project structure
Is it possible to override the default project structure in Django? I'm trying to put all my django apps in a src folder but it seems like it is not that easy. When i try to run my dev server, i get the error "ModuleNotFoundError: No module named 'django_project'". Here is my current Project Structure. -
Django - How to return to default image after users delete their uploaded image?
So I originally had the user create a post in admin and be able to leave image field blank and Django would set a default image. My problem is; If a user uploads an image, then deletes the image, I get an error: The 'image' attribute has no file associated with it. How can I make the default image reappear and specifically come from static folder? My code: urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py # FIXME: If default image is changed to user's upload but then deleted. Make default image reappear. # Recipe Field class Recipe(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='recipes/images/', blank=True) def get_image(self): if not self.image: return f'{settings.STATIC_URL}default.png' return self.image.ur solo.html <h2>{{ recipe.title }}</h2> <h3>{{ recipe.category }}</h3> <h3>{{ recipe.meal }}</h3> <img src="{{ recipe.image.url }}"> I'm just starting with Django so I apologize in advance if it's all a mess. Thank you in advance! -
using more than one button in same view in django
I am trying to make a "next" and "back" buttons for displaying 5 elements of my database, every time you click on "next" button, it will display the next 5 elements and if you click "back" button, it will show the 5 previous elements. The error that shows up is Request Method: POST Request URL: http://localhost:8000/notificacions/ Django Version: 3.0.3 Exception Type: MultiValueDictKeyError Exception Value: 'back' my python code in views is: if request.method == 'POST': if request.POST['next']: for element in range(5): show_notifications.append(notifications_list[the_counter]) the_counter+=1 elif request.POST['back']: the_counter-=10 for element in range(5): show_notifications.append(notifications_list[the_counter]) the_counter+=1 and my html code is: {% csrf_token %} BackNext -
Take value from other model in model connected FroeignKey
I wanna to two models: - Tasks - Paths (contain in Tasks) I created that two models: class Tasks(models.Model): task_type = models.IntegerField() url = models.TextField() status = models.IntegerField() class Paths(models.Model): tasks = models.ForeignKey(Tasks, on_delete=models.CASCADE) path = models.TextField() But i want to create rest api aplication and i want to have in model PATHS the thrid value Tasks_ID(ID from ForeignKey) i tried: ... path = models.TextField() tasks_id = tasks.id But it isnt so simple. Please give me advise, how should i do this. -
Django project is always rendering the home/default page, some urls.py mapping problem
Stuck with a Django project, I have an app called resumeapp in ResPortal project. A button clicked on homepage 127.0.0.1:8000 is still staying in the same page even though the url is changed to http://127.0.0.1:8000/ApplicantPage For example 127.0.0.1:8000 will go to the homepage but 127.0.0.1:8000/ApplicantPage will also display the homepage even though I linked another view. Here is my code: project urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url('',include('resumeapp.urls')), ] resumeapp\urls.py from django.conf.urls import url from django.contrib import admin from .import views urlpatterns = [ url('', views.upload_page, name='upload-page'), url('ApplicantPage', views.upload_nextpage, name='upload-page2'), ] -
Django Class Post has no object members
Class 'Post' has no 'objects' member? Code Below--models file--> from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title Code Below--views file---> from django.shortcuts import render from .models import Post def home(request): context = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', context) def about(request): return render(request, 'blog/about.html', {'title': 'About'}) please tell me this is an easy fix, I have no clue what could be wrong. using python3.7 for everything . It works on the server however in my code it says its an error. I don't like seeing errors, please help and thank you in advance. -
Django default information for model
I have 2 models (the Timeline one which will contain default information that I have to upload, and the Pdf one that contains the file and a relation to one of the timeline cells). I was told to create my own migration file and have done the following but I get this error and I can't find anything online about it: File "/Users/fetz/Desktop/parentsuportal/parentsuportal/timeline/migrations/0005_auto_20200324_1721.py", line 33, in addData Timeline(header = "Transport Support", age = "18-25") File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 520, in __hash__ raise TypeError("Model instances without primary key value are unhashable") TypeError: Model instances without primary key value are unhashable My models: HEADER_CHOICES = [ ('Financial Support', 'Financial Support'), ('Educational Support', 'Educational Support'), ('Governmental Support', 'Governmental Support '), ('Charity Support Groups', 'Charity Support Groups'), ('Therapy Support', 'Therapy Support '), ('Transport Support', 'Transport Support ') ] AGE_CHOICES = [ ('0-4', '0-4'), ('4-11', '4-11'), ('11-18', '11-18'), ('18-25', '18-25') ] class Timeline(models.Model): header = models.CharField(max_length=30, choices=HEADER_CHOICES) age = models.CharField(max_length=6, choices=AGE_CHOICES) class Pdf(models.Model): pdf = models.FileField(upload_to='timelinepdfs') timeline = models.ForeignKey(Timeline, on_delete=models.CASCADE) My migration file: from django.db import migrations def addData(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. Timeline … -
Django - not receiving AJAX data sent
I make an AJAX call, which should send data to the backend. In the backend, I print the data that has been sent from the frontend, however None is returned. This is unexpected, as the network tab(in chrome) confirms the AJAX request was successfully made, with the correct data appended to it. This make me think something is wrong with the backend(Django). HTML(signup.html): <form id="signup_form"> {% for field in form %} {{ field }} <br> {% endfor %} <button class="signup-btn btn btn-primary">Sign up</button> </form> <div id="testbox"></div> Javascript/AJAX CODE: var delayTimer; $('#signup_form').keyup(function() { clearTimeout(delayTimer); delayTimer = setTimeout(function () { var usernameVal = $("#username_signup").val(); // This returns expected result(value in input box) console.log(usernameVal); $.ajax({ url: '/users/ajax/signup', data: { 'usernameVal': usernameVal, }, dataType: 'json', success: function(data) { $('#testbox').text(data['usernameVal']); } }); }, 1000); }); views.py: // Renders form and signup page def signup(request): context ={} form = SignupForm() context['form'] = form return render(request, 'signup.html', context) // Handles AJAX (This is the view AJAX calls (url = /users/ajax/signup)) def ajax_signup(request): form = SignupForm(request.GET) if form.is_valid(): // This line below is printed successfully print("WORKS") // This line below returns None unexpectedly print(form.cleaned_data.get("usernameVal")) return JsonResponse({'usernameVal': form.cleaned_data.get("usernameVal")}) else: print(form.errors) return JsonResponse({'hello': 'not working'}) -
mouse cursor trail effect in Django
I am trying to add a mouse trail effect on a Django web page. I have written code in js and css and now I am trying to include them in my base.html so I added "" in my body tag (after my nav bar, but before {% block content %} {% endblock %} ), but nothing happens on my actual webpage. Am I supposed to write that somewhere else? -
Spotipy Authentication Flow (Spotify API)
I'm trying to allow users to login with Spotify (using the Spotipy library) to provide authentication for creating a playlist on their account and populating the playlist. After the user has logged in, I will display the playlist they have just created in the redirect template via an embedded Spotify player (using the playlist ID of the newly created playlist). I have a form input box in my HTML template which takes input from the user (their Spotify username). I also have a list of Spotify URIs for tracks ready to populate the playlist with. I followed Spotipy's documentation regarding obtaining a token for users for authentication as follows (I have removed my client-id & secret).. I'm not sure why it isn't working: import os import spotipy import spotipy.util as util from json.decoder import JSONDecodeError from datetime import date @login_required def save_playlist(request, data='Default_Data'): username = data.split('/')[0] #spotify username track_ids = data.split('/')[1:11] #list of spotify IDs for playlist tracks client_id = '****' client_secret = '****' scope = 'playlist-modify-public, playlist-modify-private' redirect_uri = 'http://127.0.0.1:8000/save_playlist/' #check if username is already in cache, if not, create cache try: token = util.prompt_for_user_token(username, scope=scope,client_id=client_id, client_secret=client_secret,redirect_uri=redirect_uri) except (AttributeError, JSONDecodeError): os.remove(f".cache-{username}") token = util.prompt_for_user_token(username, scope=scope,client_id=client_id, client_secret=client_secret,redirect_uri=redirect_uri) sp=spotipy.Spotify(auth=token) today = … -
Failed to start gunicorn.service: Unit gunicorn.service not found. Ubunto 18.04
I am following the this How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 18.04 guide. I have created the following file sudo nano /etc/systemd/system/gunicorn.service Original RECOMENDED_FORMATTING-s in the guide [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammyRECOMENDED_FORMATTING Group=www-data WorkingDirectory=/home/sammyRECOMENDED_FORMATTING/myprojectdirRECOMENDED_FORMATTING ExecStart=/home/sammyRECOMENDED_FORMATTING/myprojectdirRECOMENDED_FORMATTING/myprojectenvRECOMENDED_FORMATTING/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myprojectRECOMENDED_FORMATTING.wsgi:application [Install] WantedBy=multi-user.target How I have formatted my own version I had my virtual environment outside of the project folder on the server [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=SERVER_USER Group=www-data WorkingDirectory=/home/SERVER_USER/MAIN_PROJECT_FOLDER ExecStart=/home/SERVER_USER/ven/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/home/SERVER_USER/MAIN_PROJECT_FOLDER/MAINAPPLICATION_FOLDER.sock \ MAINAPPLICATION_FOLDER.wsgi:application [Install] WantedBy=multi-user.target I have also tried leaveing these as originally recomended --bind unix:/run/gunicorn.sock \ Than I have tried to execute the following code sudo systemctl start gunicorn Error message Failed to start gunicorn.service: Unit gunicorn.service not found. To solve this, I have tried Failed to start gunicorn.service: Unit gunicorn.service not found This points back to the exact same guide that I am doing except with an older version of linux. this is not the same code and not answered https://askubuntu.com/questions/748836/unit-gunicorn-service-failed-to-load-no-such-file-or-directory -
SuspiciousOperation at /i18n/setlang/ The request's session was deleted before the request completed
My Django Localization works perfectly in my development environment, but once i uploaded in on an ubuntu vps server with apache2 the translation is not working any more gives me this error when i ever i try to change the language : SuspiciousOperation at /i18n/setlang/ The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. Here is my code : settings.py LANGUAGE_CODE = 'en-US' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) My path to locales files are like : base/locale/ar/LC_MESSAGES/django.po And finally here is the form am using : <form style="margin-left: 50px;" action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language" id="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="{% trans 'go' %}"> </form> And also i have 'django.middleware.locale.LocaleMiddleware', inside MIDDLEWARE in my settings.py -
Pycharm "mark as template" missing
In my Pycharm I'm missing the 'templates' and 'resources' options for my directory folder. What should I fix in Pycharm to make this work? -
Convert dict to specific byte format
I am trying to create a Python client for making a HMAC authenticated request to a Django application. I am having trouble recreating the payload byte format that the Django app is using to generate the signature, and therefore I cannot recreate the signature value. the Django app is passing in the request body into the signature function in the format: b'key=value' where the payload is: { "key":"value"} I have tried both: str({ "key": "value" }).encode("UTF-8") and json.dumps({ "key": "value" }).encode("UTF-8") but both of them return: b"{'key': 'value'}" What is the this format (b'key=value') and how can I recreate it from a dict? -
Django Rest Framework - How to create a GIF file from an uploaded video
I have a Django Rest Framework + Android App where the user can upload some video files to my local Django development server. I wanted to show the videos as GIF files via a RecyclerView. I thought that creating the GIF files on server side (Django) would be more efficient than creating them on the client side (device). So I want to make a GIF file from an uploaded video before storing the video file. How can I do that in Django ? Here is my models.py: class Video(models.Model): created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=100, blank=True) video = models.FileField(upload_to='Videos/', blank=True) class Meta: ordering = ('created', ) This is how my views.py looks like: # used for displaying & creating video items class VideoList(generics.ListCreateAPIView): queryset = Video.objects.all() serializer_class = VideoSerializer parser_classes = (MultiPartParser, ) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) # the only part we change return Response({'videos': serializer.data}) And this is the urls.py with the url the app uses to upload the video file: urlpatterns = [ ... path('upload/', views.VideoList.as_view()) ] The upload of videos from my app works, but … -
list_filters are not working with redefined get_queryset in Admin list_view if that contains union
I needed to create Django Admin list_view page with redefined get_queryset() method that will do union by different models to the same page. But after I updated it, list_filter stopped work. As I find out if you use union() - Django doesn't allow to do any further filtering (only LIMIT, OFFSET, COUNT(*), ORDER BY SQL operations). And for some reason application of these filters is implemented after call of get_queryset(). I thought that call super().get_queryset(request) in my ModelAdmin.get_queryset() will return already parsed data. Questions: Is there any simple way how to get queryset with already applied list_filters and after do my custom filtering and union? Is this a bug in Django Framework by itself and this should be reported in their bug-tracker? -
How to pass 2 arguments from temlate to views in django?
So I know I can pass one argument like this: {%url '...path...' argument%} but I want to pass 2 arguments like {%url '...path...' argument1 argument2%} Here is my exact code: search.html: {% for id, title, thumbnail in videos%} <a href="https://www.youtube.com/watch?v={{id}}"><img src="{{thumbnail}}">{{title}}</a><p style="display:inline;"> | </p><a href="{%url 'select' id title%}">Add to playlist</a> <br> {%endfor%} urls.py: path('select/<id>/<title>', views.select, name='select'), I get the following error: Reverse for 'select' with arguments '('omPiA5AsGWw', 'PRESLAVA - POSLEDEN ADRES / Преслава - Последен адрес, 2007')' not found. 1 pattern(s) tried: ['select/(?P[^/]+)/(?P[^/]+)$'] -
Django Order By on Reverse Foreign Key value drops items without relationships
Context I am trying to sort a list of objects based on the value of a reverse foreign key relationship. I have partial solution, but filter used creates an inner join that drops objects without the relationship. The outcome I want to create sorted queryset with all objects, threating "null" reverse relationships as if the related value was null. Models class Student(models.Model): name = models.CharField(max_length=128) class Subject(models.Model): title = models.CharField(max_length=128) class Grade(models.Model): student = models.ForeignKey("Student", related_name="grades", on_delete=models.CASCADE) subject = models.ForeignKey("Subject", related_name="grades", on_delete=models.CASCADE) value = models.IntegerField() Fixtures +------+------------------------+ | name | subject | grade_value | +------+----------+-------------+ | beth | math | 100 | | beth | history | 100 | | mark | math | 90 | | mark | history | 90 | | mike | history | 80 | +------+----------+-------------+ Desired Outcome When sorting students by their "history" grade, I want to get [ beth (100), mark (90), mike (80) ] Now let's say mark was sick at home and missed the math exam. When sorting students by their "math" grade, I want to get [ beth (100), mark (90), mike (null) ] Instead, for the sorted by math grade returns [ beth (100), mark (90) ]. Attempted Solution … -
how save user in database? python (django) this is custom form
this is my django's forms and views py file. i want save new user. how create? this is forms.py from django import forms class SignUpForm(forms.Form): first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'first'})) last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'first'})) email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'first'})) password = forms.CharField(widget = forms.PasswordInput(attrs={'class':'first'})) re_password = forms.CharField(widget = forms.PasswordInput(attrs={'class':'first'})) this is views.py from django.shortcuts import render from django.http import HttpResponse import datetime from . import forms def regform(request): form=forms.SignUpForm() if request.method=='POST': form=form.SignUpForm(request.POST) else: html="welcome" return render(request,'home/home.html', {'html':html, 'form':form}) -
How to fix Uncaught TypeError: $image.cropper is not a function
I got the error of Uncaught TypeError: $image.cropper is not a function in my project when using the cropper jQuery plugin: https://github.com/fengyuanchen/jquery-cropper I guess the error has to do with the order defining jQuery, Bootstrap and Cropper files. After several attempts , i could not define the correct order. My order is: <script src="/static/theme/assets/js/jquery.min.js"></script> <script src="/static/theme/assets/js/bootstrap.bundle.min.js"></script> <script type="text/javascript" src="/static/cropper/js/jquery-cropper.js"></script> If it helps , my project has to do with cropping images in a django application based on the tutorial: https://simpleisbetterthancomplex.com/tutorial/2017/03/02/how-to-crop-images-in-a-django-application.html Here is the error: Uncaught TypeError: $image.cropper is not a function at HTMLDivElement.<anonymous> ((index):425) at HTMLDivElement.dispatch (jquery.min.js:2) at HTMLDivElement.y.handle (jquery.min.js:2) at Object.trigger (jquery.min.js:2) at HTMLDivElement.<anonymous> (jquery.min.js:2) at Function.each (jquery.min.js:2) at w.fn.init.each (jquery.min.js:2) at w.fn.init.trigger (jquery.min.js:2) at HTMLDivElement.o (bootstrap.bundle.min.js:6) at HTMLDivElement.i (jquery.min.js:2) Uncaught TypeError: $image.cropper is not a function at HTMLButtonElement.<anonymous> ((index):451) at HTMLButtonElement.dispatch (jquery.min.js:2) at HTMLButtonElement.y.handle (jquery.min.js:2) -
How can I set a timer in Django?
class Level(models.Model): name = models.CharField(max_length=25) duration = models.IntegerField() I want to set a duration for this model as a timer, and when it will stop call the other function, also I have to show this timer in certain template. Could anyone show me as an example? -
Django Reverse the mapper, URL name doesn't work
I'm currently doing on Django project and using reversing the mapper on urls.py. Before I use reversing it worked well, but after I change it to reversing, it started to do not work anymore. I want to know why it doesn't work. Is it because I didn't add it in proejct file's urls.py? How can I call that url with the name in app's file? from django.urls import path from . import views app_name = 'posting' urlpatterns = [ path('', views.index, name='index'), path('<int:post_id>', views.post, name='post'), path('posting', views.posting, name='postingform') ] index.html <a href='{% url 'postingform' %}'>Upload your beer now!</a> -
How to modify the frontend context for a React App using GenericViews?
I'm trying to transmit additional context to the front end through a ListAPIView by rewriting get_context_data so it returns a modified context["text_var"]="123". When I try to use something like <p>{{ test_var }}</p> at a index.js, I get the console error: "Uncaught ReferenceError: test_var is not defined". I'm trying to follow the patterns from https://docs.djangoproject.com/en/3.0/topics/class-based-views/generic-display/. Maybe the fact that the frontend is a React application implies in the requirement of additional steps? Can someone please point me what I'm missing here? Kind regards