Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the default Authentication Context Class Reference for a django server?
When you install a Django server without changing any setting, only assuming that it's using https and secure http only settings for the session cookie, what's the Authentication Context Class as defined by ISO/IEC 29115 ? -
How can I perform a GROUP BY query with the QuerySet API, that returns model instances, rather than dictionaries?
is it possible to create a list of model instances instead of a list of dictionaries when performing a GROUP BY query? I lose the functionality of a model instance when the instance is a dictionary. -
How to encrypt URL information in Django?
I want to something like www.example.com/Link2/add to be encrypted to www.example.com/DMQRzZWMDdGQtbndzBHNsawN0aXRsZQR0ZXN0AzcwMQR3b2UDMjQwMjEwNQ I tried using django-urlcrypt by follwing these instructions: https://pypi.org/project/django-urlcrypt/ . But it's not working as it seems to be for an older version of Django( for example, there is no Authentication_Backends in settings.py which is mentioned in the above link) Is there any other way to encrypt the URLs? Also how would it be decrypted? -
Database records via Searchbox into a Form of charfields -> to update records userfriendly
The Idea is a searchbox that should get the row via searching "KN" from .models the end-user is searching. after receiving the records, they need to be inserted into the "editprofileform"_form so that the enduser can change (some, not all) records and update/save/overwrite them if there are changes. Problem: I dont know and cant find anything to accomplish this. Sry for my bad english :D forms.py class editprofileform(UserChangeForm): class Meta: model = Kunden fields = ['KN', 'Name', 'Vorname', 'Straße', 'Ort', 'PLZ', 'Tel', 'Email', 'Beigetreten', 'Infos'] required = () labels = { 'KN': 'Kundennummer', 'Name': 'Name', 'Vorname': 'Vorname', 'Straße': 'Straße', 'Ort': 'Ort', 'PLZ': 'PLZ', 'Tel': 'Tel', 'Email': 'Email', 'Beigetreten': 'Beigetreten', 'Infos': 'Infos', } views.py @login_required() def article_overview(request): search_term = '' if 'search' in request.GET: search_term = request.GET['search'] customer = Kunden.objects.all().filter(KN__icontains=search_term) if customer: print(customer) return render(request, 'blog/search.html', {'customer': customer, 'search_term': search_term}) blog/search.html https://i.stack.imgur.com/jeUsf.png -
Detect changes in html using Django?
First of all, I'm very very new to web development (a few days), so I might say something that doesn't make sense. I am writing a music web app using Django and I want to display a piano keyboard, have the user play some keys and then be able to retrieve this data (the notes the user played). I was able to embed the piano thanks to this, but I don't know how to get the data back. I tried wrapping the html key tags (<li class="key">...</li>) within a form tag and a submit bottom but I can't get it to work properly, and I'm not even sure if it's possible this way. Then I realized, when you press some key, the tag's class changes from class="key" to class="key.active", so I was wondering if there is a way to detect these changes in the .html and thus be able to store the data. Does this even make sense? Maybe write a .py script to read the .html as a string and look for this changes? But does the .html file stored in the server change, or does it only change on the user's browser? I haven't found any info on … -
Cannot download pdf with Django
I want in my Django/React application "Generate Pdf" function which transform JSON to PDF. My whole app is working, many requests, responses, but somehow I've tried many solutions and generated pdf is not downloading. Request from React: generatePdf() { return fetch(APP_URL + '/generate_pdf/', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `JWT ${localStorage.getItem('token')}`, }, body: JSON.stringify(this.data) }).then((response) => { if (!response.ok) throw new Error(response.status); else return response; }) } Django view (from example https://docs.djangoproject.com/en/3.0/howto/outputting-pdf/): class PdfSongView(generics.UpdateAPIView, HTMLMixin): def post(self, request, *args, **kwargs): """ Generates pdf from context data and updates pdf path for given song """ # Create a file-like buffer to receive PDF data. buffer = io.BytesIO() # Create the PDF object, using the buffer as its "file." p = canvas.Canvas(buffer) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() # FileResponse sets the Content-Disposition header so that browsers After request I've got: [11/Jan/2020 15:22:48] "POST /generate_pdf/ HTTP/1.1" 200 1413 And in browser/network/generate_pdf/response I have: %PDF-1.3 % ReportLab Generated PDF document http://www.reportlab.com 1 0 obj << /F1 2 0 R … -
AssertionError at /cart/ Expected a `Response`, `HttpResponse` to be returned from the view, but received a `<class 'NoneType'>`
I want to refactor or integrate some old Django code from an old Django project. Everything was ok until the add to cart option or view. I don't know if there is anything I missed because I just following to code not the working procedure or steps. It's so straight forward to follow. But I got stack right now .... here is my code detail. cart models views.py file from django.shortcuts import render from django.views.generic.base import TemplateView from django.shortcuts import redirect from django.contrib.auth.forms import AuthenticationForm from django.views.generic.edit import FormMixin from django.urls import reverse from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from . import models from products import models as product_models class CartCreateView(TemplateView, APIView): """ add item to cart request handler """ template_name = 'carts/view.html' @staticmethod def _process_cart(item_id, quantity, delete, request): cart = None is_deleted = False if 'cart_id' not in request.session: cart = models.Cart.objects.create() request.session['cart_id'] = cart.id if cart == None: cart = models.Cart.objects.get(id=request.session['cart_id']) if request.user.is_authenticated(): cart.user = request.user cart.save() product_models.Variation.objects.get(id=item_id) cart_item, created = models.CartItem.objects.get_or_create(cart=cart, item_id=item_id) if created or quantity != 1: cart_item.quantity = quantity else: cart_item.quantity += 1; if delete in ['y','yes', 'true', 'True']: is_deleted = True cart_item.delete() else: cart_item.save() return cart, is_deleted, cart_item … -
response = super().list(request, args, kwargs) explanation
I am reading the codebase of the place where I work and in one of the views.py ,i see this line . Here is the code . class CreditPLansView(mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = CreditPlansSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return CreditPlans.objects.all() def list(self,request, *args, **kwargs) : from hospital.models import ProvidersDiscounts response = super().list(request, args, kwargs) print("response is", response.data) and here is the value of the response . response is [OrderedDict([('plan_id', 1), ('plan_name', 'Tenure1'), ('months', 3), ('interest', 25)]), OrderedDict([('plan_id', 2), ('plan_name', 'Tenure2'), ('months', 6), ('interest', 25)]), OrderedDict([('plan_id', 3), ('plan_name', 'Tenure3'), ('months', 12), ('interest', 25)])] I need an explanation as what this super().list(request, args, kwargs) is doing and from where is this data coming from . Any help would be highly appreciated. -
Error installing requirements-test.txt on windows
I was trying to install "requirements-test.txt" after installing "requirements.txt" but it showed me errors: 1.ERROR: Command errored out with exit status 1 2.ERROR: Failed building wheel for requirements-test.txt Can some one please help me on how to get rid of these errors. The screenshot of error screen is attached underneath: Error screenshot Link -
Django admin page not loading
i have created my superuser django admin id and after that i run the server.instead of showing admin page it showswhen i put "/admin" it shows this page but if i enter some other urls for eg."/shop" it is working this page is working correctly i have tried to search on net for this problem,but cant find out the solutionmy codes are as follows settings.py INSTALLED_APPS = [ 'shop.apps.ShopConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'onetouch.apps.OnetouchConfig', ] url.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('shop/', include('shop.urls')), path('onetouch/', include('onetouch.urls')), ] shop>models.py from django.db import models # Create your models here. class Product(models.Model): product_id = models.AutoField product_name = models.CharField(max_length=50) desc = models.CharField(max_length=300) pub_date = models.DateField() -
How to implement paginator
Why does pagination work only on e.g: category=Category objects.all But do not work on eg: category=Category objects.filter(name='shirt').? -
How to append items to context data in a ListView?
I am using a custom mixin in a ListView and want to add values for a specific key to the context variable : class MyMixin: mylist = ['itemA'] class MyList(MyMixin, ListView): mylist = ['item1','item2'] def get_context_date(self, **kwargs): context = super(ListView, self).get_context_data(**kwargs) context['mylist'].append(self.mylist) return context The desired outcome is mylist = ['itemA', 'item1', 'item2'] However, this results in a key_error. What's the correct approach to append key values to context? -
py manage.py migrate i am getiing these this error
File "C:\Users\user\Envs\Test\lib\site-packages\django\db\migrations\recorder.py", line 69, in ensure_schema raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (ORA-02000: missing ALWAYS keyword)''' -
"No blog matches the given query" This error appears when trying to get the detail of a blog post
I'm very new here in django. I was tring to make a blog site, actually blog is an app inside another site. So basically I'm tring to create that, "user can click on a blog and the user will be redirected to the detail view of the blog". I tries this by watching a tutorial, but it gives me an error in the localhost/blog/1. The error I'm getting back is: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/1/ Raised by: blog.views.detail No Blog matches the given query. my blog.urls.py file is here: from django.urls import path from . import views urlpatterns = [ path('', views.allblogs, name='allblogs'), path('<int:blog_id>/', views.detail, name='detail') ] and my views.py file is here: from django.shortcuts import render, get_object_or_404 from .models import Blog from django.views.generic import DetailView # Create your views here. def allblogs(request): blogs = Blog.objects.all() return render(request, 'blog/allblogs.html', {'blogs':blogs}) def detail(request, blog_id): detailblog = get_object_or_404(Blog, pk = blog_id) return render(request, 'blog/detail.html', {'blog':detailblog}) Now what should I do? Don't know where's the problem. -
React.Js not rendering in django project
i am creating a project where react is not rendering anything on django localhost index.html <!DOCTYPE html> <html lang="en"> <head></head> <body> <div id="App"> <!---all will be define in App.js--> <h1>Index.html </h1> </div> </body> {% load static%} <script src="{% static "frontend/main.js" %}"></script> </html> app.js import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import Header from './layout/header'; class App extends Component { render() { return ( <h1>App.JS</h1> ) } } ReactDOM.render(<App />, document.getElementById('app')); this is my project structure after running npm run dev and python manage.py runserver this is the status everything is fine till here. -
How to find tbody using bs4 in Django
I am trying to find the tag inside the table in bs4 using django it is showing result on the console but not working on the vps server . Although when I try the same code on the localhost it is working . When I am trying to access the tag inside the bs4 it shows Nonetype Error but the same code is working perfectly on the localhost I have the same version of python on the server as well as on the localhost This is my code which is having problem on the server if soup.find('tbody').find_all('tr') is not None: #but here it gives us None_type tbody tag #soup not finding tbody tag This is the complete code soup = BeautifulSoup(sorted_df.to_html(), "html.parser") count = 0 for j in soup.find("thead").find_all('tr'): if count == 0: j.append(BeautifulSoup('<td><b><center>Next Result</center></b></td>', 'html.parser')) count += 1 else: j.append(BeautifulSoup('<td></td>', 'html.parser')) modal_identifier = 0 print(soup,"HERE") #here it shows that soup has tbody tag in it job_card = 0 if soup.find('tbody').find_all('tr') is not None: #but here it gives us None_type tbody tag #soup not finding tbody tag i = 0 while ((soup.find_all("tr")) is not None) and i < len(soup.find_all('tr')): temp = soup.find_all('tr')[i].find('th').text print(temp, "TEMP") soup.find_all('tr')[i].append(BeautifulSoup( '<td><button type="button" class="btn btn-info btn-sm" … -
Django Model fonction infinite loop
When i attempt te save an instance in Contact model, it creates an infinite loop ( print(dispo_contact) will print 'irl' again and again till server breack). I do not understand what is going wrong, when i try the code on the shell it works fine. It appears I have missed something. Could you help me out please ? (Also I use django-multiselectfield app) ''' from django.db import models from django.utils import timezone from multiselectfield import MultiSelectField class Disponibilites(models.Model): Dispo_Choices = [ ('irl', 'personne'), ('tel', 'téléphone'), ('mail', 'e-mail'), ('nan', 'non précisé') ] dispo = MultiSelectField(choices=Dispo_Choices, default='nan') class Meta: abstract = True class Contact(Disponibilites): prenom = models.CharField(max_length=42) nom = models.CharField(max_length=42) metier = models.ManyToManyField('Metier') tel = models.CharField(max_length=10, blank=True, null=True) mail = models.EmailField(blank=True, null=True) date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution") class Meta: verbose_name = "contact" def __str__(self): return "{0} {1}".format(self.prenom, self.nom) def delete(self, *args, **kwargs): c = self for m in c.metier.all() : """remove dispo metier""" check_list=[] for dispo_metier in m.dispo : if dispo_metier not in c.dispo : check_list.append(dispo_metier) for dispo_contact in c.dispo : if m.contact_set.filter(dispo__contains=dispo_contact).exclude(id=c.id) : check_list.append(dispo_contact) m.dispo=check_list m.save() """fin remove dispo metier""" for s in m.secteur.all() : """remove dispo secteur""" check_list=[] for dispo_secteur in s.dispo : if dispo_secteur not in m.dispo : … -
Django create model based on form data with M to M relationship
I'm wondering if it's possible to reduce the actions when we are creating some Model based on the form data where we have Many to Many relations. We can't save the whole data at once because M to M needs to know about ID of the model and it's a problem because we don't have such ID at the first model save. So I'm doing it in the next way: Creating a model based on the simple fields to receive ID Manually set the M to M field and save it again so it looks for me like we have 2 queries to the DB (Maybe I'm wrong so fix me please) Is it possible to reduce these steps to only 1? Btw. I think the ModelForm should help, but I'm wondering if it's possible to do at a low level with the simple django.Forms. Also, I'm not sure that the ModelForm doesn't do the same stuff. here is the code example (very simple because I don't want to post a lot of code because it will makes the reading harder) # receive the form cleaned data data = form.cleaned_data # create a model with the simple fields to receive … -
Django form test non-field errors
I'd like to ask for a method to check if any kind of non-field errors was raised during form validation in Django. So far I found solution to do this during view testing. Well, it wasn't what I was looking for since I'm interested in doing it at form tests. I know the way to look for fields' errors: class FormTest(TestCase) def test_fields_errors(self): """ Suppose form has one field which has to be filled """ form = TestForm() form.full_clean() self.assertFalse(form.is_valid()) self.assertIsInstance( form.errors.as_data()['required_field'][0], ValidationError ) self.assertEquals( form.errors['deadline_datetime'][0], 'This field must not be empty' ) Is there any way to do this when we deal with non-field errors? -
How to add copyright in image using metadata
I am working on one website developed in Django framework using Python. There I am uploading some of the images. I want to add copyright in the metadata of that image. How Can i do that??? -
Django-tinymce settings/configuration for use in Admin
I want my model TextInput field in admin to look like the image below. I need the html template to look like this Thanks in advance for helping me out -
Is on_delete=models.CASCADE representing composition and models.PROTECT aggregation?
Since one of the main differences between aggregation and composition is that with composition if the composed class is deleted, all the objects of the componing classes are delated by consequence, and since this doesn't happen with aggregation, is the statement in my question correct? -
Send a request with Django view using Python-Requests
I'm trying to create a simple microservice structure on my Django projecjt: so when a certain Django view is called, this view will send a JSON post request to a Flask microservice containing some user's data; the Flask microservice should receive the request, take that user's data and send back to Django some additional data using Requests again, so that my Django view can receive that data and perform some operations, such as showing it to the user. Right now i'm just sending some dummy data, to test if this whole system ( Django > request to Flask > Flask > Request to Django) works, but i'm having some problems. To debug my code, i'm trying to just print the received data. Here is my view: def myView(request): mydict = {} # The request is sent to my external Python script.. req = requests.post('http://127.0.0.1:5000/', json={"one": 1}) # Some dummy data # .. Once the external script sends back a request with data, this should handle it if request.method == 'POST': # The data is inside this variable data = request.POST for key in data.items(): if float(key[1]) > 0: mydict.update({key[0]: key[1]}) print(mydict) #FIRST PRINT STATEMENT print(mydict) #SECOND PRINT STATEMENT response = … -
Weasyprint not generating PDF in production
I am building a web application using Django .I am using weasyprint to generate the PDF.Weasyprint is working fine while generating the PDFs in the local environment (my PC). Now ,I have migrated the changes over the cloud using the deployment platform provided by digital ocean .It is involving the use of gunicorn and nginx for running the server. But it is not generating any PDF output when I am hosting it . Instead it is giving 500 internal server error. Requesting someone to please help me out with this. Thanks, Aayush -
A more efficient way to check that there isn't a related item that has a certain value
I have the following method in one of my model classes. It's designed to let my views know that an JournalEntry can be edited. It should return true if the entry is not more than 90 days old and does not have any related LineItems that have a value in the LineItems reconciled_date field. Ie all the related LineItems must have NULL in their reconciled_date field. The method works but it iterates thru the LineItems which seems very inefficient. Is there a better way? Models.py class JournalEntry(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=False, blank=False) date = models.DateField(null=False, blank=False) def can_edit(self): """Checks if logged user can edit""" is_reconciled = 0 for lineitem in self.lineitem_set.all(): if lineitem.reconciliation_date != None: is_reconciled = 1 if (datetime.date.today() < (self.date + datetime.timedelta(90))) and is_reconciled == 0: return True else: return False Thank you