Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django refresh_from_db in transaction
I'm dealing with django legacy project, there is some usage of refresh_from_db method, inside of atomic transaction clause: with transaction.atomic(): self.refresh_from_db() The question is - will the refresh_from_db take existing values in DB? i.e ignoring the transaction and updating the instance? If so its kind of dangerous doing this kind of move -
Search Bar Bringing A Blank Page
I am trying to build a search bar and this is the code in my view.py ''' def searchjobs(request): if request.method == 'GET': query = request.GET.get('q') submitbutton = request.GET.get('submit') if query is not None: lookups = Q(title_of_job__icontains = query) | Q(work_type__icontains = query) | Q(location__icontains = query) | Q(industry__icontains = query) | Q(job_function__icontains = query) results = Job.objects.filter(lookups).distinct() context = {'results': results, 'submitbutton': submitbutton} return render(request, 'job/search.html', context) else: return render(request, 'job/search.html') else: return render(request, 'job/search.html') ''' then for my search.html template, this is what I have ''' {% if submitbutton == 'Search' and request.GET.q != "" %} {% if results %} Results for {{request.GET.q}} {% for result in results %} <div class="container"> <div class="card flex-row" style="box-shadow: 5px 5px lightgrey;"> <div> <img class="rounded-circle card-img" src="{% static 'images/briefcase.png' %}"> </div> <div class="card-body"> <h4><a href="{% url 'job-detail' job.id %}" class="card-link">{{ job.title_of_job }}</a></h4> <h5><a href="" class="card-link">{{ job.publisher }}</a></h5> <h5 class="card-text">{{ job.location }} | {{ job.work_type }}</h5> <h5><a href="" class="card-link">{{ job.job_function }}</a></h5> </div> </div> </div> {% endfor %} {% endif %} {% endif %}''' when I run it in my browser, all I get is a blank page, and not the things that is being put in the search bar. Please I will like … -
Django Channels: URLRouter can't take list as argument
I am working on a project that requires me to use 2 WebSockets with 2 different Consumers but when I try to feed URLRouter with a list it says the list has no attribute 'callback' from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import chat_app.routing, startupapp.routing application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter([ chat_app.routing.websocket_urlpatterns, startupapp.routing.websocket_urlpatterns ]) ) }) Is there a solution or any other way to achieve the same? -
Which one is more convenient to create django form, CreateView or forms.ModelForm
I am very beginner in django. I want to create a post form which be able to have title, content, image/file upload and etc. I am very confused with concept of modelforms and createview. I tried this: blog/view.py: class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content', 'imagefile'] success_url = '/blog/home/' # template_name = 'blog/post_form.html' def __init__(self, *args, **kwargs): super(PostCreateView, self).__init__(**kwargs) # Call to ModelForm constructor def form_valid(self, form): form.instance.author = self.request.user form.save() return super().form_valid(form) blog/templates/blog/post_form.html: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Post::</legend> {{ form|crispy }} <img src='{{ post.imagefile.url }}'> <br><br> </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </div> </form> </div> {% endblock content %} blog/urls.py: from django.urls import path from .views import ( PostCreateView, ) urlpatterns = [ path('blog/post/new/', PostCreateView.as_view(), name='post-create') ] blog/models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) # image = models.ImageField(default='default_post.jpg', upload_to='postimages') imagefile = models.FileField(upload_to='postimages', null=True, verbose_name="") # if user is deleted the idea should be deleted as author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): # return self.title return self.title + ": " + str(self.imagefile) def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) My question: All I … -
Disable email confirmation for super user in django allauth
I am using django-allauth for registering user into my django dashboard application. Here the super user will be logging in and he can see certain data that I am fetching from DB. Whenever someone logs in into the dashboard with super user credential, it asks for email confirmation which I dont want. How can I disable that? -
Module not found Error while deploying website
I am tyring to deploy a django project on pythonanywhere.com, The project runs fine on the local server. I'm using a free account, I have created a virtual env and I've installed all required modules including django. I have also edited the wsgi.py file as follows: path = '/home/karmah24/reporting_portal' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'portal.settings' I'm getting a "Module not found Error: test.urls not found" even though I've added this to the main project urls, and this project works on my local server. https://github.com/Karmah24/reporting_portal is my github repository that I want to deploy. Thanks :) -
PUT request for file in django-react-redux
I tried to apply put request in Django-react-redux for the file. What I was trying to do is, the user should have to replace the file using ID filed from put request. I write the following code in django-restframework. class EarSingleView(APIView): parser_classes = (MultiPartParser, FormParser) def get(self, request, ear_id, *args, **kwargs): ear = Ear.objects.get(pk=ear_id) serializer = EarSerializers(ear) return Response(serializer.data) def delete(self, request, ear_id, *args, **kwargs): ear = Ear.objects.get(pk=ear_id) ear.delete() return Response(status=status.HTTP_204_NO_CONTENT) def put(self, request, ear_id): ear = Ear.objects.get(pk=ear_id) serializer = EarSerializers(ear, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) My get request and delete request working perfectly. But in PUT request, If I tried to change the file filed and try to submit, the following error will occur, 400:Bad request. detail: "Multipart form parse error - Invalid boundary in multipart: None" My form looks like this, <form onSubmit={this.onSubmit} encType="multipart/form-data"> <Input placeholder="Enter layer name..." name="name" value={name} onChange={this.onChange} /> <input type="file" name="fileName" onChange={this.handleFileChange} /> </form> My form onSubmit event is looks like this, onSubmit = (e) => { e.preventDefault(); const { name, file, } = this.state; const newEARData = { id: this.props.idNumber, name, file, }; axios .put(`http://localhost:8000/api/ear/${newEARData.id}`, newEARData, { headers: { "content-type": "multipart/form-data", }, }) .then((res) => { dispatch({ type: UPDATE_EAR, … -
Django - Annotating the sum of a certain field in One To Many model
I am trying to get the sum of revenue of all the sales project, but I am not sure how to do it. Here are my models.py (simplified version but kept all the neccessary parts) class Quotation(models.Model): decisions = ( ('approved', 'Approved'), ('rejected', 'Rejected'), ('pending', 'Pending'), ) quotation_id = models.AutoField(primary_key=True) salesProject = models.ForeignKey('SalesProject' ,related_name='quotations', on_delete=models.CASCADE) quotation = models.MoneyField(max_digits=10, decimal_places=2) decision = models.CharField(max_length = 20, choices = decisions, default='pending') class SalesProject(models.Model): sales_project_id = models.AutoField(primary_key=True) sales_project_name = models.CharField(max_length=100) sales_project_est_rev = MoneyField(max_digits=10, decimal_places=2) What I want to do is to get the sum of all the 'quotation' field under the Quotation model that is tied to the same SalesProject instance. Is there a way to do so? My ideal output would be something like this (where actual_revenue is the sum of all the quotations tied to that particular SalesProject) [{ sales_project_id: 1, sales_project_name: 'Test Project', sales_project_est_rev: 200000, actual_revenue: 150000}, {...}, ...] All help is appreciated, thanks all! -
eb config and .ebextensions/ - .ebextensions/ not working
It is my understanding that editing the config via eb config and via .ebextensions/ both do the same thing. Using eb config directly changes the config were using .ebextensions/ changes the config but is scripted, thus repeatable. Is this correct? Initially, I usesed ebconf to change aws:elasticbeanstalk:container:python: NumProcesses: '1' NumThreads: '15' WSGIPath: application to aws:elasticbeanstalk:container:python: NumProcesses: '1' NumThreads: '15' WSGIPath: project.wsgi # <-- change which worked and I was able to run my application. I then decided I wanted to do all my changes thru .ebextensions/. I reverted the change made with eb config and created the file .ebextensions/02_python.config which contains: option_settings: "aws:elasticbeanstalk:container:python": WSGIPath: project.wsgi NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:environment:proxy:staticfiles": "/static/": "static/" after eb deploy all the chages are reflected when I do eb config except the WSGIPath value is not changed thus my app is no longer working. Why is .ebextensions/02_python.config not overwriting that one value? -
How to fix the “ unexpected token '=' ” error and can't assign to literalPython(parser-80) in python3 Django
I am trying to add the module to urls.py. Here my code: My init.py: from .account import ( AccountIsOwner, ) My view: class AccountIsOwner(StaffuserRequiredMixin, View): def post(self, request, *args, **kwargs): user = get_object_or_404(ReconUser, pk=self.kwargs['pk']) if user.is_account_owner: user.is_account_owner = False user.save() messages.success( self.request, 'User {username} no longer owner'.format( username=user.get_full_name() ) ) else: user.is_account_owner = True user.save() messages.success( self.request, 'User {username} is now an owner'.format( username=user.get_full_name() ) ) next = self.request.POST.get('next', '') if next: url = next else: url = reverse('account_detail', kwargs={'pk': user.pk}) return HttpResponseRedirect(url) my model: is_account_owner= models.BooleanField(default=False) my url: url(r'^user/(?P<pk>.+)/account_owner/$', AccountIsOwner.as_view(), name='account_is_account_owner' ) The errors are on the url: Line 1 can't assign to literalPython(parser-80) Line 2 class AccountIsOwner Mixin allows you to require a user with is_staff set to True. can't assign to literalPython(parser-80) Line 3 name: str can't assign to literalPython(parser-80) The code seems right,but VS reporting an error. -
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