Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pass string via POST | Python
I am trying to hit an endpoint http://localhost:8001/header in which I am sending a string(ans) to another endpoint via POST request, but at the receiving endpoint side, the data is empty. Following is my code Please suggest where I am doing wrong. def header(request): ans = '[{"id": "dag"}, {"id": "afqw"}]' requests.post("http://localhost:8001/drftoken", data=ans) return JsonResponse({'message': 'ok'}) def drftoken(request): user = dict(request.POST) print(user) # printing {} here return JsonResponse({'message': 'ok'}) -
Getting dynamic data for chart.js from Django model
I am trying to create an analytics dashboard page for users that sign into my site. So if user 'DummyCo' signs in and goes to mywebsite.com/DummyCo/dashbord, they will see analytics relating to the model records where they are listed as the user (or client as I call them on the model.) I have the data working (shown below) but that simply allows me to display the count number. What i'd like to do is start using this data in charts on chart.js which I have up and running, but it does not allow me to grab that signed-in user the way my other view does (chart view shown below also). models.py class Session(models.Model): uid = models.CharField(max_length=50, blank=True) cid = models.CharField(max_length=50, blank=True) client = models.CharField(max_length=50, blank=True) views.py class DashboardListView(LoginRequiredMixin, ListView): template_name = 'blog/dashboard.html' context_object_name = 'sessions' ordering = ['-session_date'] def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Session.objects.filter(client=user).order_by('-session_date') def get_context_data(self, **kwargs): user = get_object_or_404(User, username=self.kwargs.get('username')) context = super().get_context_data(**kwargs) session_list = list(context['sessions']) context['total_actions'] = Session.objects.filter(client=user).count() # count function context['total_users'] = Session.objects.filter(client=user).values('uid').distinct().count() context['total_modules'] = Session.objects.filter(client=user).values('cid').distinct().count() context['sessions'] = session_list return context @ login_required() def dashboard(request): return render(request, 'blog/dashboard.html', {'title': 'Dashboard'}) urls.py path('<str:username>/dashboard/', views.dashboard and DashboardListView.as_view(), name='blog-dashboard') html tags produced {{ total_users }}, {{ total_actions }}, … -
How to perform function before submitting a Django form
There are many SO questions about async functions and how to perform something before sending a POST request. My problem is specific to Django because my CSRF token is lost if I wrap the function in a $.when or do any other solutions. I want to call a function that in itself sends a GET request to and API and fills certain form fields AND THEN afterward, sends a POST request to Dajngo (because the data isn't populated until the first function completes). I want to perform these functions only after the data is validated with Jquery's ".valid". Any IE compatible methods of doing this? Heres my JS: $('#long_form').on('submit', function(e) { e.preventDefault(); if ($("#long_form").valid()) { $.when( finished()).done(function(){ $('#long_form').unbind('submit').submit(); $.ajax({ url : $(this).attr('action') || window.location.pathname, type: "POST", data: $(this).serialize(), success: function (data) { console.log("Done")}, error: function (jXHR, textStatus, errorThrown) { alert(errorThrown);}}) })}}) Finished() is a function that calls the other functions, including one that sends an GET request to an API. I am also validating the data with jquery before sending to Django which is why I'm using AJAX. I'm quite new to Django and Ajax so this may be a dumb question, but I can't figure this out on my … -
modelForm crispy formhelper and choices list datepicker not showing
I've searched through Stackoverflow for this and cannot find an answer. I am trying to render a ModelForm using crispy forms and FormHelper to help me lay it out nicely. Everything was working fine when I was using the forms.Form library. but the main problem now is that the date picker and the choices field no longer have a dropdown list with the datepicker or the So this is my forms.py file: CITIES= (("London","London"), ("Istanbul","Istanbul"), ("Cape Town","Cape Town")) class EntryForm(forms.ModelForm): class Meta: model = Items itemName = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'item name'})) ... date = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'}),required=False) location =forms.ChoiceField(choices=CITIES, required=False) fields = ['itemName', 'date', 'location'] def __init__(self, *args, **kwargs): super(EntryForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( 'itemName', ... Row( Column('date', css_class='form-group col-md-6 mb-0'), Column('location', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), Submit('submit','Kelepiri Paylaş') ) My template file looks like this: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h1>Entry Form</h1> <br> {% crispy form %} <br> {% endblock %} -
How to pass user back to front end client after authorizing and obtaining access token?
I have a Django backend and React/Redux front end and I am trying to integrate the Spotify API. I am a total django noob so please have mercy. I currently send the user to my backend via a regular ol' anchor tag on the front end. My backend then redirects the user to the Spotify Authorize page and then that page redirects them to another page which trades the authorization code for the access token which I now have. However this code and the urls just send me to my backend API. How do I get the user back to the front end with this access token? "My" code: from django.views.generic.base import RedirectView, TemplateView from rest_framework.response import Response from rest_framework import generics, viewsets, permissions from django.urls import reverse from furl import furl import requests def build_authorize_url(request): params = { "client_id": "<client-id>", "response_type": "code", "redirect_uri": request.build_absolute_uri( reverse("spotify callback") ), "scope": " ".join( [ 'user-read-currently-playing', 'user-modify-playback-state', 'user-read-playback-state', 'streaming', 'app-remote-control', 'playlist-read-collaborative', 'playlist-modify-public', 'playlist-read-private', 'playlist-modify-private', 'user-library-modify', 'user-top-read', 'user-read-playback-position', 'user-read-recently-played', ] ), } print(params) url = ( furl("https://accounts.spotify.com/authorize") .add(params) .url ) print(url) return url AUTH_HEADER = { "Authorization": "Basic " + base64.b64encode( "<my client id>:<my client secret>".encode() ).decode() } def handle_callback(request): code = request.GET["code"] response … -
Django-taggit - tags aren't saving/how to save tags?
I'm trying to integrate taggit with my app. It seems to be mostly working, and I'm able to add tags via django admin. But I want to save the input from JobForm's tags field, I have tried following the documentation adding form.save_m2m() in place of where form.save is in my example but nothing seems to get the input. In my searches I've only came accross people explaining how to do this via the shell or admin, but I need users to be able to enter their own tags. class JobForm(forms.ModelForm): ... class Meta: model = Job fields = ['company', 'title', 'description', 'application_info', 'remote', 'city', 'state', 'country', 'location', 'email', 'category', 'tags'] @login_required(login_url='/login/') def jobs_new(request): ... if request.method == 'POST': if site.siteconfig.remote: form = JobRemoteForm(request.POST) else: form = JobForm(request.POST) company_form = CompanyForm(initial={'site': site}) if form.is_valid(): job = form.save(commit=False) if site.siteconfig.remote: job.remote = True job.site_id = site.id job.user_id = request.user.id job.tags = request. job.tags.all job.save() form.save() context = {'job': job, 'protocol': site.siteconfig.protocol} send_mail_with_helper( '[%s] New job posting' % site.name.upper(), render_to_string( 'job_board/emails/new_job_notification.txt', context ), site.siteconfig.admin_email, [site.siteconfig.admin_email] ) -
Django models (ManyToManyField?) - adding same object multiple times & conserving order
I have a Battleship-like grid (with positions A1, B1, C1, ... A2, B2, C2, ...) and objects that are moving around on the grid, where a position can only be occupied by one object at any given time. I'm trying to use Django models to store the paths taken by each object and was wondering the best way to do that. For example, I would want to be able to query and see that ObjectZ has been to [A1, B1, B2, C2, C3, D3, D2, C2, C3] - then I would know that ObjectZ started at A1 and is now at C3. I tried to use the ManyToManyField, but soon realized that I could not add the same object multiple times (meaning, I could not add C2 more than once). Thanks in advance! -
Login_redirect_url not working. View always redirecting to index
This is my login redirect url in settings.py: LOGIN_REDIRECT_URL='/category/all' And this is my login view: def login(request): if request.user.is_authenticated: return redirect('/') else: if request.method == "POST": email=request.POST['email'] password=request.POST['password'] user=auth.authenticate(email=email,password=password) if user is not None: auth.login(request, user) return redirect('/') else: messages.info(request,"Email Password didn't match") return redirect('login') else: return render(request,"login.html") Whenever the user logs in I want to redirect him to the category/all page but it is always redirecting to index("/") and this might be because I am using return redirect("/").Also even when I have login required for some view then too even when the url is like: http://localhost:8000/login/?next=/cart/ Instead of redirecting me to cart it redirects too index. Please help me to work around this so that the redirect works properly. -
Uploaded media files not displaying after deploying on Heroku
After deploying my Django web app on Heroku, whenever I upload any image to the site, the image displays for some time then after stops showing... my uploaded images only shows temporary. How can I resolve this issue, I have installed white noise and added it to middleware in settings.py still the issue persists. -
Django did not display the uploaded image from cloudinary
May I know how to display the img that uploaded to cloudinary from django templates? I have tried the {{ obj.img.url }} but returned error: attribute has no file associated with it. Did I missed somethings? model.py: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) wts_img = models.ImageField(upload_to='wts/', blank=True, null=True) html: {% load cloudinary %} {% for order in orders %} <img src="{{ order.wts_img.url }}" > {% endfor %} setting.py: CLOUDINARY_STORAGE = { 'CLOUD_NAME': 'xxxxx', 'API_KEY': 'xxxxxxx', 'API_SECRET': 'xxxxxxxxxx' } DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' -
Django. How to kind of "spread" object when passing as with parameter to include?
I have a component which i include like that: {% include "components/item_link.html" with target="_blank" href=link.href icon=link.icon text=link.text %} There are lots of repetitions of link.. Is there a way to "spread" object and include it like that? {% include "components/item_link.html" with target="_blank" ...link %} -
int() argument must be a string, a bytes-like object or a number, not 'NoneType' Django
Why am i getting this error here? It very wierd, sometimes it works and sometimes it does not. Can someone explain if they understand. The error accures in my views.py file: fotlister = Produkt.objects.filter(under_kategori__navn__iexact="lister") kalkuler = ProduktKalkureing.objects.all() beregning = {} if request.method == "POST": omkrets = request.GET.get('omkrets') for i in kalkuler: kalk = math.ceil((int(omkrets)/i.lengde)*1000) add = ({'produkt_tittel': i.produkt.produkt_tittel, 'produkt_bilde': i.produkt.produkt_bilde, 'produkt_info': i.produkt.produkt_info, 'produkt_link': i.produkt.produkt_link, 'pris_heltall': i.produkt.pris_heltall, 'antall_kalk': kalk, 'total_kost': kalk * i.produkt.pris_heltall }) beregning.update(add) What im trying to do is get the value from a POST request and calculate based on that value. Also i would like to put all the values into a dictionary, also having trouble with that. All i would like to put all the information in the add dictionary and display that on my template. Thanks for any answers, im just trying to understand how python operates. -
Django. How to use filters in include with clause
I have link component which i include like that {% include "components/item_link.html" with href="{{ title | lower | slugify }}" %} It renders with href equal to {{ title | lower | slugify }} instead of properly filtered title value (string) -
How do I fix a reverse error in Django when redirecting?
I am currently working on a website where you can create a shopping list. I am trying to insert items into the shoplist. So things like banana, cake, etc would go into shoplist. I got everything to work. When I create the item, it goes inside the database but when I try to redirect back to the website where I pressed create item, it shows the error Reverse for 'detail' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['shoplist/(?P<item_id>[0-9]+)/$'] Also, when I try to enter my details page, it shows the error Reverse for 'createitem' with arguments '('',)' not found. 1 pattern(s) tried: ['shoplist/(?P<item_id>[0-9]+)/createitem/$'] I think I did something wrong when making my paths or doing something wrong syntax wise. Nothing I found on the internet is fixing it. Is there a way to fix this problem? Thank you very much! views.py def createitem(request, item_id): if request.method == 'GET': return render(request, 'shoplist/createitem.html', {'form':ItemForm(), 'id':item_id}) else: form = ItemForm(request.POST) itemlist = form.save(commit=False) itemlist.shoplist = Shoplist.objects.filter(user=request.user, pk=item_id).first() itemlist.user = request.user itemlist.save() return redirect('detail', pk=item_id) urls.py from django.contrib import admin from django.urls import path from shoplist import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), #authentication path('signup/', views.usersignup, name='usersignup'), path('logout/', … -
login page doesnot show any field
I am using Django 2.2.15 my views.py code for login page is given below, from django.contrib.auth import authenticate, login, logout def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('store') context = {} return render(request, 'registration/login.html', context) and my main part of login.html code is given below, <h2>Login to your account</h2> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">Log In</button> </form> But when I start to refresh my login page it doesnot showing any field for login page like below screen shot, login page please help me to sort out this problem. -
DRF other fields in serializer on get and on post
I'm trying for a few hour how to get other fields representation in serializer when i'm doing get and other when i'm doing post. I want this all data which are in author field in json, but lower in html form i want only choose exist user from list. When i change author field to display only url then i can choose author from list. Is it possible to get author info like on first screen and have only possibility to choose author from user list without editing all user fields? -
Programatically adding an image to Wagtail from one's local machine
I'm trying to add images to a model on my Wagtail site with a manage.py command. I found this post that covers it, but it's using a requests.get() call to the image from the internet. I have my images saved locally and have tried to adapt the linked code unsuccessfully: from django.core.files.images import ImageFile from wagtail.images.models import Image path = f"{img_directory}/{filename}" img_bytes = open(path, "rb").read() img_file = ImageFile(BytesIO(img_bytes), name=filename) img_obj = Image(title=filename, file=img_file) print(img_obj.file) img_obj.save() The print(img_obj.file) statement does print the filename as defined, but when I try to call img_obj.save(), I get the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: wagtailimages_image.width I'm guessing that I'm opening the file wrong and it's not reading it as an image as I want it to, but I can't figure out where exactly I'm going wrong. -
How can I prevent a full table scan in this PostgreSQL query?
This query is contstructed using the Django ORM. I have indexed on all ID columns, so I was surprised when EXPLAIN showed a prohibitively long full table scan on orders_query. The long-running piece is in the very top of the EXPLAIN log, but here's the relevant portion (the very top lines): GroupAggregate (cost=999695.25..19231670646.03 rows=1897315 width=105) Group Key: users_profile.id, users_user.last_login -> Sort (cost=999695.25..1007470.17 rows=3109968 width=73) Sort Key: users_profile.id, users_user.last_login -> Hash Right Join (cost=738.71..387928.02 rows=3109968 width=73) Hash Cond: (orders_query.user_id = users_user.id) -> Seq Scan on orders_query (cost=0.00..345054.24 rows=2943324 width=8) -> Hash (cost=702.78..702.78 rows=2874 width=73) -> Hash Right Join (cost=301.35..702.78 rows=2874 width=73) Question: Is there another index I can make to avoid this Seq Scan that slows down the SQL query? SELECT "users_profile"."id", "users_profile"."created", "users_profile"."modified", "users_profile"."guid", "users_profile"."user_id", "users_profile"."charter_role_id", "users_profile"."owner_id", "users_profile"."volume_limit", "users_profile"."vol_limit_ovrd", "users_profile"."charter_vol_limit_contrib_ovrd", "users_profile"."sponsored_ovrd", "users_profile"."view_peers_ovrd", "users_profile"."inherit_permits", Count(DISTINCT "orders_order"."id") AS "orders", (SELECT Count(DISTINCT U0."guid") AS "io" FROM "orders_order" U0 INNER JOIN "users_user" U1 ON ( U0."user_id" = U1."id" ) INNER JOIN "users_profile" U2 ON ( U1."id" = U2."user_id" ) WHERE U2."owner_id" = "users_profile"."id" GROUP BY U2."owner_id") AS "indirect_orders", Count(DISTINCT "orders_query"."id") AS "searches", (SELECT Count(DISTINCT U0."guid") AS "isch" FROM "orders_query" U0 INNER JOIN "users_user" U1 ON ( U0."user_id" = U1."id" ) INNER JOIN "users_profile" U2 … -
Exception Value: Value too long for type character varying(2)
So I am using React and Django. I currently have a problem with submitting forms because I am gettin the strange error Exception Value: Value too long for type character varying(2) Models.py for the Model in question: @python_2_unicode_compatible class Member(models.Model): class Meta: ordering = ('last_name', 'first_name') first_name = models.CharField(max_length=50, db_index=True) last_name = models.CharField(max_length=50, db_index=True) dob = models.DateField(verbose_name='Date of Birth', null=True, blank=True, help_text='format: 1999-12-31') card_number = models.CharField(max_length=10, help_text="The ID number on the membership card", unique=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) latest_membership = models.ForeignKey('Membership', null=True, blank=True, related_name='latest_member') email = models.EmailField(blank=True) phone = PhoneNumberField(blank=True) street_1 = models.CharField(max_length=200, blank=True) street_2 = models.CharField(max_length=200, blank=True) city = models.CharField(max_length=100, blank=True) state = USStateField(choices=us_states, blank=True) zip_code = models.CharField(max_length=16, blank=True) I see there is some fields with max_length but I know I am not violating the constraint. API for React form: def redesign_member_form(request): if request.method == 'POST': errors = {} try: data = json.loads(request.body) data["dob"] = parse(data["dob"]) print("dob parsed") Member.objects.create(**data) except Exception as e: errors["error"] = e.message return JsonResponse(errors, status=400) return HttpResponse(status=200) else: return HttpResponse(status=400) The react form: import React from 'react'; import Form from '../../components/form/Form'; import { FormContext } from '../../components/form/Form'; import FormDropdown from '../../components/form/FormDropdown'; import FormDatePicker from '../../components/form/FormDatePicker'; import FormInput from '../../components/form/FormInput'; import FormButton from '../../components/form/FormButton'; … -
how edit names of field in django filters, and add styling
I am following a tutorial to make a django app, I was making a filter table however there are some issues in it. I have already tried things suggested in other answers, and they did not work for me. In the image attached as you can see I have underlined the names of the fields that I want to change and don't know how to do it, django just named those fileds by itslef and I want to change it, also please tell how can I use bootstrap to make it look good. Thank you.. filters.py file - import django_filters from django_filters import DateFilter, CharFilter from . models import * class OrderFilter(django_filters.FilterSet): start_date = DateFilter(field_name="date_created", lookup_expr="gte") # lookup_expression, gte-> # greater than or equal to end_date = DateFilter(field_name="date_created", lookup_expr="gte") # lookup_expression, lte-> less # than or equal to note = CharFilter(field_name="note", lookup_expr="icontains") class Meta: model = Order fields = '__all__' # we are excluding these because we want to customize them exclude = ['customer', 'date_created'] model - Order - in models.py - class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for Delivery', 'Out for Delivery'), ('Delivered', 'Delivered') ) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) date_created = … -
What order do JavaScripts need to be written in Python?
After much trial and error I discovered that to get my date widget to work I needed to do this - <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/js/tempusdominus-bootstrap-4.min.js" integrity="sha256-z0oKYg6xiLq3yJGsp/LsY9XykbweQlHl42jHv2XTBz4=" crossorigin="anonymous"></script> If I put my scripts the other way round, the date widget would not work. It never dawned on me that the order the scripts were in would have an impact on whether the code worked or not. Would an experienced Python programmer be able to tell, just by looking at the two scripts, what order they need to be in? To prevent future problems, is there anything I can check, to work out what orders script need to be written in? -
Django ORM: distinct and annotate
Let's say I have a table like this: class Developer(models.Model): first_name = models.CharField(max_length=255) last_name= models.CharField(max_length=255) team = models.CharField(max_length=255) closed_tickets = models.IntegerField() objects = DeveloperManager() I want to write a query which returns: Write SQL to show percentage of team tickets closed by every developer and rank developers by contribution level. something like this: is there a way to it in a one query? I am trying to think in the direction of annotation with distinct clause class DeveloperManager(models.Manager): def rank(self): return self.order_by('team').annotate( total=models.Sum( 'closed_tickets' ), piece=models.F('closed_tickets') / models.F('total'), ).distinct('team').values() but it returns me an error: NotImplementedError: annotate() + distinct(fields) is not implemented. -
azure invalid username when migrating django database
I followed [Tutorial: Deploy a Django web app with PostgreSQL in Azure App Service][1] I created the DB and the app till I get to : Run Django database migrations Open an SSH session in the browser by navigating to https://.scm.azurewebsites.net/webssh/host run the "python manage.py migrate" it gives me this error FATAL: Invalid Username specified. Please check the Username and retry connection. The Username should be in <username@hostname> format. (antenv) root@5f4958961a00:/home/site/wwwroot# thnx in advance [1]: https://%3Capp-name%3E.scm.azurewebsites.net/webssh/host -
DRF serilaizers nested create/update with 2 FK
My models class Checklist(models.Model): checklist_name = models.CharField(max_length=255) is_done = models.BooleanField(default=False) class Category(models.Model): checklist_name = models.ForeignKey(Checklist, on_delete=models.CASCADE, related_name="checklist_name") category_name = models.CharField(max_length=255) is_done = models.BooleanField(default=False) class Task(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category') task_name = models.CharField(max_length=255) How can I create/update nested serializers with 2 Foreignkey starting from Checklist ? -
django filter queryset based on list of dates and get the count on each day
I have a model like this class MyModel(models.Model): date = models.DatetimeField(auto_now_add=True) and i have a list of dates (dates of last seven days, it can be dates of last 30 days as well). What i am trying to do is get the number of MyModel objects created in a particular day in all of the dates. Like below. [{'date1': 2}, {'date2': 3}, {'date3': 7}....{'daten':26}] the keys of the dictoary are dates and values are the number of objects created in that particular date. by using a forloop and hitting db multiple times i am getting the output, but is there a way to get it from a single query ?