Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Flitering django queryset based on ManyToManyField
In my Request model, there is a field requested_to which is a ManyToManyField requested_to = models.ManyToManyField(OrganizationUser) I want to filter queryset of Request model where a organization_user is not in requested_to -
DJango Query Issue
I am making a Blog website where my blog post model is related to User model using many-to-many relation for the likes. Now I am querying the DB for getting the likes count for each specific post. This is the Query that I have written -> posts = Post.objects.select_related().prefetch_related('images_set','comments_post').annotate(Count('comments_post')).annotate(Count('Likes')).all() Now When I see the actual Query that is being made to the DB and the result It all looks fine and the No of queries are also made to DB are fine. I am getting a column named 'LIKES__COUNT'. Now I am unable to use this column name in my template. Can anyone help me out on how to use this in the template? This is the result That I am getting from the DB. -
How to switch wagtail homepage depending on user logged in status
I have previously been using path("", include(wagtail_urls)) for my home_page url which displays the template at home/home_page.html correctly I wish to however display different pages depending on whether a user is logged in or not so have changed this to: def logged_in_switch_view(logged_in_view, logged_out_view): '''switches views dependedn on logon status''' def inner_view(request, *args, **kwargs): if request.user.is_authenticated: return logged_in_view(request, *args, **kwargs) return logged_out_view(request, *args, **kwargs) return inner_view urlpatterns = [ path("", logged_in_switch_view( TemplateView.as_view(template_name="home/home_page.html")), TemplateView.as_view(template_name="home/not_authenticated.html")), name="home"), ] With this approach (directly specifying the template rather than using wagtail_urls) the home page does not display correctly when logged in, in that all the wagtail tags in the html e.g. the blog posts are not displaying home_page.html {% extends "base.html" %} {% load wagtailcore_tags wagtailimages_tags %} {% block content %} <main class="container"> {% for post in page.blogs %} {% with post=post.specific %} <div class="col-md-8 mx-auto px-auto"> <div class="row border rounded overflow-auto flex-md-row mb-4 shadow-sm position-relative "> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">{{ post.category }}</strong> <div class="mb-1 text-muted">{{ post.date }}</div> <h3 class="mb-0">{{ post.title }}</h3> <p>{{post.intro}}</p> </div> <div class="col-auto my-auto py-2 px-2 d-none d-lg-block"> <a href="{% pageurl post %}" class="stretched-link"> {% with post.main_image as main_image %}{% if main_image %} {% image main_image min-250x250 … -
How to raise custom validation error for a serializer field?
class SomeSerializer(serializers.ModelSerializer): first_name = serializers.CharField(validators=[RegexValidator( regex=(r"^[a-zA-Z_ \- \. \' ]+$"), message="Enter a valid first name")]) phone = serializers.IntegerField(source="user.phone") Now, this phone field since called an integer field, is giving a validation error, "Enter valid integer". How can I make that a custom message? -
Django All Columns Are Distinc
Given that I have a data. id, street, city 1, Main Street, Hull 2, Other Street, Hull 3, Bibble Way, Leicester 4, Bibble Way, Leicester 5, High Street, Londidium 6, High Street, Londidium I want to distinct so that it would only delete Bibble Way, Leicester and High Street, Londidium because it is the only entry where all columns have a duplicate. I already tried .distinct('street','city') but it deletes if either street or city has a duplicate. I want to only delete if all columns match. Whats the right query to get result of id, street, city 1, Main Street, Hull 2, Other Street, Hull 3, Bibble Way, Leicester 5, High Street, Londidium -
What would cause the same Django template include block to behave differently twice on the same page?
I'm including a simple pagination template into a template that lists blog posts. It gets output without getting interpreted, as in, I see the double curly brace enclosed tag as text in the resultant webpage. But, when debugging, I pasted same block higher in the page, and it gets interpreted fine. Between the two, I iterate over the same object that gets passed to the pagination template, so this is probably something that I don't understand about the state of that object? Or Django's rendering process. {% extends "blog/base.html" %} {% block title %}My blog site thing{% endblock %} {% block content %} <h1>Blog site</h1> **{% include 'pagination.html' with page_object=posts %}** {% for post in posts %} <h2><a href="{{post.get_absolute_url}}">{{ post.title }}</a></h2> <p class="date">Published {{post.publish}} by {{post.author}}</p> {{post.body|truncatewords:5|linebreaks}} {% endfor %} **{% include 'pagination.html' with page_object=posts %}** {% endblock %} Pagination.html <div class="pagination"> <span class="step-links"> {% if page_object.has_previous %} <a href="?page={{ page_object.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ page_object.number }} of {{ page_object.paginator.num_pages }}. </span> {% if page_object.has_next %} <a href="?page={{ page_object.next_page_number }}">Next</a> {% endif %} </span> </div> views.py for this app from django.shortcuts import render, get_object_or_404 from .models import Post from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def post_list(request): … -
Need to link the Loggin User with the User model created by me in django framework
User Model class User(models.Model): BLOOD_GROUP_CHOICES = ( ('a+','A+'), ('a-','A-'), ('b+','B+'), ('b-','B-'), ('ab+','AB+'), ('ab-','AB-'), ('o+','O+'), ('o-','O-') ) BILLABLE_and_NON_BILLABLE_CHOICES=( ('Billable','Billable'), ('Non-Billable','Non-Billable') ) employee_name = models.CharField(max_length=50) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) pancard=models.CharField(max_length=25,default=None) aadhar=models.CharField(max_length=20,default=None) personal_email_id=models.EmailField(max_length=254,default=None) phone = PhoneNumberField() emergency_contact_no=models.IntegerField(default=None) emergency_contact_name=models.CharField(max_length=100,null=True) relation=models.CharField(max_length=25,default=None) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True) designation=models.ForeignKey(Designation,on_delete=CASCADE,related_name="designation") billable_and_non_billable=models.CharField(max_length=25,choices=BILLABLE_and_NON_BILLABLE_CHOICES,default='Billable') joining_date=models.DateField(max_length=15,null=True) relieving_date=models.DateField(max_length=15,null=True) class Meta: db_table ='User' def __str__(self): return self.employee_name serializers class UserSerializers(serializers.ModelSerializer): #Email Notification def create(self, validate_data): subject = 'Your account was activated' plain_message = 'SAMPLE TEXT' from_email = 'demomaster147@gmail.com' to_email = validate_data['email'] EmailThread(subject, plain_message, from_email, to_email).start() return User.objects.create(**validate_data) dob=DateField(input_formats=DATE_INPUT_FORMATS) class Meta: model= User fields ='__all__' password = serializers.CharField(max_length=128, write_only=True, required=True) admin class StaffAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) #job = qs.filter(job_name='test job').first() #print(f"\nQUERY : {job}\n") #print(f"\nQUERY USER : {job.user}\n") print(f"\nrequest.user : {request.user}\n") if request.user.is_superuser: return qs return qs.filter(user__id=request.user.id) #Admin SuperUser @admin.register(User) class UserAdmin(ImportExportModelAdmin): list_display = ('id','employee_name','email','billable_and_non_billable','designation') search_fields = ['employee_name'] pass Actually with the above code I couldn't able to get the details of logged in user details or user inputted data alone. I have a User model created to add the details of the user in my project and that is not connected with the logged in user. for example (if i register a user as "vinoth" with username and email, and i entered a user with the same details … -
I create a One to One realtionship in django Multitable-Inheritance but it not show Book-id in my child class Table and also show Integrity Error Why?
This is my models.py : class Book(models.Model): Book_Name = models.CharField(max_length=100, default="Don Quixote") Author_Name = models.CharField(max_length=100, blank=True, default="Miguel de Cervantes") Price = models.FloatField(default=175.00) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) def __str__(self): return self.Book_Name class ISBN(models.Model): book = models.OneToOneField(Book, on_delete=models.CASCADE, parent_link=True, primary_key=True) Isbn = models.CharField(max_length=100) def __str__(self): return self.Book_Name in according to my code every Book has one isbn number but in admin panel ISBN table don't show book attributes or don't show any book-id. it show only Isbn column and after i give input in this column it show me error "IntegrityError at /admin/inheritance/isbn/add/" and "NOT NULL constraint failed: inheritance_isbn.book_id" This is my admin.py : @admin.register(Book) class PostAdmin(admin.ModelAdmin): list_display = ['Book_Name', 'Author_Name', 'Price'] @admin.register(ISBN) class PostAdmin(admin.ModelAdmin): list_display = ['book', 'Isbn'] I'm a noob to python and Django so any help would be greatly appreciated. -
Does live travel tracking of user possible in django website
I am working on Django website and I want to implement user live travel tracking.Is it possible to implement live tracking of user in the Django website.If Yes, How it is possible. -
Plotly chart not showing in django web app
I've been trying to do this for hours and I still can't figure it out. This is my code for the plot in 'functions.py' def candles(): symbol = 'AAPL' stock = yfinance.Ticker(symbol) hist = stock.history(period='1y', interval='1d') figure = go.Figure(data = [go.Candlestick(x =hist.index, open = hist['Open'], high = hist['High'], low = hist['Low'], close = hist['Close'])]) x_axis = figure.update_xaxes( title_text = 'Date', rangeslider_visible = True, rangeselector = dict( buttons = list([ dict(count = 1, label = '1M', step = 'month', stepmode = 'backward'), dict(count = 6, label = '6M', step = 'month', stepmode = 'backward'), dict(count = 1, label = 'YTD', step = 'year', stepmode = 'todate'), dict(count = 1, label = '1Y', step = 'year', stepmode = 'backward'), dict(step = 'all')]))) layout = figure.update_layout( title = { 'text': 'AAPL', 'y':0.9, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'}) y_axis = figure.update_yaxes( title_text = 'AAPL Close Price', tickprefix = '$') chart = plot(figure, x_axis, layout, y_axis, output_type = 'div') return chart My 'views.py' def chartView(request): candlestick = candles() context={ 'candlestick' : candlestick } return render(request, 'portfolio.html', context) In portfolio.html I'm using {{candlestick | safe}} -
why is the url in django not reading the primary key and just reading it like a string?
def lead_update(request,pk) : lead = Lead.objects.get(id=pk) form = LeadForm() if request.method == "POST" : form = LeadForm(request.POST) if form.is_valid() : first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] age = form.cleaned_data['age'] lead.first_name = first_name lead.last_name = last_name lead.age = age lead.save() return redirect("/leads/{{ lead.pk }}/") # the problem context = { "form" : form, "lead" : lead } return render(request,"leads/lead_update.html",context) on debug : it is showing The current path, leads/{{ lead.pk }}/, didn't match any of these. -
How to refresh image with new random one from list in Django
I have a working function that loads a random image from a collection of images in firebase and displays it in template. However the image doesn't seem to reload on page refresh and that is exactly what I want. How can I achieve this? Working Function. def fetchsliderimages(): big_list = [] ref = dbs.reference('cartoons/sliderimages') snapshot = ref.order_by_child("timestamp").limit_to_last(100).get() if snapshot: for value in snapshot.values(): big_list.append(value['image']) image = random.choice(big_list) return image How I Load The Image <img width="100%" height="110%" src="{{ summary.sliderimages }}"> -
How to keep django rest API server running automatically on AWS?
So I uploaded my Django API with Rest framework on AWS EC2 instance. However, I have to manually go to Putty and connect to my EC2 instance and turn API on whenever I want to use it. When I turn off my PC, putty closes and API cannot be accessed anymore on the ip address. How do I keep my API on forever? Does turning it into https help? Or what can be done? -
Why this python returned value is changing type after assignment
I'm puzzled by this piece of code. The code below is a copy of renderer.py module from django rest framework. Than led me to study a lot of Python inner workings but I still can't understand what is going on with the return / assignment behavior of self.get_template_context function. def render(self, data, accepted_media_type=None, renderer_context=None): (...) print('1', id(data), data) context = self.get_template_context(data, renderer_context) print('4', id(context), context) (...) def get_template_context(self, data, renderer_context): print('2', id(data), data) response = renderer_context['response'] if response.exception: data['status_code'] = response.status_code print('3', id(data), data) return data So the render function calls get_template_context passing two variables, data and renderer_context. The function then includes the status_code on data dictionary before returning it (if exception). I put some print statements to see what is going on with this small piece of code: 1 1730745664704 <class 'rest_framework.utils.serializer_helpers.ReturnDict'> {'date': '', 'memo': ''} 2 1730745664704 <class 'rest_framework.utils.serializer_helpers.ReturnDict'> {'date': '', 'memo': ''} 3 1730745664704 <class 'rest_framework.utils.serializer_helpers.ReturnDict'> {'date': '', 'memo': ''} 4 1730745396352 <class 'dict'> {'data': {'date': '', 'memo': ''}, 'serializer': TransactionSerializer(context={'request': <rest_framework.request.Request: POST '/ledger/ledgers/1/transactions/'>, 'format': None, 'view': <ledger.views.TransactionViewSet object>}): url = NestedHyperlinkedIdentityField(parent_lookup_kwargs={'ledger_pk': 'ledger__pk'}, view_name='transaction-detail') date = DateTimeField() memo = CharField(allow_blank=True, required=False, style={'base_template': 'textarea.html'}) entries = EntrySerializer(many=True, required=True): url = NestedHyperlinkedIdentityField(parent_lookup_kwargs={'transaction_pk': 'transaction__pk', 'ledger_pk': 'transaction__ledger__pk'}, view_name='entry-detail') value = DecimalField(decimal_places=5, … -
Django Model - special characters in field name
I'm creating model for my app. Unfortunately I'm working with measurements units like km/h, kg CO2/ton, heat content (HHV) - 30 different units at all. I don't know how to save it properly in django model or maybe in serializer to make it display proper unit name, including "/", " ", "(" in REST Responses. Also I will be importing data through django-import-export module so it should recognize excel columns which will be named like actual unit name. For example: class Units(models.Model): km_h = models.FloatField(default=-1, null=True) kg_co2ton = models.FloatField(default=-1, null=True) and I would like to have this data available in the following form: class Units(models.Model): km/h = models.FloatField(default=-1, null=True) kg co2/ton = models.FloatField(default=-1, null=True) How to write model and/or serializer to make it work and look good? -
How to deploy a Django and React project on the same Ubuntu 18.04 server using gunicorn and nginx?
I have a Django project that I have already successfully deployed on my Ubuntu 18.04 server via gunicorn and nginx using this tutorial. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 The project uses Django Rest Framework and I'm able to access it's endpoints via a web browser. However, I would also like to deploy a separate react project on the same server, so that it can send http requests to the Django app and display data received from the REST API. How can I go about doing this? Here is my current gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/my_project/coffeebrewer ExecStart=/home/ubuntu/my_project/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/my_project/coffeebrewer/coffeebrewer.sock coffeebrewer.wsgi:application [Install] WantedBy=multi-user.target And here are my current nginx configurations server { listen 80; listen [::]:80; server_name my_ipv6_address; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root root /home/ubuntu/my_project/coffeebrewer; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
Maintaining current URL after incorrect password entry -- Django
def login_view(request): if request.method == "POST": form = AuthenticationForm(data=request.POST) if form.is_valid(): user= form.get_user() login(request, user) if "next" in request.POST: return redirect(request.POST.get('next')) else: print('failed to redirect after login') return redirect('articles:list') <form class="site-form" action='.' method="post"> {% csrf_token %} {{ form }} {% if request.GET.next %} <input type="hidden" name="next" value="{{ request.GET.next }}"> {% endif %} <input type="submit" value="Login"> </form> So the issue I am having is that when I use the @login_required parameter on a specific view function in Django. Things work fine initially. The URL contains ?next=/original/url and the form is correctly able to collect the request.POST.next value of the dictionary it returns and send it back to the login function. Then if you put the password in correctly, it redirects you back to the page you were originally trying to get to via the value of the request.POST.next value THE ISSUE: This only works if you get the password right on the first try. If you enter the password incorrectly, it loses the ?next= part of the url tag and just goes to the default log in page. Thus, when you get the password right the second time, it does not redirect you back to the page you were trying to … -
Unable to login if I register the user using post man or with API in django
unable to login the user if the register the user with postman or with API, but if the register the same user in django admin i can able to login and generating the token. Please help me on this. my serializer code: class UserSerializerWithToken(UserSerializer): token = serializers.SerializerMethodField(read_only=True) class Meta: model = NewUser fields = ['_id','token'] def get_token(self,obj): token = RefreshToken.for_user(obj) return str(token.access_token) my token generation code: class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) # data['username'] = self.user.username serializer = UserSerializerWithToken(self.user).data for k, v in serializer.items(): data[k] = v return data class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer I have created the custom model I think i have problem with the register one but once I register the token is generating but if i am logging in its is saying in valid credentials @api_view(['POST']) def registerUser(request): data = request.data try: user = NewUser.objects.create_user( email=data['email'], first_name=data['first_name'], last_name=data['last_name'], password=make_password(data['password']), ) serializer = UserSerializerWithToken(user, many=False) return Response(serializer.data) except: message = {'detail': f'User with email: {data["email"]} already exists'} return Response(message, status=status.HTTP_400_BAD_REQUEST) -
wagtail django.core.exceptions.FieldError: Unknown field(s); Fields doesn't exist anywhere
my python manage.py makemigrations return error with message File "/usr/local/lib/python3.6/site-packages/django/forms/models.py", line 268, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (seo_title_fr, title_fr, search_description_en, slug_en, seo_title_en, slug_fr, search_description_fr, title_en) specified for PostPage I did serch everywhere in the code where are this fields I didn't find theme at all I did search in database wagtailcore_page I didn't find that fields id | path | depth | numchild | title | slug | live | has_unpublished_changes | url_path | seo_title | show_in_menus | search_description | go_live_at | expire_at | expired | content_type_id | owner_id | locked | latest_revision_created_at | first_published_at | live_revision_id | last_published_at | draft_title | locked_at | locked_by_id | translation_key | locale_id | alias_of_id | url_path_en | url_path_fr I did search in all the code including migrations but not found anything I did try : python manage.py update_translation_fields but no luck my model is : import json from django.db import models from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import slugify from django.utils.timezone import now from django.shortcuts import render from django.http import HttpResponse, JsonResponse,HttpResponseRedirect, Http404 from django.template.response import TemplateResponse from django.forms import FileField from django.core.serializers.json import DjangoJSONEncoder from wagtail.core.models import Page from wagtail.core.fields … -
How to know when heroku rotate my heroku postgres credentials?
Heroku rotate the credentials on heroku postgres, how can i prevent this issue in production apps? -
how to request and post an object to a foreignkey field
When I do this exactly as provided below, a shipping address object is created without the customer assigned in the shipping address foreignkey field, I can add it from the admin panel manually but I'm not able to make it work through code, idk what I'm doing wrong, please help! **models.py** class Customer(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, blank=True, null=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=150) class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) address_one = models.CharField(max_length=200) address_two = models.CharField(max_length=200) ... **views.py** def checkout(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total': 0, 'get_cart_items': 0} if request.method == 'POST': form = ShippingForm(request.POST) if form.is_valid(): #how do I get the customer to get added in the foreignkey field for the shipping address model form.save() return redirect('store:checkout_shipping') else: form = ShippingForm() else: form = ShippingForm() context = {"items": items, "order": order, "form": form} return render(request, 'store/checkout.html', context) -
Error in Postgresql: connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "TheGecko"
Im trying to use PostgreSQL with django and I get that error when running python3 manage.py migrate: connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "TheGecko" I was following this guide:https://djangocentral.com/using-postgresql-with-django/ Here is my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'websitedb', 'USER':'TheGecko', 'PASSWORD':'xx', 'HOST':'localhost', 'PORT':5432, } } Also, even though I entered that line: GRANT ALL PRIVILEGES ON DATABASE websitedb TO TheGecko;, when I do \l, I get this output. Shouldn't the owner be TheGecko? I've looked over the web and nothing I could read worked for me. Please help. -
Python Django Rest framework
What are the contents of args and kwargs in this create method? def create(self, request, *args, **kwargs) -
Django's Image Field and Google app engine
I have a django app deployed on google cloud platform. I also have the same app deployed on heroku(It works fine). I have a model in my code that looks like this : class Notification(models.Model): ## other fields qrcode = models.ImageField(null=True, blank=True, default=None) When I pass this model to the serializer, I got a status code 500. I googled it and find some answers reffering to PIL library or some needed configuration in the Google Cloud App Engine in order to support ImageField. Does anyone know what to do in this case? Thnx in advance -
What other softares/libraries should I look to import to base Django if I'm looking to make a banking application?
I'm a relatively new full stack developer that recently picked up a project to create a banking application that handles users' banking information and allows them to purchase bonds. I'm familiar with Django, templating, and APIs, but I was wondering if someone could recommend some of the best software to combine with Django to make this app possible.