Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.template.exceptions.TemplateDoesNotExist: nouveaucontact.html
i'm Learning how to use Django and i have a problem… I Don't know why it tells me that my Template nouveaucontact.html doesnotExist… (I have put os.path.join(BASE_DIR, 'templates') in my settings.py) Thank you for your help :) You can see my code: blog\urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('accueil', views.accueil, name='accueil'), path('article/<int:id>-<slug:slug>', views.lire, name='lire'), path('article/<int:id_article>', views.view_article, name='afficher_article'), path('redirection', views.view_redirection, name='redirection'), path('contact/', views.contact, name='contact'), path('nouveaucontact/', views.nouveau_contact, name='nouveau_contact'), path('date', views.date_actuelle, name='date'), path('addition/<int:nombre1>/<int:nombre2>', views.addition, name='addition'), # autre manière d'écrire (d4 attend un nombre à 4 chiffres que la vue disposera sous le nom year re_path(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})', views.list_articles, name='afficher_liste_articles') ] views.py def nouveau_contact(request): sauvegarde = False form = NouveauContactForm(request.POST or None, request.FILES) #request.POST => pour els donnés textuelles et request.FILES pour les fichiers comme les photos if form.is_valid(): contact = Contact() contact.nom = form.cleaned_data["nom"] contact.adresse = form.cleaned_data["adresse"] contact.photo = form.cleaned_data["photo"] contact.save() sauvegarde = True return render(request, 'nouveaucontact.html', { 'form': form, 'sauvegarde': sauvegarde }) forms.py class NouveauContactForm(forms.Form): nom = forms.CharField() adresse = forms.CharField(widget=forms.Textarea) photo = forms.ImageField() models.py class Contact(models.Model): nom = models.CharField(max_length=255) adresse = models.TextField() photo = models.ImageField(upload_to="photos/") def __str__(self): return self.nom nouveaucontact.html <h1>Ajouter un nouveau contact</h1> {% if sauvegarde %} <p>Ce contact a bien été enregistré.</p> {% endif … -
How to customise a third party library or (Django app)?
I am working on Django-Oscar, For customizing oscar apps, Oscar provides us with a very amazing management command, python manage.py oscar_fork_app customer oscar_apps This clones the oscar app, and create a local version of oscar.apps.customer. Now we can modify Models, views, in an easy way. I am looking for the same alternative in Core Django. What I am trying to achieve? I have a requirement, where I have installed djstripe library. with pip command. now I want to customize a management command from that library. I did my R&D over this and got to know that I can clone from git and then run pip install -e setup.py But sadly, after cloning djstripe I got to know that there is no setup.py available. How can I customize a third-party library like djstripe according to my needs? -
django model choices in the react fronend
suppose i a have model like this class Posts(models.Model): status = models.IntegerField(choices=((1, _("Not relevant")), (2, _("Review")), (3, _("Maybe relevant")), (4, _("Relevant")), (5, _("Leading candidate"))), default=1) now my question is how can i render this choices in the frontend like react js? -
The error "Exception inside application: ["'undefined' is not a valid UUID."]" occasionally being triggered
I'm working on an app project that has a chat feature that's been build in the backend using Django channels 2.2.0 which seems to be working most times but then sometimes on occasion, and without any specific patterns being noticed, the chat history fails to open meaning no messages show up and no websocket connection seems to be established because nothing can be sent or received, although the latest incoming message does show up on the listing view of the chat from outside. Our Sentry reports shows the error: Exception inside application: ["'undefined' is not a valid UUID."] Our channels-redis is 2.4.0 while our server's is 5.0.4 if that might serve any clarifications, though I'm not sure if that's a problem why it might trigger an error only sometimes. Here's more details about the error: File "/home/youlans/virtual/lib/python3.6/site-packages/channels/sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "/home/youlans/virtual/lib/python3.6/site-packages/channels/middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "/home/youlans/virtual/lib/python3.6/site-packages/channels/consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "/home/youlans/virtual/lib/python3.6/site-packages/channels/utils.py", line 52, in await_many_dispatch await dispatch(result) File "/home/youlans/virtual/lib/python3.6/site-packages/asgiref/sync.py", line 150, in __call__ return await asyncio.wait_for(future, timeout=None) File "/opt/rh/rh-python36/root/usr/lib64/python3.6/asyncio/tasks.py", line 339, in wait_for return (yield from fut) File "/opt/rh/rh-python36/root/usr/lib64/python3.6/concurrent/futures/thread.py", line 56, in run result = self.fn(*self.args, … -
Update foreign key attribute depending on String without filter query
I have following situation. I got a Device model which is linked to 3 SensorColor models like: first_sensor_color = models.ForeignKey( SensorColor, on_delete=SET_NULL, blank=True, null=True, related_name="first_sensor_device", ) So I got 3 foreignkey's like that in my Device model. Now I want to update these SensorColor's in my algorithm run. The actual sensor is based on a String. So I can't just do: device.first_sensor_color = sensor_color_object Also I rather want 1 object for every device/sensorcolor combination in database So I thought doing this by first checking if there already exists an object or not. If it not exists it will make one, if there exists one, it updates it. In that last part it cause wrong. I do this with: sensor_to_update = getattr(self.device, sensor_attribute) setattr(sensor_to_update, "color", new_value_color) setattr(sensor_to_update, "status", new_value_status) But that only updates the fields and not the actual object. How can I update the SensorColor object? Is this possible without a query filter? -
How to access individual fields with of customised User model using AbstractUser?
I have defined a user model inheriting AbstractUser from django.auth.models. How can I refer to each individual fields of that customized user model? Say if I want to refer to date of birth of the customised user what should I write? I need to show the user profile, so in show_profile.html file, I wrote : first name = {{ settings.AUTH_USER_MODEL.first_name }} date 0f birth = {{ settings.AUTH_USER_MODEL.dob }} ... But it didn't work. Any idea? Moreover, my url route looks like this: path('my-profile/', views.ProfileView.as_view(), name='my_profile'), The concerned line in base.html is: <a class="dropdown-item" href="{% url 'my_profile' %}">Edit profile</a> The concerned lines in views.py are: class ProfileView(LoginRequiredMixin, TemplateView): template_name = 'show_profile.html' Please tell where I have done wrong. -
Form to edit multiple models at once
I have three models: class Press(models.Model): """Production unit""" class Job(models.Model): """Production specs""" press = models.ManyToManyField(Press, through='JobInst') class JobInst(models.Model): """Instance of a job assigned to a press for a period of time""" job = models.ForeignKey(Jobe) press = models.ForeignKey(Press) other_fields... I want to create a View that looks like an Excel spreadsheet, which works like this: 1. Get queryset of Press instances. 2. Render a formset that looks like a table: ____________________________________________________________________________________________ |Press.notEditable|Last-assigned-job.asChoiceField|OtherLast-assigned-jobFields.asCharField| | | | | ____________________________________________________________________________________________ What would be the most adequate approach to this? -
How to filter querysets dynamically with ajax and dropdown menu
I have a question for you. I have in my views the following code: def stato_patrimoniale(request): now=now.year ... This variable is used to filter my data in the queryset. I want to implement it adding the possibility to choose the reference year. I have created another app with the following model that with a form gives the possibility to add new year: class Timing(models.Model): reference_year=models.DecimalField(max_digits=4, decimal_places=0, default="2020") Now I want to create a dropdown button that contains all the reference_year filled and when the client click on one of them, the now variable in my def stato_patrimoniale(request): is updated. It is possible with an ajax call? -
Updating profile pic of user but its not requesting user to upload the pic
I want to update the profile pic of the user in the database, But its not requesting the user to upload the pic, on clicking the upload button its simply redirecting me to the page. models.py from django.db import models from django.contrib.auth.models import User class userprofile(models.Model): user = models.OneToOneField(User,on_delete = models.CASCADE) profilepic = models.ImageField(default='pp.png',upload_to='profile_pic',blank = True) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import userprofile class ProfileUpdateForm(forms.ModelForm): class Meta: model = userprofile fields = ['profilepic'] views.py @login_required def profile(request): if request.method == 'POST': p_form = ProfileUpdateForm(request.POST,request.FILES,instance=request.user.userprofile) if p_form.is_valid(): p_form.save() return render(request,'test_homepage.html') context = { 'p_form': p_form } return render(request,'profile.html') profile.html <form method ="POST" class="sm:w-1/3 text-center sm:pr-8 sm:py-8" enctype="multipart/form-data" > {% csrf_token %} {{ p_form|crispy }} <img id="profile_pic" alt="team" class="flex-shrink-0 rounded-lg w-full h-56 object-cover object-center mb-4" src="{{user.userprofile.profilepic.url}}"> <input style="padding: 8px 93px;" class="text-white bg-green-500 border-0 py-2 px-8 focus:outline-none hover:bg-green-700 rounded text-lg" type="submit" value="Upload"> </form> -
how remember image to secondary validations form
How to remeber upload image files to secondary validations form , when image is correct but another fields are wrong. Now I heve to upload image every time when form is run. I want to remeber image files if is correct to secondary validations form. my Form class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs = {'class':'form-control input-lg', 'placeholder':'Password'})) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput(attrs = {'class':'form-control input-lg', 'placeholder':'Password confirmation'})) class Meta: model = User fields = ('email', 'username','full_name','image') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['email'].widget.attrs.update({'class':'form-control input-lg','placeholder':'email'}) self.fields['username'].widget.attrs.update({'class':'form-control input-lg','placeholder':'Login'}) self.fields['full_name'].widget.attrs.update({'class':'form-control input-lg','placeholder':'Imię Nazwisko'}) print("init-file:",self.files) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user MY MODEL from __future__ import unicode_literals from django.db import models from django.core.validators import RegexValidator from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager) from django.conf import settings import random import os from django.dispatch import receiver from django.core.exceptions import ValidationError USERNAME_REGEX = '^[a-zA-Z0-9.+-]*$' def validate_image(image): file_size = image.file.size limit_kb = 2*1024 print("validate:",image) if file_size > limit_kb * 1024: raise ValidationError("Max size of file is 2 … -
Django channels - sending data on connect
I'm using a websocket to feed a chart with live data. As soon as the websocket is opened, I want to send the client historical data, so that the chart doesn't start loading only with the current values. I want to do something like this, if it was possible: class StreamConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) data = get_historical_data(1) await self.send({ 'type': 'websocket.accept', 'text': data }) What's the right way to do it? -
Connecting Django's Admin Users to Model
Let's say I have a two models: class Member(models.Model): nickname = models.CharField(max_length=128) email = models.EmailField() avatar = models.ImageField(upload_to='photos/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f'Member {self.nickname}' class Dashboard(models.Model): title = models.CharField(max_length=128) owner = models.ForeignKey(Member, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Here I create a distinct model for tracking members who can edit dashboards. Can I use Django users for that instead, avoiding creation of my own models? -
Error in makemigrations and migrate in pycharm using django
Guy i was working on a django website i create a django website before also but this time when ever i run command Python manage.py makemigrations Its stop there no error nothing shows after this command Suggest me what to do And one thing i run the python makemigration blog (Blog is app name here) Its is working properly then but after this migrate command will hang Detail : I created a project name blogs And inside it i create a app blog I am using postgresql database After writing model class I run the make migration command And it shows nothing and no other command i can write after this as shown in image enter image description here -
How to create a python script (Django) that triggers itself at a specific time?
I devellope a web application which must recover the data on another site every day at 00: 00h. To trigger the recovery of the data I had to create a middleware which is based on a request sent by any user who would navigate on the site around 00: 00h. Until then everything works normally. Problem: Retrieving data takes a long time and this disrupts the navigation of the user in question. Question: So I wanted to know how to do without this mechanism by creating a script that is triggered by itself at 00: 00h without going through a request from any of the user. Thanks to everyone who will help me. -
Python check if attribute is none depending on string
I want to check if an attribute from a class is None. The attribute itself depends on some cases and is stored in a string "attribute_name". How can I check of the attribute is None? Something like: hasattr(object, attribute_name) but then not checking of the attribute exists in the model but if it has a value -
Django: images do not appear in templates index.html
hii can you help to solve this error images do not appear in index.html image src: /media/{{product.0.image}} my project folders are C:\Users\noman\PycharmProjects\PyShop\pyshop> for images to store: pyshop\media\products\images for html template: pyshop\products\templates\index.html when I check images location on products page below is the location that appears http://127.0.0.1:8000/media/products/images/test01.jpg product page is: http://127.0.0.1:8000/products -
Does Django render JS on server side?
I know that Django has default config of SSR (server-side rendering) but all the articles I have gone through mention that the Django-forms are rendered on server side and then sent to the browser. No specific information on the use case when javascript is mixed in the template. I want to know if I use jquery tables in my Django template. Does that still render on server side? If yes then how does it render Javascript/jquery on the server-side? I'd be glad if someone corrects me if my question itself has invalid argument. -
Django how to filter table with dropdown menu?
I have created an app that collect all daily income. The model is the following: class Income(models.Model): date=models.DateField('', default="GG/MM/YYYY") income=models.DecimalField() I have created a simple template that contains the form and the data table with all data collected. <form method="post"> <div class="row"> h5>Income data collection</h5> <div class="row"> <div class="form-group col-2 0 mb-0" > {{form.income|as_crispy_field}} </div> <div class="form-group col-2 0 mb-0" > {{form.date|as_crispy_field}} </div> </div> <table class="table" > <thead> <tr> <th>Income</th> <th>Date</th> </tr> </thead> <tbody> {% for inc in income%} <tr> <td>{{inc.income}}</td> <td>{{inc.date}}</td> </tr> {% endfor %} </tbody> </table> In the views I have added the following filter: income=Income.objects.filters(data__year='2020') At this point, I have created another model that set the reference year as the following: I have the following model class Timing(models.Model): reference_year=models.DecimalField(max_digits=4, decimal_places=0, default="2020") This model have a view with form that give to the client the possibility to register all reference year (2020, 2021 and so on). Now I want to link reference_year with income views.py. How? with a dropdown menu that cointains all reference_year filled. So for example if clients save in timing models a reference_year equal to 2020, in the dropdown the client could select it and the views dynamically update the filter. -
How do I create tag when creating post instance
I have Tag and Post models in many to many relationship. How do I create a tag instance or choose a tag already exist before when creating a post entity. Below is the class in my serializer file class PostSerializer(serializers.HyperlinkedModelSerializer): # display the category name category = serializers.SlugRelatedField(queryset=Category.objects.all(), slug_field='name') author = serializers.SlugRelatedField(queryset=Author.objects.all(), slug_field='username') tags = TagSerializer(many=True, read_only=True) class TagSerializer(serializers.HyperlinkedModelSerializer): posts = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name= 'post-detail' ) -
How to create a Trigram index in Django 3 with multiple columns
I've implemented Trigram Similarity search with annotate which gives me exactly what I want in terms of results; but I have 220,000 records in my database and the search takes 5+ seconds per query which is too long. The search is with 3 columns and one of those invokes a join. How do I add an index or the equivalent SearchVectorField but for Trigram to speed up my query? See current code below: trig_vector = (TrigramSimilarity('make__name', text) + TrigramSimilarity('model', text) + TrigramSimilarity('specification', text)) query_set = cls.objects.annotate(similarity=trig_vector).filter(similarity__gt=0.5).order_by('-similarity') I have tried making my own index from varous posts but I'm not too familiar with index's and each one I've implimente hasn't has an effect on the query time. -
Is there a way to upload large files to github
Please i am trying to upload my django aplplication to github so that i can deploy to heroku, but the files are very large so i am finding it difficult to upload. I used lfs but still after it start compressing the files objects, it get stucked at 99% and later on shows a fetal error. can someone help me out. i am really getting frustrated. I am using postgres as my database and in the files i have some video files that are about 400mb each in size. my static files to are about 300mb. this add to the above question, i also most often face this problem blog/templates/blog commit not checkout when trying to add the files. What might be the cause. -
when ever i am trying to start a project after i have installed django, execution displays No Module Found Error :django module or django.core
(.env) C:\Users\shara\Desktop\testfolder\_djhole>pip install Django (executed) (.env) C:\Users\shara\Desktop\testfolder\_djhole>django-admin start project my site (No Module Found Error). I have repeated this process for a long time. Cannot start working on Django so far due to this ModuleNotFoundError: No module named 'django.core'; 'Django' is not a package I have uninstalled it and reinstalled it several times. when I use pip freeze then asgiref==3.2.7 Django==3.0.7 pytz==2020.1 sqlparse==0.3.1 but still cannot start working on Django because the module is not found an error. By the way, there is only one python version 3.8.3 and added to the path. I hope that there would be some genius out there who could give me some answer because I have searched all over the internet for resolving this diabolical problem and got no company. -
How to work with multidimensional list in python
A multidimensional array is an array containing one or more arrays.This is a definition of multidimensional array in php and below is an example of multidimensional array [employee_experiences] => Array ( [0] => Array ( [company_name] => xyz [designation] => worker [job_description] => abc [started] => 2020-06-09T19:00:00.000Z [ended] => 2020-06-09T19:00:00.000Z ) [1] => Array ( [company_name] => zyz [designation] => worker [job_description] => def [started] => 2020-06-09T19:00:00.000Z [ended] => 2020-06-08T19:00:00.000Z ) ) My question is that how can I get this format in python and save it to the the database I know python can't handle array instead python use lists -
Is there a way to block self-following in Follow model?
My model structure looks like this: from django.db import models class Follow(models.Model): follower = models.ForeignKey('accounts.User', related_name='following', on_delete=models.CASCADE) user = models.ForeignKey('accounts.User', related_name='followers', on_delete=models.CASCADE) class Meta: unique_together = (('user', 'follower',),) def __str__(self): return f'{self.follower.username} follows {self.user.username}' I'm looking for something similar to "unique_together" but for the same user. I know there're possibilities to block it in API but I want it to do it from model level. -
Page not found in django on post request when upload a file
my django project is not working. when i save images getting page not found error and when i remove imageField it saves data successfully when i submit the form with image get this error when i submit the form with out image submitted succesfully