Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Pytrends calling results Type Error Object of type QuerySet is not JSON serializable
Firstly, I have looked at previous documentation from previous questions, but they are not super similar. In pytrends, you have TrendReq, and then build payload which requests the data from google trends. I am having trouble with having User Input from a form field in Django. I created a model form to store the queries which I will be using for some other things. However, whenever I try to pass a user input, the payload never gets built due to this error saying it is not JSON serializable. So in this case I am thinking it is two things: I have an issue with my user input. TrendReq already requests the information, therefore I do not need to have a request function in my views Here are the three pieces of relevant code: forms.py class TrendForm(ModelForm): class Meta: model = trendParams fields = ['trends'] widget = {'trends': TextInput(attrs={'class': 'form-control', 'placeholder': 'Look Up'})} views.py (where I call) def pytrends_query(request): form = TrendForm() trendData = [] all_trends = trendParams.objects.all() pytrends = TrendReq(hl='en-US', tz=360)#calls pyTrends kw_list = [all_trends] #calls form from forms.py for user input from HTML file pytrends.build_payload(kw_list, cat=0, timeframe='now 7-d', geo='US-MA', gprop='') #builds payload for request req = pytrends.related_queries() #calls related … -
Django html page wont allow post with multiple items
I have a html page that runs a for loop to populate students on a board. Here is screenshot and the code. Issue: The issue is if i have more than one student in the class , no matter which button on the page i click it will not let me do a POST. If there is just a single kid in the class, the POST will work. So the post is failing and i don't know why. Thanks for the help in advance. {% extends 'base.html' %} {% load crispy_forms_tags %} {% crispy K8Points_ClassroomForm %} {% load static %} {% block content %} <br> <h2>{% load static %} <img src="{% static 'forms/star.png' %}" alt="chain" height="62" width="62"> My Classroom</h2> <br> <br> <form action="/points/k8_points_classroom" method="POST"> {% csrf_token %} <!-- Start Date --> <div class="container"> <div class="container"> <div class='row'> <div class="col-4"> <p> Recording Data as User : {{user.username}} </p> <p><b> Classroom : {{class_name}} </b></p> </div> </div> <div class='row'> <div class = "col-2"> {{form.date|as_crispy_field }} </div> <div class = "col-2"> {{form.week_of|as_crispy_field }} </div> <div class = "col-2"> {{form.day|as_crispy_field }} </div> </div> </div> <div class="jumbotron" align="middle"> <h1>My Students</h1> <!-- Line Break --> <hr style="border: 1px solid black;"/> <!-- Line Break --> <div class="row mb-3"> … -
How can two Python applications hosted in different servers communicate?
I'm having an hard time figuring out how to solve a problem with a little project. Basically i have a Django application. On the other hand i have an external Python script running. I would like to create a system where, each time a form in my Django app is submitted, the data submitted in the form is sent to the external Python application. The external Python service should receive the data, read it, and according to who is the user and what did he submit, it should perform some tasks, then send a response. Here is what i thought: 1) Connect the external Python app to the same database that Django is using. So that when the form is submitted, it is saved on the database and the data can be 'shared' with the second Python service. The problem with this solution is that i would need the second app to query the Database every second and perform a lot of queries, that would be a problem with performances. 2) Create an epi endpoint, so that the external python app would connect to the endpoint and fetch the data saved in the database from there. The problem is the … -
How to stop quotes JSON from being escaped in a Django template?
How do you stop quotes from being escaped in a Django template? I'm trying to render a Python dictionary, representing Javascript options. My Django view's context retrieval method looks like: def get_context(self): context = {'options': mark_safe(json.dumps({'name': 'value'}))} return context and my template looks like: <html> <script>new SomePlugin.Object({{ options }});</script> </html> but for some reason, it renders like: <html> <script>new SomePlugin.Object({\"name\": \"value\"});</script> </html> For some reason, it's inserting backslashes to escape the quotes, as though it was rendering the data inside a string. Since it's not inside a string, this results in malformed Javascript. However, I can't find any way to disable this escaping. How do I do this? I thought that's what mark_safe did, but that's having no effect, and neither does {{ options|safe }}. -
How to add 'Delete' button to User Profile view in Django app?
I have an app login/logout system in which I automatically generate user profiles once user is registered. My Profile.html looks like this: <div class="col s12"> <form method="POST"> {% csrf_token %} <fieldset class=""> <legend class="">Profile Info</legend> {{ u_form.username }} {{ p_form.postcode }} </fieldset> <div class="col s6"> <button class="btn" type="submit">Update</button> </div> </form> /div> and my profile function from views like this: @login_required def profile(request): if request.method == "POST": u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f"Account updated!") return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = {"u_form": u_form, "p_form": p_form} return render(request, "users/profile.html", context) How do I add a 'Delete' button and function to allow user delete his/fer own profile to no longer exist in my database? -
Difference between UpdateView and BaseUpdateView - Django
My Doubt is: Difference between UpdateView and BaseUpdateView and how to use them I have tried to find information on the subject, but it is not much, so I have the doubt how to use exactly the BaseUpdateView view and similar views. Thanks in advance for your answers! -
Django get() missing 1 required positional argument: 'header'
Every time i do a successful post request i get this message. I know it has something to do with implementing the redirect function so you don't get a double post, but i cant get it to work right. Here is my code. Thanks for the help. @login_required def K8_Points_Test(request): if request.method == 'POST': form = K8PointsTestForm(request.POST) if form.is_valid(): form.save(commit=False) class_name = form.cleaned_data.get('class_name') getstudents = Student.objects.filter(class_name = class_name) students = getstudents.all() context = {'form': form ,'students' : students , 'class_name': class_name} return render(request, 'points/k8_points_test.html', {'form': form} ) else: return HttpResponseBadRequest else: form = K8PointsTestForm() return render(request, 'points/k8_points_test.html', {'form': form} ) -
Passing a value from html template to views.py in Django
can you please help me with the issue I'm experiencing? Basically, I followed a tutorial online to create a location-based application that displays the shops around the user's location. However, the longitude and latitude are hard-coded in views.py. views.py from django.http import request, HttpResponse from django.views import generic from django.contrib.gis.geos import Point from django.contrib.gis.db.models.functions import Distance from .models import Shop longitude = 10.113 latitude = -2.231 user_location = Point(longitude, latitude, srid=4326) class Home(generic.ListView): model = Shop context_object_name = 'shops' queryset = Shop.objects.annotate(distance=Distance('location', user_location) ).order_by('distance')[0:15] template_name = 'shops/index.html' I added the Leaflet integration with my template so now I can I have access to the latitude and longitude variables which I need to pass back to my views.py and update them there. Is that possible in general and what you be the solution for this? Thank you a lot for the help index.html map.locate({setView: true, maxZoom: 16}); function onLocationFound(e) { var radius = e.accuracy; var lat = e.latlng.lat; var lon = e.latlng.lng; L.marker(e.latlng).addTo(map) .bindPopup("You are within " + radius + " meters from this point"+ +lat+lon).openPopup(); L.circle(e.latlng, radius).addTo(map); } -
500 Server Error Serving Static with Whitenoise
Apologies for the length of code in this, I wanted to make sure I include as much as necessary for troubleshooting purposes. I have a Django application that needs to serve static files in production, and I've chosen whitenoise because it A) was built to do exactly that and B) seems like the simplest to configure. I've followed the steps in the documentation and this medium article and this blog post but I'm still seeing a 500 server error. I don't have any more details than that, I'm not getting a stack trace error and the page just says 500 server error. I'm at a loss as to what I'm doing wrong to get this to work. The only difference I can see between what I'm doing and what the blogs are doing is that my application is built in a Docker container. Any help would be much appreciated! settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STAT = os.path.join(BASE_DIR, 'static') DEBUG = False INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'audit_tool', 'rest_framework', 'crispy_forms', 'bootstrap', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] WSGI_APPLICATION = … -
Invalid template library specified. ImportError raised when trying to load 'compressor.templatetags.compress': cannot import name 'six'
I'm trying to add .scss to project by this tutorial. With Django 2 it works fine. But with Django 3.0 I'm getting an error. I'm creating new project with django-admin startproject mysite Then doing this part of tutorial https://prnt.sc/q6qyy2, and getting this error: File "/home/yuriy/Desktop/my/mysite/env/lib/python3.6/site-packages/django/template/backends/django.py", line 125, in get_package_libraries "trying to load '%s': %s" % (entry[1], e) django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'compressor.templatetags.compress': cannot import name 'six' my pip freeze output: asgiref==3.2.3 Django==3.0 django-appconf==1.0.3 django-compressor==2.3 django-libsass==0.7 libsass==0.19.4 pkg-resources==0.0.0 pytz==2019.3 rcssmin==1.0.6 rjsmin==1.1.0 six==1.13.0 sqlparse==0.3.0 Appreciate any help. Thanks -
Django - what is the best way to avoid doing repetitive queries in a dynamic navbar?
I'm currently developing a project which has two apps. When the user logs into the system, the navbar will show the links according to what permissions the user has in the database. If the user only has permissions for app 1, the links it will show will only correspond to this app, the same if it only has permission for app2. If the user has permission for both the navbar will show all the links of both apps. Being dynamic the navbar has to make queries to the database. so I want to avoid making a query every time a page is loaded. I have thought that an option is, in the view, to make the query a first time and then store it with request.session: Try: #If the query has already been made, it accesses the saved value query = request.session['navbar'] Except: # If the query has not been made, makes it and saves it in request.session['navbar'] request.session['navbar'] = #QUERYCODE This is a good way to handle the problem? is there another better way? -
How to filter a query on Django ORM
I know this should be pretty basic but somehow I don't quite get it. I want to get all users which age is lesser than 18 so the query should be something like this User.objects.filter(age < 18) what Im doing wrong? -
Django - If i put 2 formsets together in my view, the function to add multiple times the same views doesnt work
I have this code bellow. Im using formset to add multiple times the same form. But if i put this 2 formsets together, like in my view, just the first data for each form is saved. And if i put just 1 formset in my def, it works, all datas for i put to the form is saved. Someone have any idea why this is happening? (sorry for my eng) Forms.py class InsereIdioma(forms.ModelForm): class Meta: model = Idioma fields = '__all__' exclude = ['usuario'] InsereIdiomaFormset = formset_factory(InsereIdioma, extra=1) class InsereTecnologia(forms.ModelForm): class Meta: model = Tecnologia fields = '__all__' exclude = ['usuario'] InsereTecnologiaFormset = formset_factory(InsereTecnologia, extra=1) Views.py def cadastro_curriculo(request): if request.method == 'GET': formset_idioma = InsereIdiomaFormset(request.GET or None) formset_tecnologia = InsereTecnologiaFormset(request.GET or None) elif request.method == 'POST': formset_idioma = InsereIdiomaFormset(request.POST) formset_tecnologia = InsereTecnologiaFormset(request.POST) if formset_idioma.is_valid(): for form in formset_idioma: idioma = form.cleaned_data.get('idioma') fluencia = form.cleaned_data.get('fluencia') if idioma and fluencia: Idioma( idioma=idioma, fluencia=fluencia, usuario=request.user ).save() if formset_tecnologia.is_valid(): for form in formset_tecnologia: sistema = form.cleaned_data.get('sistema') nivel = form.cleaned_data.get('nivel') if sistema and nivel: Tecnologia( sistema=sistema, nivel=nivel, usuario=request.user ).save() return render(request, "personal/curriculo.html", { 'formset_idioma': formset_idioma, 'formset_tecnologia': formset_tecnologia, }) -
Post HTML input tag file data to another input tag file and retrieve in Django views
I'm trying to send one <input type="file"... value to another <input type="file".. using Javascript. I've created an HTML form and after filling it, I want to review the form. Then submit that form in my FormFill model through views.py. So far what I have done is creating 2 different Divs for the same work. In div1, I'm sending my form data using action="javascript:reviewForm()" and in reviewForm(), I'm setting all the form data of div1 to div2 form using document.getElementById('cfname2').value = document.getElementById('cfname1').value; It's setting all the values and then posting it to views.py successfully except my <input type="file" name="pic2".. data. Since python retrieves form POST data using request.FILES['pic2'], in div2 I don't have file data to Post. So far what I've tried is: document.getElementById('pic2').value = document.getElementById('pic1').value; where, In div1 I have <input type="file" id="pic1"... and in div2, <input type="file" id="pic2"... My models.py class FormFill(models.Model): pic = models.ImageField(upload_to='candidates/pics/') ... How can I post the div2 image data to views and then to Django models? Note: I don't want to Post the div1 data directly to Django models since I want my users to first review the form that they have filled. And that's why using the concept of 2 Divs. Thanks in … -
Chaining querysets in managers
I am looking for a way to reuse this abstract model/manager with queryset on the models that require soft delete but some of my models already have custom managers/querysets. Ideally I would like all of those other managers to use SoftDelete manager/queryset so that they would always return only undeleted items. Is there a way to achieve this in Django 1.10? class SoftDeleteQuerySet(QuerySet): def delete(self): for obj in self: obj.is_active = False obj.save() def undelete(self): for obj in self: obj.is_active = True obj.save() class SoftDeleteManager(Manager): def get_queryset(): return SoftDeleteQuerySet(self.model, using=self._db).filter(is_active=True) class SoftDelete(Model): is_active = m.BooleanField(default=True) objects = SoftDeleteManager() class Meta: abstract = True def delete(self): self.is_active = False self.save() def undelete(self): self.is_active = True self.save() -
KeyError when passing kwargs to ModelForm
I'm trying to create a custom field for my M2M field in my ModelForm. ConnectedTo is the many to many field. Code below: views: def addPartForm_Create(request, site, subtype): siteselected = site sitenumber = str(site) print(sitenumber) subtypeselected = Subtype.objects.get(SubtypeID = subtype) if request.method == 'POST': form = addPartForm(request.POST, sitenum=sitenumber) if form.is_valid(): obj = form.save(commit=False) obj.SiteID = Site.objects.get(SiteID = siteselected) obj.Subtype = subtypeselected obj.save() form.save_m2m() return redirect('/sites/'+str(site)) else: form = addPartForm() return render(request, 'myproj/addPart.html', {'form': form, 'SiteNo': Site.objects.get(SiteID = siteselected).SiteID, 'subtype': subtypeselected}) forms: class addPartForm(forms.ModelForm): class Meta: model = Part fields = ('Comment', 'Location', 'ConnectedTo', 'BatchNo', 'Manufacturer', 'Length', 'InspectionPeriod') labels = {"BatchNo": "Batch Number", "InspectionPeriod": "Inspection Period"} def __init__(self, *args, **kwargs): super(addPartForm, self).__init__(*args, **kwargs) sitenum = kwargs.pop('sitenum') self.fields["ConnectedTo"].widget = forms.CheckboxSelectMultiple() self.fields["ConnectedTo"].queryset = Part.objects.filter(SiteID = sitenum) I get KeyError when I try to pass sitenum from view to form. I know I could set a default value None but I don't want it to ever display none. I need to always have a sitenum sent here. Am I passing this wrong? -
pytest, How do you break up rather long test?
I'm writing my first pytest test, and it is rather long (currently 120 lines) It tests the store's checkout process, What it does is roughly following: grab product info add_to_cart add purchaser information (phone, name, address etc) (extra) add coupons or points to use create an order from cart handle payment (bypassing actual payment gateway, but still need to do something like stock decreasing, change order status etc) cancel the order (because created order data needs to be reused, I'm putting them together) How to break up pytest tests when many objects need to be shared.. -
Function instead of class django
I am wondering how to write it, but in function instead of class? from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from django.views import generic class SignUp(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' -
How to figure out NoReverseMatch at / in Django
Hi and thank you for your time Im using Django and i've got a following issues: NoReverseMatch at /dashboard/. NoReverseMatch at /event/. When i try to go to the dashboard page or to the event_list page i get the error. I know that it depends to url's links put in the templates files that use EventoDetailView and url name=dettagli but i don't understand the reason why. Im trying to figure it out but im not be able to do this. This is the code: Model.py class Evento(models.Model): nome = models.CharField(max_length=200, default='', blank=True, null=True) descrizione = models.TextField(max_length=5000, default='', blank=True, null=True) slug = models.SlugField() objects = models.Manager() cover = models.ImageField(upload_to='media/', default='', blank=True, null=True) data = models.DateTimeField(auto_now=False, auto_now_add=False, blank=True, null=True) author = models.ForeignKey("auth.User", on_delete=models.CASCADE, verbose_name="Balneatore", null=True) stabilimento = models.ForeignKey(Stabilimento, blank=True, null=True) saved = models.ManyToManyField(User, related_name='saved', blank=True) def __unicode__(self): return self.nome def total_saved(self): return self.saved.count() def get_absolute_url(self): return reverse("eventi:dettagli", args=[self.id]) class Meta: verbose_name = "Evento" verbose_name_plural = "Eventi" @receiver(pre_save, sender=Evento) def pre_save_slug(sender, **kwargs): print (kwargs) slug = slugify(kwargs['instance'].nome) kwargs['instance'].slug = slug View.py def EventiListView(request): evento_list = Evento.objects.all() evento_filter = EventoFilter(request.GET, queryset=evento_list) context = { 'evento_list': evento_list, } return render(request, 'evento_filter_list.html', {'filter': evento_filter}, context) def EventoDetailView(request, id): evento = get_object_or_404(Evento, id=id) #eventi_salvati = Evento.objects.filter(saved=saved) is_saved … -
How do I make and access regex capture groups in Django without RawSQL?
How do I annotate a Django queryset with a Regex capture group without using RawSQL so that I later can use that value for filtering and sorting? For example, in PostgreSQL I could make the following query: CREATE TABLE foo (id varchar(100)); INSERT INTO foo (id) VALUES ('disk1'), ('disk10'), ('disk2'); SELECT "foo"."id", CAST((regexp_matches("foo"."id", '^(.*\D)([0-9]*)$'))[2] AS integer) as grp2 FROM "foo" ORDER BY "grp2" dbfiddle -
Jquery POST in Django (continued)
I have read the 2 posts related to this subject. Can't make them apply to my case: I get a word that I pick from a radio button. I send that word via jquery ajax POST to a view function. That word should serve the purpose of filtering the query set like the WHERE in a sql query. Then the other issue is how I can get the proper content so that I can write it in the html template. I got that when I was not using jquery but now that I do, don't know how to use what I get from the view function. JQUERY $(document).ready(function(){ $('input[type="radio"]').click(function(){ var valor = $(this).val(); $.post('home', {valor:valor}, function(data)) $('#feedback').text(data); // this won't help. I actually need something like what I get with return //render(request, 'home.html', {'listoflanguages': listoflanguages}) }); }); VIEW FUNCTION def home(request): valor = request.POST.get('valor') listoflanguages = Language.objects.values('language','lesson', 'description', 'url').order_by('language', 'lesson').annotate(count=Count('lesson')) listoflanguages = listoflanguages.filter(valor) # I want to filter it here WHERE... return render(request, 'home.html', {'listoflanguages': listoflanguages}) AND THE TEMPLATE {% for item in listoflanguages %} <tr> <td class="align-middle">{{ item.language }}</td> // how can I implement what I get from the view? etc etc -
Django 2.2.x returns on specific computer: The requested resource was not found on this server
I have the same code running under Django 2.2.1 (also tried 2.2.5). Serving the page with python manage.py runserver The login page and also admin page is served. But after login there is a redirect to another page example.com/worklist which is not working on one computer. On the other system the page is served. On the first computer django returns: Using the URLconf defined in ms_worklist.urls, Django tried these URL patterns, in this order: admin/ accounts/ logout worklist/ The current path, worklist, didn't match any of these. The code is identical on both computers: The main app: # ms_worklist/urls.py from django.contrib import admin from django.urls import path, include admin.site.site_header = 'Worklist Admin' urlpatterns = [ path('', include('pages.urls')), path('worklist/', include('worklists.urls')) , path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')) ] And the worklist app: # worklists/urls.py from django.urls import path from django.db.utils import OperationalError from worklists.views import upload_csv, load_methods urlpatterns = [ path('', upload_csv, name='worklist'), path('ajax/load-methods/', load_methods, name='ajax_load_methods') ] -
How Not Duplicate Submit Form - without JavaScript - DJango
The objective of this is create an input where the user introduce username, there are 2 buttons that submit the form with OK or NO. The problem is that when I submit the form everything is going well but when 'reload' button is pressed the form is sent it again and the username is written in the database. How can I avoid this? Just submit the form, save the username in database, and then show the success message Preventing POST on reloading a form? This is the code: view.py def notificationchecker(request): user = '' # comprobamos cookie de usr try: user = request.COOKIES['user'] except Exception as e: print("Not cookie found: " + str(e)) finally: if user is not '': form = CheckerForm(initial={'user': user}) else: form = CheckerForm() # comprobamos cookie de success notification try: success = request.COOKIES['success'] date = request.COOKIES['date'] response = render( request, 'notificationchecker/notificationchecker.html', {'form': form, 'success': success, 'date': date, 'user': user} ) response.delete_cookie('success') response.delete_cookie('date') return response except Exception as e: print("Not cookie found: " + str(e)) return render( request, 'notificationchecker/notificationchecker.html', {'form': form, } ) def notificationchecker_result(request): form = CheckerForm(request.POST) if request.method == "POST": if form.is_valid(): ntchecker = form.save(commit=False) ntchecker.device = request.user_agent.ua_string ntchecker.option_selected = request.POST['option_selected'].lower() date = timezone.now() ntchecker.checked_date … -
Django - Form (populate field with instance)
obj = Contact.objects.get(id=1) return is -> 124571 myName from my database instanceForm = ContactFormDjango(request.POST or None, instance=obj) ContactFormDjango was a form field with contact and name my question is, how can i use my obj(Contact object id=1) to populate my form field as initial value when its load. -
When to use form methods
I am reading the Django documentation and ran across a couple examples in the forms sections that I do not understand why they did something 2 separate ways.. In the first example I found they send email from the FBV. This makes a lot of sense to a beginner. from django.core.mail import send_mail if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] sender = form.cleaned_data['sender'] cc_myself = form.cleaned_data['cc_myself'] recipients = ['info@example.com'] if cc_myself: recipients.append(sender) send_mail(subject, message, sender, recipients) return HttpResponseRedirect('/thanks/') In the second example I found they use CBVs and apply methods to the form and call this method in the view: from django import forms class ContactForm(forms.Form): name = forms.CharField() message = forms.CharField(widget=forms.Textarea) def send_email(self): # send email using the self.cleaned_data dictionary pass from myapp.forms import ContactForm from django.views.generic.edit import FormView class ContactView(FormView): template_name = 'contact.html' form_class = ContactForm success_url = '/thanks/' def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.send_email() return super().form_valid(form) When should you apply form methods and call those methods in the view? Is there a benefit to writing the code this way? Also, in the second example they used pass in the send_email() …