Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create charts from XML in Django?
My goal is to create a chart using the XML output from an HTTP request. By this script from django.shortcuts import render import xml.etree.ElementTree as ET # Create your views here. from django.http import HttpResponse from sickle import Sickle def index(request): return render(request, 'index_content.html') def completeness(request): sickle = Sickle('http://www.culturaitalia.it/oaiProviderCI/OAIHandler') records = sickle.ListRecords(metadataPrefix='oai_dc', set='mura_fort') return render(request, 'completeness.html', {'records':records}) I'm having around 200 records in XML format. Here an example of one of them: <record xmlns="http://www.openarchives.org/OAI/2.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <header> <identifier>oai:culturaitalia.it:oai:touringclub.com:56000</identifier> <datestamp>2012-02-06T16:09:08Z</datestamp> <setSpec>Beni_culturali</setSpec> </header> <metadata> <oai_dc:dc xmlns:oai_dc="http://www.openarchives.org/OAI/2.0/oai_dc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd"> <dc:description>Lungo le mura, al posto del baluardo nord-est, la cosiddetta Fortezza medicea è un degradato complesso di corpi di fabbrica eretti nella 2ª metà del '500 attorno al trecentesco cassero senese.</dc:description> <dc:identifier>56000</dc:identifier> <dc:relation>http://www.touringclub.com/monumento/toscana/grosseto/fortezza-medicea_3.aspx</dc:relation> <dc:title>Fortezza medicea, Grosseto</dc:title> <dc:type>Oggetto fisico</dc:type> </oai_dc:dc> </metadata> </record> As you can see from here return render(request, 'completeness.html', {'records':records}) the template is rendering the XML records. However, what I would like to have as output is a chart representing the overall number of each dc:description, dc:title etc. For sure I have to iterate my request over the XML and then count how many dc:title, dc:description or dc:identifier are in the output records. Any suggestion about a quick and simple solution? -
Django modelform fields from related objects
I have multiple OneToOneFields in my model and I was wondering if it was possible to create a ModelForm that links directly to the fields in that related object instead of having multiple forms (One for each model). For example: class ModelA(models.Model): fielda = models.TextField() fieldb = models.TextField() fieldc = models.TextField() class ModelB(models.Model): parent = models.OneToOneField(ModalA, on_delete=models.CASCADE, related_name='child') fieldd = models.TextField() fielde = models.TextField() fieldf = models.TextField() class MyModelForm(forms.ModelForm): class Meta: model = ModelA fields = ['fielda', 'fieldb', 'fieldc', 'child__fieldd', 'child__fielde', 'child__fieldf'] Is the above possible and if not, what are are the recommended alternatives? Many thanks, Dave -
Nginx does not receive form-data from another computer
I have a problem with nginx that doesn't receive form-data. Now I'm preparing web application using nginx and aws ec2. Currently, ubuntu+django+uwsgi+nginx is placed on ec2 through ssh. The problem is, on my computer, all the features on the ec2 Public Instances page are normally worked, but if another computer(different IP)enter the page(page opens well) and try to send formData to a server(nginx) then error403(incomplete chunked encoding) occurs. It has also set up 80 ports in the security group of the ec2. How can I receive a video file(formData) sent by an external user from a browser? What I've done so far 1.setting client_max_body_size client_max_body_size 50M; 2.change chown-socket value 660 => 666 3.change load balance round robin => hash 4.changed the user of nginx.conf to www-data //uwsgi.ini [uwsgi] uid=django base=/var/www/fileconvert home=%(base)/venv chdir=%(base) module=config.wsgi:application env=DJANGO_SETTINGS_MODULE=config.settings master=true processes=5 socket=%(base)/run/uwsgi.sock logto=%(base)/logs/uwsgi.log chown-socket=%(uid):www-data chmod-socket=666 vacuum=true //uwsgi.service [Unit] Description=uWSGI Emperor service [Service] ExecStart=/var/www/fileconvert/venv/bin/uwsgi --emperor /var/www/fileconvert/run User=django Group=www-data Restart=on-failure KillSignal=SIGQUIT Type=notify NotifyAccess=all StandardError=syslog [Install] WantedBy=multi-user.target // sites-available/fileconvert upstream django{ server unix:/var/www/fileconvert/run/uwsgi.sock; } server { listen 80; server_name ec2_public_domain; charset utf-8; client_max_body_size 50M; location / { include /etc/nginx/uwsgi_params; uwsgi_pass django; } } If you need more information, I'll add it right away. thanks. -
How to specify generated django model as a sender for signal?
I would like to listen for pre_create_historical_record signal provided by simple-history package but only from certain sender. The problem is that historical models are generated by simple-history and I can't figure out how can I import class "core.HistoricalUser" as a type to set as sender. -
Django filtered Viewset, need to annotate sum over all filtered rows. Group by "all"?
There are hundreds of questions here on various django annotate/aggregate constructions and filters but I couldn't find this simple use-case asked (or answered). I have a "Payments" model and associated ListAPIView ViewSet endpoint with nicely setup DjangoFilters so the client can filter on created__lte, created__gte, company= etc. Now I want to add an endpoint that derives from the above but only returns the sum of some fields and count of the total filtered objects. I know exactly how to do this if I would just write the View "from scratch" (I can just hack the DRF View into executing get_queryset().aggregate() then feeding into a serializer and returning), but I want to do it in a "Django-way" if possible. For example, combined with a serializer that defines "total_amount" and "nbr", this (almost) works: queryset = models.Payment.objects.values('company').annotate(total_amount=Sum('amount'), nbr=Count('id')) The values() call groups by "company" (a sub-field of Payment), which in combination with annotate() performs a sum by all company payments and annotates with total_amount/nbr. Adding filtering query parameters magically adjusts what goes into the annotation properly. The problem is, what if I don't want to group (or even filter) by "company", I just want to "group by all"? Is there a way … -
Q objects in unpacking arguments Django
I want to use a Q object while I'm unpacking arguments. So, I have an optional filter that only needs to filter CS_roles. So no users with CS roles are listed. I was thinking to do the filter like this: ~Q(roles__role=Role.CS) so my argument looks like: staff_arguments = {~Q(roles__role=Role.CS)} My filter is: site.users.all().filter(*staff_arguments,) When I do this, I still get users with CS roles. What am i doing wrong? -
Insert newline in django form using forms.py
I am making a login form in django. This is my forms.py: from django import forms from django.views.decorators.csrf import csrf_protect class loginForm(forms.Form): email_id = forms.CharField() password = forms.CharField(max_length=32, widget=forms.PasswordInput) forms.CharField(required=True) My question is, how can I insert a newline in between email_id and password? Because the page looks like this: Thanks in advance. -
Sorting querysets by annotated field of reverse relation
I have 2 models, Form and Row, Each Row has a FK to a Form. I want to sort my Forms by the time of last row addition. class Form(models.Model): ... class Row(models.Model): form = models.ForeignKey( Form, related_name="rows", ) created_at = models.DateTimeField( auto_now_add=True, ) I tried this but it doesnt work: queryset = Form.objects.filter(is_empty=False) queryset = queryset.annotate(last_submit=Max("rows__created_at")) -
Django problem: views.py called twice, variables overridden
I use django to process users data in json recieved thru typeform's api(a google forms-like service). After submitting their typeforms, users are redirected to my django server which passes processed data to a link of a landing page where users' scores are displayed. This worked for a while, but after a lot of back and forth with different verisons of my algorithm, the views.py function is called twice. What's even weirder - the variables get overridden, which shouldnt be possible concering the sctructure of my code. Each score in the list below shouldn't be higher than 40, but it gets multiplied. After I reset the server it's good again but only for one GET request, then it gets messy again regardless whether its the same user's email(used for identifying his/hers submit data) or a different one. This is how it looks in my console: Django version 3.0.3, using settings 'demo_server.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. # First request: user's scores: [['A', 30], ['R', 24], ['E', 20], ['I', 16], ['S', 16], ['C', 14]] {correct link} [04/May/2020 15:01:23] "GET /typeform/dan@hiry.pl HTTP/1.1" 302 0 # Second request: user's scores: [['A', 100], ['R', 82], ['E', 70], ['I', 58], ['S', … -
A field in Django Model has white space. How can I strip it right in the model? I am not using it in form
So, post-uploading my CSV to Django model, I was querying. That's when I got a Zero Division Error in one of my fields which is based on the filter. The filter is a CharField. That has whitespace but of course, Django returns a stripped version of the string when passed through a form. However, it is not a ModelForm. Two Ways: 1) When it brings back the value after hitting submit on the form, it shouldn't strip. (But it isn't a ModelForm) 2) Trim the white space in the CharField in the Model itself. Either of these I have no idea how to do. Can someone help me here? -
Django - ModuleNotFoundError (basic app to print Hello in browser)
I'm new to django so take me easy. I'm just following some youtube tutorials and try to make a simple app to print Hello on the browser with django. And I keep getting this error in the urls.py file ModuleNotFoundError: No module named 'app' I get this error in urls.py file of my project which is bellow: urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('app.urls')), path('admin/', admin.site.urls), ] I also made an app called app app\urls.py from django.urls import path import views urlpatterns = [ path('', views.home, name = 'home'), ] app\views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse('Hello!') I read I think all threads on this topic and nothing helped so far and I can't realise where's my mistake or what I did wrong. -
how to change <input> type- text to type- date in django form
I want to apply bootstrap for forms, but in the input "date" tag the "type" is defined as "text". model: class AdmissionForm(forms.Form): date = forms.DateTimeField(widget=forms.DateTimeInput( attrs={ 'class': 'form-control' } )) def save(self): new_admission = Admission.objects.create( date = self.cleaned_data['date'],) -
Django ' One To Many ' Relationship (Comment on a joke)
thought I'd make a website, where people can upload jokes and comment on different ones, basic functions so far. The only issue I am facing is once I create a comment, I cannot automatically assign it to a joke, I have to select the joke manually that I want to comment on, how do I do that using the current many to one relationship that I have now. Current thoughts... Use this from the jokes model that I'm passing around in the urls to select the joke and assign to the comment this way (Not sure how to do this) Here are my models: from django.db import models from django.utils import timezone from django.urls import reverse class JokeListItem(models.Model): title = models.CharField(max_length=100, null=True) content = models.TextField(null=True) date_posted = models.DateTimeField(null=True, default=timezone.now) comment = models.CharField(max_length=100,null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('joke-home') class Comment(models.Model): content = models.CharField(max_length=100,null=True, blank=True) joke = models.ForeignKey(JokeListItem, blank=True, null=True, on_delete=models.CASCADE,related_name='comments') def __str__(self): return self.content def get_absolute_url(self): return reverse('joke-home') Here are my views: from django.shortcuts import render from .models import JokeListItem, Comment from django.views.generic import CreateView, DeleteView, DetailView, UpdateView from django.shortcuts import get_object_or_404 # Create your views here. def home(request): all_joke_items = JokeListItem.objects.all() return render(request, 'website/home.html', {'jokes': all_joke_items}) class … -
Handling html special chracter in django url
This is my django rest framework view: class NewsArticleViewSet(viewsets.ReadOnlyModelViewSet): queryset = [] serializer_class = NewsArticleSerializer pagination_class = None def get_queryset(self): slug = self.request.query_params.get('news', None) if slug: news = News.objects.filter(slug=slug) return news return [] which is working perfectly except when I pass html special chracter in url like this one: ?news=example/2020/4/4/&apos;53-lorem-ipsum&apos; its returning nothing; because self.request.query_params.get('news', None) parsing as example/2020/4/4/ not full string example/2020/4/4/&apos;53-lorem-ipsum&apos; Here is value of self.request.query_params for debugging: <QueryDict: {'news': ['example/2020/4/4/'], 'apos': ['', ''], '53-lorem-ipsum': ['']}> How to fix this problem ? -
How to run a Django Query to filter from a list of values?
I have a list that looks like this - Let's call this list "links" ['https://crucible05.cerner.com/viewer/cru/CCS-28483', 'https://crucible05.cerner.com/viewer/cru/CCS-28520', 'https://crucible05.cerner.com/viewer/cru/CCS-28779'] My Python model, reviewComments looks like this - class reviewComments(models.Model): reviewID = models.CharField(max_length=20, blank=True) commentID = models.CharField(max_length=20, primary_key=True) solution = models.CharField(max_length=50) comment = models.TextField() dateCreated = models.DateField() type = models.CharField(max_length=20, blank=True) crucibleLink = models.URLField(blank=True) authorID = models.CharField(max_length=20) reviewerID = models.CharField(max_length=20) def __str__(self): # pragma: no cover return self.commentID In reviewComments, the field crucibleLink field contains several elements in the database like this - ['https://crucible05.cerner.com/viewer/cru/CCS-24654#CFR-2484153', https://crucible05.cerner.com/viewer/cru/CCS-26041#CFR-2549576 ] Notice the extra #CFR part in each of these.. I need to run a Django query to filter out the "links" elements from the ones present in the database. I tried doing this - crucible_db = reviewComments.objects.values_list('crucibleLink', flat=True) for link in links: crucible_db = crucible_db.filter(crucibleLink__icontains = link) print(crucible_db) But this returns only one queryset and then several empty querysets like this - How do I go about doing this? Thanks -
Django - How can i use "def create()" in an article serializer?
I am trying to make a serializer that can create an article. I have done registration and login part successfully,but i don't know how to write a def create serializer so the data can be saved on Article. Can somebody help? class ArticleCreateSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('id','author','caption','details') def create(self, validated_data): //???? return article -
How can I display images with the same height with CSS?
I have a dating website and I display lists of users with profile pictures. If the user doesn't have a profile picture, I display a specific image. Here is the code: @register.inclusion_tag(filename='accounts/profile_picture.html', takes_context=True) def profile_picture(context, user, geometry, with_link=True, html_class=''): context = copy.copy(context) geometry_splitted = geometry.split('x') width = geometry_splitted[0] if (len(geometry_splitted) == 2): height = geometry_splitted[1] else: height = geometry_splitted[0] context.update({ 'user': user, 'geometry': geometry, 'width': width, 'height': height, 'with_link': with_link, 'html_class': html_class, }) return context profile_picture.html: {% thumbnail user.photo.file geometry crop='center 20%' as image %} <img src="{{ image.url }}" alt="{{ user.name }}" width="{{ image.width }}" height="{{ image.height }}" class="img-fluid {{ html_class }}" /> {% empty %} <img src="{% static 'speedy-core/images/user.svg' %}" alt="" width="{{ width }}" height="{{ height }}" class="img-fluid {{ html_class }}" /> {% endthumbnail %} CSS: .img-fluid { max-width: 100%; height: auto; } But the problem is, because of this height: auto; thing, users without a profile picture have profile pictures higher than users with profile pictures. I want to display all users with the same height, and if necessary, display a smaller width for users without a profile picture (which displays speedy-core/images/user.svg as their profile picture). If possible, without changing the file user.svg itself. How do I do … -
Django, how to sum queryset value in dictionary values
I have the following queryset dictionary: {'Key_1': [100.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'Key_2': [103.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]} In which I have as Key the category of my products and as items 12 values, that rappresent the sum of each month. I want to calculate the cross sum of all keys of each items, as the following example: {'Total': [203.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]'} How could I obtain it? -
How do I get data stored in localStorage by Django
I made web with Django. And web is created by Javascript. The problem is how to get localStorage Value. If I choose the button then it stored number 1 or 2 at localstorage. function setNumber(num) { localStorage.setItem(FST_NUM_LS, num); } like this. And web is changing for another button, and choose and choose, etc.. Finally, local storage have number that sum of all before number. And I want show result at next page. The result is if sum of number is 1 then show "num 1 result", else "num 2 result" like this.. Result is append to sum of value in localStorage. But I coudn't get localStorage value with Django. How can I get localStorage value?? Or use another method? Plz give me a hint... -
Optionally link a model to another model via a foreign key
I have a Django application where registered users can add, through an input form, details of performances of their music ensemble. This application also has a a section for composers, where they add their own composition. I'm using a custom user model, with profiles linked to user accounts: class User(AbstractBaseUser): email = models.EmailField(verbose_name="email", unique=True, max_length=255) first_name = models.CharField(max_length=30, blank=True, null=True) [...] class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) [...] This is my 'composition' model: class Composition(models.Model): title = models.CharField(max_length=120) # max_length = required composer = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) [...] And this is my 'performance' model. The performance information links to the piece performed (performed): class Performance(models.Model): performed = models.ManyToManyField(Composition, blank=True) [...] So far, so good. Now, I'd like the performers to be able to add pieces by composers who are not (yet) registered to the website. Let's say that the performer performed a piece by John Lennon and is adding information about that performance. So, the performer will need to be able to add both John Lennon, his composition, and link the two. The most important bit is: if the ghost of John Lennon tomorrow wants to register to the website, the administrator of the website will need to be … -
Pytest Not Deselecting Certain Tests (but should be in pytest.ini)
I've got a test suite setup and have been using pytest (which I find so fantastically helpful for testing Django projects, which this is). I also am using pytest-django on this project. To give some background: I am trying to do some integration testing with a Headless Browser and have pytest ignore certain tests that are used where I am using a standard browser (not-headless); I'd like to deselect those tests using a real, visual browser so that they don't trigger in my CI/CD pipeline. Given the example pytest.ini below if I run: pytest launcher it shows as I would expect that there is 1 test being deselected (the StandardBrowserTestCases class only has 1 test in it). However, if I run: pytest other_app (which also has a StandardBrowserTestCases class) it does not show anything being deselected and StandardBrowserTestCases is ran with the other tests and not deselected. [pytest] addopts = --nomigrations --cov-config=.coveragerc --cov=my_project --cov=other_app --cov=launcher --cov=people ; # Ignore the StandardBrowserTestCases - these are only used for local ; # development / visual debug and contain no real valuable tests --deselect=other_app/tests/test_integrations.py::StandardBrowserTestCases --deselect=launcher/tests/test_integrations.py::StandardBrowserTestCases --deselect=people/tests/test_integrations.py::StandardBrowserTestCases --junitxml=./test-results/junit.xml --cov-report html:./test-results/htmlcov --html=./test-results/test_results.html --self-contained-html DJANGO_SETTINGS_MODULE = my_project.unit-test-settings python_files = tests.py test_*.py *_tests.py Question(s): Am I using … -
Django child model with OneToOne parent does not inherit parent's fields?
I have a parent classs Dish and a child Pizza that inherits from Dish. They have a 1to1 relationship and I wrote them as follows: class Dish(models.Model): PIZZA = 'PIZZA' SUB = 'SUB' PASTASALAD = 'PASTASALAD' PLATTER = 'PLATTER' TYPE_CHOICES = ( (PIZZA, 'Pizza'), (SUB, 'Sub'), (PASTASALAD, 'PastaSalad'), (PLATTER, 'Platter') ) name = models.CharField(max_length=64, blank=True) type = models.CharField(max_length=64, choices=TYPE_CHOICES, blank=True) size = models.CharField(max_length=1, choices=SIZE_CHOICES, default=SMALL, blank=True) price = models.DecimalField(max_digits=6, decimal_places=2, default=None) def __str__(self): return f"{self.name} {self.size} - Price: ${self.price}" class Pizza(Dish): dish = models.OneToOneField(Dish, on_delete=models.CASCADE, related_name="dish_id_pizza", parent_link=True) REGULAR = 'REGULAR' SICILIAN = 'SICILIAN' STYLE_CHOICES = ( (REGULAR, 'Regular'), (SICILIAN, 'Sicilian'),) style = models.CharField(max_length=7, choices=STYLE_CHOICES, default=REGULAR) topping_count = models.IntegerField(default=0, validators=[MaxValueValidator(5), MinValueValidator(0)]) def __str__(self): return f"{self.size} {self.style} pizza with {self.topping_count} toppings: ${self.price}" Now I have a Dish object with ID=17 and a price of 21.95, type=Pizza, size=Small, type=Regular. I now try to create the corresponding Pizza object as follows: >>> parent=Dish.objects.get(pk=17) >>> new_17_pizza = Pizza(dish=parent, topping_count=2, style="Regular") >>> new_17_pizza.save() I would assume that all Dish fields and values are inherited, i.e. I don't have to repeat them, but I get: sqlite3.IntegrityError: NOT NULL constraint failed: orders_dish.price Why is that? I know I am not allowing blank=True for the price in Dish, but … -
Receiving "'hmset' with mapping of length 0" error
I want to store my session data on redis dataset. I have set SESSION_ENGINE = 'redis' in settings.py. Code for redis.py #redis.py from django.contrib.sessions.backends.base import SessionBase from django.utils.functional import cached_property from redis import Redis class SessionStore(SessionBase): @cached_property def _connection(self): return Redis( host='127.0.0.1', port='6379', db=0, decode_responses=True ) def load(self): return self._connection.hgetall(self.session_key) def exists(self, session_key): return self._connection.exists(session_key) def create(self): # Creates a new session in the database. self._session_key = self._get_new_session_key() self.save(must_create=True) self.modified = True def save(self, must_create=False): # Saves the session data. If `must_create` is True, # creates a new session object. Otherwise, only updates # an existing object and doesn't create one. if self.session_key is None: return self.create() data = self._get_session(no_load=must_create) session_key = self._get_or_create_session_key() self._connection.hmset(session_key, data) self._connection.expire(session_key, self.get_expiry_age()) def delete(self, session_key=None): # Deletes the session data under the session key. if session_key is None: if self.session_key is None: return session_key = self.session_key self._connection.delete(session_key) @classmethod def clear_expired(cls): # There is no need to remove expired sessions by hand # because Redis can do it automatically when # the session has expired. # We set expiration time in `save` method. pass I am receiving 'hmset' with mapping of length 0 error on accessing http://localhost:8000/admin in django. After removing SESSION_ENGINE='redis' I am not receiving … -
Is there a calendar module for Django in Bootstrap?
So I'm newbie in programming world. I've been looking for a calendar in my webpage, so that users can dynamically input their schedules on it. However I'm having hard time finding a fine module. There isn't much in pypi.org, lots of modules are quite outdated. Do you have any recommendations? Thanks a lot :) -
Customizing default auth form in Django for html template
I'm trying to use the CSS from an HTML template I downloaded online to work in my default Django login form, and I gather that to imbue {{ form.username }} with any styles, you must create a custom LoginView in forms.py and modify that as if it were any other form using attrs={}. I have already done what was suggested in this question before anyone says this is a duplicate. class UserLoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(UserLoginForm, self).__init__(*args, **kwargs) username = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'input100', } )) password = forms.CharField(widget=forms.PasswordInput( attrs={ 'class': 'input100', } )) The name of the CSS style I'm trying to apply to the username (and password) text fields is "input100" but the username and password don't seem to be affected by anything I'm putting in forms.py. In fact, even if I take out the username and password fields in the above file, it still works the same, so clearly changes to forms.py aren't reaching the template (but the template is using UserLoginForm fine as if I take the whole thing out it crashes). change to urls.py: urlpatterns = [ path('', subsmems, name='subsmems'), path('accounts/', include('django.contrib.auth.urls')), path('signup', signup, name='signup'), path( 'login/', views.LoginView.as_view( authentication_form=UserLoginForm, ), name='login' ) ] html …