Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Do not wait for database result in async view in Django
I have an async view in Django 3.1: async def log_click(request): await sync_to_async(Click.objects.create(author=request.user)) return HttpResponse('<html>Clicked</html>') Is it possible to improve the performance of this view by not needing to wait for Click instance's creation? I tried omitting await, however in this case the Click object is not created at all. I want this view to finish execution as fast as possible, but still get Click object created. -
GCP AppEngine Deployment Stuck at "Building and pushing image for service [default]"
Problem I'm hoping someone has experience a similar issue. I have a python web-application deployed on Google Cloud Platform's flexible application service. I've updated this site dozens of times before without significant issue. A few days ago, I went to apply a hotfix but when I deployed the app through the GCP SDK, it stopped at "Building and pushing image for service [default]". While this step has typically taken 5 minutes at the most, this time I've left it running for several hours without any change in the console. Attempted Solutions I've run the gcloud components update. I've waited a few days to see if the problem resolved itself on a different day... I'm frankly at a loss. There aren't any error logs to be found and my google searching hasn't come up with any similar problems. -
Is there any way to accept only business/company emails that signup through Google Signup in django?
I want to restrict users with simple email by accessing the website, but also i would like to keep the sign up from google form, and i want to restrict it only to users who have a company email with gsuite. I am using social-auth-app-django==3.1.0 with django==3.0.2. -
Registration Form not saving data in Profile Model, using extended Django User model
Recently i am facing a problem in registration. I have made a ** accounts** app in my project for registrations. I don't want to save data in default **User** model in dB. So I have extended **User** model with **OneToOne** relationship with **Profile** model and trying to save the data into "Profile" model but when I submitting the form I don't get any error but data don't save in "Profile" DB. here is my models.py where I make OneToOne Relationship with default "User" model. from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone=models.CharField(max_length=20) address=models.CharField(max_length=150) def __str__(self): return self.user.username I am trying to make ProfileForm form and InfoProfileForm form here to get the form data in forms.py. from django import forms from django.contrib.auth.models import User from .models import Profile from django.contrib.auth.forms import ReadOnlyPasswordHashField class ProfileForm(forms.ModelForm): password = forms.CharField(max_length=20, widget=forms.PasswordInput) #form = ProfileForm(data=request.POST, user=request.user) class Meta: model = User fields=('username','email','password') #extra info class InfoProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('phone','address') Here is my Views.py where I am trying to merge two models (default User model and Profile model) from django.shortcuts import render from django.http import HttpResponse, JsonResponse # Create … -
uwsgi ImportError: No module named site
I've looked at the other similar questions, but mine is a different one. I tried to migrate a django app from one server to a new server and copied the entire file system of the app from the old server to the new server, including the environment folder. I have no problems to start nginx on the new server, but when I tried to start uwsgi, I got the errors as shown below. $ sudo uwsgi --ini /home/devuser/webapps/myproj-env/myproj/server/uwsgi/myproj.ini [uWSGI] getting INI configuration from /home/devuser/webapps/myproj-env/myproj/server/uwsgi/myproj.ini *** Starting uWSGI 2.0.9 (64bit) on [Mon Aug 24 14:13:03 2020] *** compiled with version: 4.4.7 20120313 (Red Hat 4.4.7-11) on 31 January 2015 12:37:00 os: Linux-3.10.0-1127.13.1.el7.x86_64 #1 SMP Fri Jun 12 14:34:17 EDT 2020 nodename: rhlnx01 machine: x86_64 clock source: unix detected number of CPU cores: 2 current working directory: /home/devuser/webapps/myproj-env/bin detected binary path: /home/devuser/webapps/myproj-env/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! setgid() to 2147186151 set additional group 986 (nginx) set additional group 20001 (spinner) setuid() to 2122832 chdir() to /home/devuser/webapps/myproj-env/myproj/server/uwsgi//../.. *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 31117 your memory page size is 4096 bytes detected max file descriptor number: 1024 … -
Querying with id and other fields vs querying with id and checking others after
For a large database, it's faster (and thus better) to grab the object with the id only and then check if the user matches, right? # Option A post = get_object_or_404(Post, id=post_id, owner=request.user) # Option B post = get_object_or_404(Post, id=post_id) if post.owner != request.user: raise Http404() -
Django KeyError when session variable exists
I'm getting a KeyError because the session variable is not found. However, I know the session variable exists and is displayed in the prior page. I tried to update settings.py with SESSION_ENGINE = ''django.contrib.sessions.backends.db' As explained in this question, but it didn't work. Django Session KeyError when key exists Python 3, Django 2.7 -
Select instance/row with max field/column value per with field/column (group by)
So, I have these models: class Computer(models.Model): hostname = models.CharField(primary_key=True, max_length=6) <other computer info fields> class ComputerRecord(models.Model): id = models.AutoField(primary_key=True) pc = models.ForeignKey(Computer, on_delete=models.CASCADE) ts = models.DateTimeField(blank=False) <other computerrecord info fields> I want to get the row / computerrecord instance that has the max ts for each pc (Computer model) In sql would be something like this: SELECT hub_computerrecord.* FROM hub_computerrecord JOIN ( SELECT pc_id, MAX(ts) AS max_ts FROM hub_computerrecord GROUP BY pc_id ) AS maxs ON hub_computerrecord.pc_id = maxs.pc_id WHERE hub_computerrecord.ts = maxs.max_ts; -
if statmen not working well in django please help me
I want to show and hide HTML elements depends on the content of the data I receive after pressing the button. data will be created after pressing the button (its output of another py file) but the if statement not working {% if data == 'empty' %} its shows the image not the massage i want. {% load static %} <html> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <head> <title> Analyze your tweets </title> </head> <br> <br> <h1 class="text-light">Analyze Emotions in Your 2020 Tweets &#128526; </h1> <br> <br> <form action="/external/" method="post"> <div class="outter" aria-label="actionButtons"> <div class="inner"> {% csrf_token %} <label>Enter your @</label> <input id="username" type="text" name="param" placeholder="Username" required > <input id="btnSearch" type="submit" value="Analyze" onclick="show();"> </div> </form> </div> <div class="outter"> <div class="inner"> <div class="lds-ellipsis" id="load" style="display: none;"><div></div><div></div><div></div></div> </div> </div> <div class="outter"> {% if data %} {% if data == 'empty' %} <h5 style="font-family:Lato; color: azure; font-size: 18;">Sorry the username you looking for is either private or doesn't exist </h5> {% endif %} <div class="inner"> <h5 style="font-family:Lato; color: azure; font-size: 18;">Here is your result <span style="color:black;">@{{data}}</span></h5> <img id="pic" src="{% static 'images/graph.png' %}" width="640" height="480" /> </div> {% endif %} </div> <br> <br> <div class="outter2"> <h5>This website will <u>not</u> violate your Account Privacy.</h5> … -
Unable to send messages form Wagtail form using gmail
I'm trying to use my Gmail account to receive messages form my Wagtail/Django app. The messagesget added to Forms in admin panel and get printed in the console, however, they do not get send to and from my gmail account. My settings ass below: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'mg@gmail.com' EMAIL_HOST_PASSWORD = 'Password$' EMAIL_USE_TLS = True EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL ='noreply@mysite.com' EMAIL_TO = 'mg@gmail.com' I tried to overwrite sent_mail function in ContactForm(AbstractEmailForm) and replace from_address and to_address with DEFAULT_FROM_EMAIL and EMAIL_TO. No success. -
How to disable next URL parameter while using login_required decorator in django?
I have the following project folder structure in Django: . |_blog/ |_django_blog/ |_users/ |_manage.py I have the following in django_blog/urls.py: from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog.urls')), path('profile/',user_views.profile,name='profile'), path('register/',user_views.register,name='register'), path('login/',auth_views.LoginView.as_view(template_name='users/login.html'),name='login'), path('logout/',auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'), ] And I have the following decorated view in users/views.py: from django.contrib.auth.decorators import login_required @login_required def profile(request): return render(request,'users/profile.html') And following constants in django_blog/settings.py: LOGIN_REDIRECT_URL = 'blog-home' LOGIN_URL = 'login' Now if user is not logged in and tries to access /profile/ URL he will be redirected to login page with next=/profile/ paramter passed in to the URL. After the user signs in, it redirects the user to /profile/. But I want the user to be redirected to the homepage instead which is the default behaviour of signing in from /login/ URL. How should I implement that functionality? -
Django Decimal field with value Decimal(0.00) is displayed as 0E-10 in the Django Admin Inline
Model Definition. class ExampleModel(BaseModel): price = models.DecimalField(max_digits=20, decimal_places=10) margin = models.DecimalField(max_digits=20, decimal_places=10) If the user saves margin or price as "0" it would be displayed as "OE-10" on the next page load. Screenshot is from DjangoAdmin. -
400 Bad Request while updating Django model with form-data
I am trying to update my Django model with axios and i send data as form-data. I use PATCH method while i want to make changing fields optional. This however is not working and i got 400 Bad Request error .There is also DRF serializer and APIview in the backend. Only field that i can update through form is my imagefield. What could cause error here? How form-data gets sent: handleFormSubmit = (event) => { event.preventDefault(); let form_data = new FormData(); form_data.append('name', event.target.elements.name.value); form_data.append('email', event.target.elements.email.value); form_data.append('location', event.target.elements.location.value); form_data.append('sport', this.state.sport); form_data.append('image', this.state.file); const profileID = this.props.token let url = `http://127.0.0.1:8000/api/profile/${profileID}/update` axios.patch(url, form_data, { headers: { 'content-type': 'multipart/form-data' } }) .then(res => console.log(res)) .catch(error => console.err(error)); } In my UpdateAPIView i also have parser_classes which should handle issue, but it doesn't class ProfileViewUpdate(generics.UpdateAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'token' lookup_url_kwarg = 'pk' parser_classes = (MultiPartParser, FormParser) Thanks in advance! -
Django: Create zipfile from S3 using django-storage
I use django-storages and have user related content stored in folders on S3. Now I want users to have the ability to download all their files at once, preferably in a zip file. All the previous posts related to this are old or not working for me. The closest to working code I have so far: from io import BytesIO import zipfile from django.conf import settings from the_bookie.tax_returns.models import IncomeTaxReturn from django.core.files.storage import default_storage class DownloadIncomeTaxFiles(View): def get(self, request, id): itr = IncomeTaxReturn.objects.get(id=id) files = itr.attachments zfname = 'somezip.zip' b = BytesIO() with zipfile.ZipFile(b, 'w') as zf: for current_file in files: try: fh = default_storage.open(current_file.file.name, "r") zf.writestr(fh.name, bytes(fh.read())) except Exception as e: print(e) response = HttpResponse(zf, content_type="application/x-zip-compressed") response['Content-Disposition'] = 'attachment; filename={}'.format(zfname) return response This creates what looks like a zipfile but the only content it has is '<zipfile.ZipFile [closed]>' I got many different results, mainly with errors like zipfile expecting string or bytes content while a FieldFile is provided. At this point I'm completely stuck. -
FileNotFoundError: A json file not found after pushing it to heroku
I am working on a website. For this website I have to create a table which shows the time of the meeting and the participants of it. I am writing the code of site using Django. For the table I have a data on a .json file. When I run the server locally it works fine and when I push it to heroku it raises FileNotFoundError. I found this question which faces with the similar problem but the answer shows how to log something, but I need .json file for data. My django app directory: 66 admin.py 100 apps.py <DIR> migrations 60 models.py 3,332 schedule_of_teams.json <DIR> static <DIR> templates 63 tests.py 333 urls.py 807 views.py So I have a view function in views.py file: def schedule_of_teams(request): with open('./schedule_of_teams.json',encoding='utf-8') as f: context = json.load(f) context['title'] = 'Yarış cədvəli' return render(request,'schedule_of_teams.html',context) And open context manager raises the error: FileNotFoundError at /schedule_of_teams/ [Errno 2] No such file or directory './schedule_of_teams.json/' So why is this happening? Why it works fine when I run python manage.py runserver with localhost but when I push to heroku it raises this exception? Is heroku ignores .json files? By the way, I do not have *.json on my .gitignore … -
Changing the choices of the model in the ModelSerializer
please I need your help, I have choices in the model and make model Serializer from this model but need to modify on those choices as i use filterset in the Serializer so i need to add more options in the dropdown menu, here is the code. Serializer.py: class BlaListSerializer(serializers.ModelSerializer): STATUS_new1='new1' STATUS_new1='new2' STATUS_FOLLOWED = 'followed' STATUS_CREATED = 'created' STATUS_CHOICES = ( (STATUS_new1, _('New1')), (STATUS_new2, _('New2')), (STATUS_FOLLOWED, _('Followed')), (STATUS_CREATED, _('Created')), ) status = serializers.ChoiceField(choices=STATUS_CHOICES) class Meta: model = Bla fields = ( "id", "title", "status", ) model.py: class Bla(ProjectBaseModel, AuditLogMixin): STATUS_FOLLOWED = 'followed' STATUS_CREATED = 'created' STATUS_CHOICES = ( (STATUS_FOLLOWED, _('Followed')), (STATUS_CREATED, _('Created')), ) title = models.CharField(max_length=200, blank=True, null=True, verbose_name=_('Title')) status = models.CharField(max_length=200, blank=False, null=True, choices=STATUS_CHOICES) view.py: class MyBla(ListAPIView): serializer_class = BlaListSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['status', ] my problem is that the status isn't updated with the new options in the DRF -
How does Django manage different subdomains on one Django project?
I want my Django project to be accessible at many different endpoints. For one app, I want it accessible at app.domain.com and for another app I want it accessible at dashboard.spira.ai. How can I achieve this? I am using AWS Elastic Beanstalk and Route 53. I tried looking at Django's djangoproject.com and their Github repo, as they do this. However, I couldn't figure it out. Thanks! -
Formatting a JSON Response to build a URL
I'm incredibly stuck on trying to format receive a JSON response, and format it. Order of operations: Query a REST API endpoint (https://endpoint.com/api/v1/employee?id={username}) Receive JSON response: {"employee":{"full name":"Example Name","function":"Role","office":"Office Location",team":"Team 1|Team 2|Team 3|"}} In my base.js file within my django app, I am hoping to extract the team strings and pass them into another URL. What way can I do this? When I $.getJSON from the endpoint I receive responseJSON, responseText, etc. but I'm unable to pull them out/use them in any way. -
How can I access parent model fields in a form using the child model?
For context, I'm trying to create a form that allows users to upload info about their own custom Pokemon. Basically, they are creatures that you can catch, name, and level up. To draw a comparison, it is a similar concept to dogs; there are labradors, German Shepherds, huskies, etc. that would be variations of a base Dog model, but then each individual would have a name and other defining characteristics. I've created Pokemon and CustomPokemon models and imported the latter into my forms.py file. I'm trying to access some parent fields but am unable to: from django import forms from .models import CustomPokemon class PokemonForm(forms.ModelForm): class Meta: model = CustomPokemon fields = ['pokemon.poke_name', 'name', 'level'] The poke_name field is inherited from the parent Pokemon model while the other two fields belong to the CustomPokemon model. I'm getting this FieldError: Unknown field(s) (pokemon.poke_name) specified for CustomPokemon. The issue isn't resolved by using poke_name, so I'm curious how I can access the parent model's fields so they can be displayed in the form. -
Why is my print statement not showing up in django runserver?
I've been using django for only 3 days and the biggest problem that I've had with it is that i can't print() stuff with it in the runsever terminal i'm using django 2.1.5 this is what I've done def test(request): print('test') return HttpResponse('test') the code works fine but it's not displaying the print(), it seems to work with everyone else is maybe there's another way to display it to the terminal? I've tried using python logging as well it's still not displaying anything P.S sorry for such a simple question but i'm that kind of guy that can't read documentation -
How to correctly query to a Foreign Key in Django?
I have a group of models Cluster, Server and Service which have a relationship, through a ForeignKey, one-to-many, as the following snippet: class Server(models.Model): cluster = models.ForeignKey(Cluster, null=True, on_delete=models.PROTECT) shortname = models.CharField(max_length=20, null=False) . . . class Service(models.Model): host_server = models.ForeignKey(Server, null=False, on_delete=models.PROTECT) name = models.CharField(max_length=20, null=False) technology = models.CharField(max_length=20, null=False) . . . And now I am trying to get a set of Servers in a query, along with the related Services using def infra(request, cluster_name): cluster = Cluster.objects.get(name__iexact=cluster_name) servers = Server.objects.filter(cluster_id=cluster.id).order_by('shortname') services = Service.objects.filter(host_server__in=servers).order_by('id') template = 'webapp/infra.html' context = { 'cluster':cluster, 'servers':servers, 'services':services, } return render(request, template, context) However, on the view, I am getting all the services in a single QuerySet instead of a QuerySet per Server containing only the Services associated with it. As a workaround to this, I used the following: <h5>Services</h5> <ul class="list-group"> {% for service in services %} {% if service.host_server_id == server.id %} <li class="list-group-item">{{ service.name }}</li> {% endif %} {% endfor %} </ul> But I have the feeling that there must be a way to iterate through the services of each server in a more elegant way than going through absolutely all of the services each time and then deciding if … -
Django field lookup - sequence of letters
I would like to be able to search trough a database attribute with sequences of letters rather than words. Example: The MySQL database has an attribute called breadcrumb_text containing the following: HomeMonclerMenClothingTrousersMonclerTrousersMonclerTrousers With my current code (see below), if I search with "Moncler Trouser" as keywords, or just "Moncler", no result will be returned. product_list = Products.objects.filter(Q(breadcrumb_text__icontains= search_text)).all() I have to search for the precise attribute to get a result. I would like the code to look for any sequence of letters contained in the attribute that matches each keywords. Can someone help me with that? Many thanks in advance, Kind regards -
Django - How to change the default queryset in a view if a filter is used?
I have a Django project, in which, in my view, I have this: def get_queryset(self, **kwargs): qs = super(OrderTableView, self).get_queryset() if self.request.user.profile.store is not None and self.request.user.is_superuser is False: qs = qs.filter(store=self.request.user.profile.store) today = datetime.datetime.now().date() qs = qs.filter(total__gt=0).filter(address__isnull=False).filter(location__isnull=False).filter(date__date=today).order_by('-date') return qs This works correctly, I want only the orders from the day to be displayed when the view loads, and this works correctly. However, in the view I also have filters for the date, which I want to use to filter the date if the user so chooses. This filter, for example, filters all the dates after the date selected in the filter. def filter_date(self, queryset, name, value): yesterday = datetime.date(year=value.year, month=value.month, day=value.day) - datetime.timedelta(days=1) queryset = queryset.filter(date__gt=yesterday) return queryset The problem is that, as far as I understand, the get_queryset method works first, and so, when arriving to the filters, the queryset already excludes all dates that are not from today, which is fine when the view loads, but should not always occur, since sometimes I'd like to include orders in dates other than today, if I'm searching, for instance. Is there a way in Django to set an initial queryset to a view, but then using a different queryset … -
Can't pass model data in templates django
I want to pass data from 'About' model to html template, but I can't figure out what is going wrong.. as I am new to Django. I gave lot of time to it.. but it still remains the same: from django.db import models class About(models.Model): image = models.ImageField(upload_to = 'pics') desc = models.TextField() views.py from django.shortcuts import render from .models import About def index(request): abt = About.objects.all() return render(request,'home/index.html',{abt:'abt'}) html <img src="{{abt.image}" alt="profile photo"> <p>{{abt.desc}}</p> -
django : calculate with function each line of your db
I would like to calculate 'total' for each line, with the following code, it shows only last line total, not each line total. class Invoice(models.Model): date = models.DateField(default=timezone.now) client = models.ForeignKey(Client,on_delete=models.CASCADE) def total(self): items = self.invoiceitem_set.all() for item in items: amount_due = (item.price * item.quantity) return round(amount_due, 2) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(max_digits=20, decimal_places=2) HTML {% for product in object.invoiceitem_set.all %} <tr> <td>{{product.product}}</td> <td>{{product.price}}</td> <td>{{product.quantity}}</td> <td>{{object.total}}</td> </tr>