Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I return an array of objects instead of an array of arrays in Django Rest Framework?
I am trying to display all doctors that work at a certain clinic as an array of objects instead of an array of arrays. http://localhost:8000/api/clinic/ results [ { "id": 1, "doctors": [["Henry", "Ford", 20], ["Elon", "Musk", 30]] // get array of objects instead "name": "Clinic number 1", }, ... ] This how I implemented my models, serializers and viewsets: class Clinic(models.Model): name = models.CharField(max_length=200) class Doctor(models.Model): clinic = models.ManyToManyField(Clinic, related_name="doctors") class ClinicSerializer(serializers.ModelSerializer): doctors = serializers.SerializerMethodField() class Meta: model = Clinic fields = '__all__' class DoctorSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = '__all__' class ClinicViewset(viewsets.ModelViewSet): queryset = Clinic.objects.all() serializer_class = ClinicSerializer class DoctorViewset(viewsets.ModelViewSet): queryset = Doctor.objects.all() serializer_class = DoctorSerializer -
Django authetication problem, wrong error message
My sign up form works fine but when I type the Your username and password didn't match. Please try again. I want it to say something like 'try a stronger password' my sign up view def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() email = form.cleaned_data.get('email') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(email=email, password=raw_password) login(request, user) return redirect('/') else: form = SignUpForm() return render(request, 'registration/signup.html', { 'form': form }) -
ERR_HTTP2_PROTOCOL_ERROR loading admin pages in Django
I've started to get errors loading some pages in Django admin (with Grappelli): net::ERR_HTTP2_PROTOCOL_ERROR 200 It appears in chromium browsers console. These pages never load. For some time firefox has served this pages well, but today I've got the admin page which has been loaded partially, disrupted in the middle of inline forms, with this in the console: Layout was forced before the page was fully loaded. If stylesheets are not yet loaded this may cause a flash of unstyled content. I'm not even sure if the problem is with Django, because everything is ok on the dev server and the problem occurs with the production server (Nginx). I've already tried solutions from here with no result. But since the problem somehow connected with Django admin pages, how can I investigate it? -
format django current time and 7 days back time
Here i have piece of django python code. I am trying to get current time 7 days back time. But unfortunately both time formats are not matching so the api is not accepting seven_days_back_date date. I don't wants to replace anything looking for some efficient way. from datetime import datetime from django.utils import timezone now = f"{datetime.utcnow().isoformat()}Z" profile = Profile.objects.get(id=profile_id) last_updated_date = profile.data_last_updated seven_days_back_date = last_updated_date - timezone.timedelta(days=7) seven_days_back_date = f"{seven_days_back_date.isoformat()}Z" print(now) print(seven_days_back_date) Result i am getting: 2020-09-21T16:16:30.753375Z 2020-09-14T16:16:04.042587+00:00Z expecting: 2020-09-21T16:16:30.753375Z 2020-09-14T16:16:04.042587Z Please have a look -
Custom systemd service to run Gunicorn not working
I am trying to deploy my Django website to a Ubuntu server. I am following this tutorial: linuxhint.com/create_django_app_ubuntu/. However, the Gunicorn service doesn't work. I have my site at /home/django/blog. My Python 3.6 virtualenv is activated at /home/django/.venv/bin/activate (-rwxr-xr-x 1 django root 2207 Sep 21 14:07 activate). The script for starting the server is at /home/django/bin/start-server.sh (-rwxr-xr-x 1 django root 69 Sep 21 15:50 start-server.sh), with the following content: cd /home/django source .venv/bin/activate cd blog gunicorn blog.wsgi Running this script manually works just fine. The Gunicorn service is at /etc/systemd/system/gunicorn.service, with this content: [Unit] Description=Gunicorn After=network.target [Service] Type=simple User=django ExecStart=/home/django/bin/start-server.sh Restart=on-failure [Install] WantedBy=multi-user.target Running 'systemctl status gunicorn.service' gives this: ● gunicorn.service - Gunicorn Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2020-09-21 16:15:17 UTC; 6s ago Process: 1114 ExecStart=/home/django/bin/start-server.sh (code=exited, status=203/EXEC) Main PID: 1114 (code=exited, status=203/EXEC) Sep 21 16:15:17 example.com systemd[1]: gunicorn.service: Failed with result 'exit-code'. Sep 21 16:15:17 example.com systemd[1]: gunicorn.service: Service hold-off time over, scheduling restart. Sep 21 16:15:17 example.com systemd[1]: gunicorn.service: Scheduled restart job, restart counter is at 5. Sep 21 16:15:17 example.com systemd[1]: Stopped Gunicorn. Sep 21 16:15:17 example.com systemd[1]: gunicorn.service: Start request repeated too quickly. Sep 21 16:15:17 example.com systemd[1]: … -
Django rest returning 'token not valid' when using token generated from google and fb api
Calling Facebook endpoint send me this: { "token": "token", "email": "", "username": "" } But whenever I try to use the token to access a view it throws: The error is same when using google api too. { "code": "token_not_valid", "detail": "Given token not valid for any token type", "messages": [ { "message": "Token has no id", "token_type": "access", "token_class": "AccessToken" } ] Am i missing something? -
In DRF how can one properly display the related name field from one model inside another?
I am trying to display all doctors that work at a certain clinic but keep getting clinic.Doctor.None. I'm trying to get a list of the doctors ids or names in there http://localhost:8000/api/clinic/ results [ { "id": 1, "doctors": "clinic.Doctor.None", //how to show list of ids or names here? "name": "Clinic number 1", }, ... ] This how I implemented my models, serializers and viewsets: class Clinic(models.Model): name = models.CharField(max_length=200) class Doctor(models.Model): clinic = models.ManyToManyField(Clinic, related_name="doctors") class ClinicSerializer(serializers.ModelSerializer): doctors = serializers.CharField(read_only=True) class Meta: model = Clinic fields = '__all__' class DoctorSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = '__all__' class ClinicViewset(viewsets.ModelViewSet): queryset = Clinic.objects.all() serializer_class = ClinicSerializer class DoctorViewset(viewsets.ModelViewSet): queryset = Doctor.objects.all() serializer_class = DoctorSerializer -
How do i compute every Item unitprice multipy by its quantity
I know how to use aggregate and annonate, (a little bit), but what i want is to compute every item product not the total average, how do i compute every product unitprice multipy by its quantity? I just want to get the total amount of every item, but how do i do that? what should I use? aggregate or annotate? I use aggregate for getting the total amount of all product total = CustomerPurchaseOrderDetail.objects.filter( id__in=cart.values_list('id') ).aggregate( total=Sum( F('unitprice') * F('quantity'), output_field=FloatField(), ) )['total'] print('aggregate', total) and this is my logic on how to get the the total amount of per product total_amount_of_product = CustomerPurchaseOrderDetail.objects.filter( id__in=cart.values_list('id')).annotate(total_per_item=Sum(F('unitprice') * F('quantity'), output_field=FloatField(),)) item_totals = [item.total_per_item for item in total_amount_of_product] this is the result in my html this is how i print to the html <td class="cart__cell--total"><span class="cart__item-total">₱ {{item_totals}}</span></td> -
UserInfo matching query does not exist.?
I create a django web app. It's a crud project. When i want to login as a admin it show me this message but it's work well when i login as a user. can not figure out where is the problem. Help me to solve this. -
How to clear cache data without delete my session data in Django 2.2.2
I am trying to delete the cache from django in browser without delete the session data of my website. -
Django + React: React "frontend" Django app vs. React scripts embedded in Django templates?
I am trying to understand how to best structure my Django-React project to increase readability and maintainability for the future. As far as I understand there are multiple ways to integrate Django and React. The two options I am considering for my project are: Creating a big "frontend" Django app where all the HTML will be managed through a React app. Embedding smaller React scripts in Django templates and use Django as the main vehicle to manage HTML. Which alternative would be better for what particular context and why? -
How to change the browse file address or location of Froala editor in Python Django?
I am using Froala Rich Text Editior in Python Django. I want to upload images from already uploaded images and there is an option known as browse image but this browse image showing default images not my uploaded or existing images. Please.enter image description here -
how to add comments to an article in django(Python)?
I'm new to Django, I repeat after the tutorial, but I just can not display comments even from the database in html. urls.py static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') models.py from django.db import models class Post(models.Model): photo = models.ImageField(upload_to='media/photos/',null=True, blank=True) name_barber = models.CharField(max_length=30) description = models.TextField(blank=True, null=True) def __str__(self): return self.description[:10] class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField() date_add = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post, self.name) html file } </style> {% for post in posts %} <img src="{{MEDIA_URL}}{{post.photo.url}}" width="800" /> <h3>{{ post.name_barber}}</h3> <p>{{ post.description}}</p> {% endfor %} <h3> Comments.. </h3> {% if not post.comments.all %} no comments yet...<a href = "#">Add one</a> {% else %} {% for comment in post.comments.all %} <strong> {{ comment.name }} {{ comment.date_add }} </strong> {{comment.body }} {% endfor %} {% endif %} after adding a comment through the admin panel, the page displays: no comments yet.. What is the problem please tell me?? -
Django GEOSException at /
Recently when I tried to create a Polygon instance in Django (version 3.1) I got this error: GEOSException at / Error encountered checking Geometry returned from GEOS C function "GEOSGeom_createLinearRing_r". Here's my coordinates that I'm using: Polygon((51.558994, -0.16349), (51.552505, -0.121468), (51.527564, -0.179695), (51.527564, -0.179695)) These coordinates are just a sample. I'm using Polygon coordinates from the leaflet, but when I try to create django.contrib.gis.geos.polygon.Polygon Instance, I get that error. Do have any idea or approach to store received coordinate from leaflet to polygon in Django? -
Images I upload on the admin console are not served
This is being a bit confusing for me. If I set DEBUG=True run python manage.py runserver on VSC, I can access http://127.0.0.1:8000/admin, log in and upload a new photo that will be displayed when I access portifolio.html among the other photos that were previously updated. These photos are saved on BASE_DIR/media/images. However, when DEBUG=False, the previously shown images are not found anymore (404 error on console). I read online that I should use Whitenoise when serving static files on Django while on production and installed it. Still, I get the same behavior. When I run python manage.py collecstatic, the files located on BASE_DIR/django_app/static are copied to BASE_DIR/static and the media folder remains unchanged. settings.py DEBUG = False INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'users.apps.UsersConfig', ... ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(SITE_ROOT,'static/'), ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') models.py class ImageModel(models.Model): image = models.ImageField(upload_to='images/') url = models.CharField(max_length=100,default='abcdefg') def get_url(self): return self.url def __str__(self): return self.url views.py def index(request): context = { "images": ImageModel.objects.all() } return render(request,'blog/index.html',context) url.py urlpatterns = [ path('admin/', admin.site.urls), ... ] urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_URL) urlpatterns += static(settings.MEDIA_URL, … -
Django How to get user email in model form
So i have profile update form in django and using form.modelform but unable to get user email by self.request.user.email class UserUpdateForm(forms.ModelForm): #Profile email email=forms.EmailField() username=forms.CharField(required=True,validators=[username_check,]) class Meta: model =User fields =['username','email'] def clean_email(self): form_useremail=self.cleaned_data.get("email").lower() if form_useremail!=self.user.email and User.objects.filter(username=form_username).exists(): raise forms.ValidationError("Email already in use") else: return form_useremail Error 'UserUpdateForm' object has no attribute 'user' appears -
django admin inline fields options filtered based on main form field value
I have the following Models: class Organizations(models.Model): name = models.CharField(max_length=30,unique=True) class Postcodes(models.Model): organization = models.ForeignKey(Organizations,on_delete=models.PROTECT) postcode = models.PositiveBigIntegerField() class Agent(models.Model): organization = models.ForeignKey(Organizations,on_delete=models.PROTECT) name = models.CharField(max_length=50) class AgentPostcodes(models.Model): agent= models.ForeignKey(Agent,on_delete=models.PROTECT) postcode = models.ForeignKey(Postcodes,on_delete=models.PROTECT) and admin.py is class AgentPostcodesInline(admin.TabularInline): model = AgentPostcodes class AgentAdmin(admin.ModelAdmin): list_display = ['organization','name'] inlines = [AgentPostcodesInline] How can I have the inline form fields filtered based on organization for postcodes related to that organization only. Currently it shows postcodes for all organizations even not related to the agent. -
object created in Django forms not created in admin but saved DB
I am using UserCreationForm for the registration of new users, while new users are created using forms at the front end , it saved in database . However, I do not see any updates in the Django admin. I am not sure what is happening here. If someone could help with this issue. views.py from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm def register(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form= UserCreationForm() return render(request,'users/register.html',{'form':form}) ---------------------------------------------------------------------------------------------- Project/urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static from users import views as user_views from django.contrib.auth import views as auth_views urlpatterns = [ path('admin/', admin.site.urls), path('register/',user_views.register,name ='register'), path('', include('blogs.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) --------------------------------------------------------------------------------------------------- register.html {% extends 'blogs/base.html' %} {% load crispy_forms_tags %} {% load static %} {% block content %} <h2> Register </h2> <form class =site-form" action ="{% url 'register' %}" method="post"> {% csrf_token %} {{ form|crispy }} <input type ='submit' name="submit" value="Register"> </form> {% endblock %} ------------------------------------------------- Thank you in advance. -
Django multiple forms as popups and AJAX?
In my project I have a page where all the multiple user types are listed as cards and I was trying to add a detail view to each card with update and delete options within the card detail display. So this basically calls for AJAX calls. But I can't seem to figure out how to nest views within templates and style each forms according to my needs. Any advice? -
Form not rendering in template
form not rendering in template please sort out this problem my form forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField(required=True) email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea) my view views.py def contactform(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') else: form = ContactForm() return render(request, 'portfolio/contact.html', {'form': form}) my templtae contact.html <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="send"> </form> -
TypeError create_superuser() got an unexpected keyword argument
I am in the progress of learning django, so kindly consider me as a newbie. I was able to use default user model in django, but while trying custom user model , i am facing issues in creating super user. I would like to have Email as username and have few additional fields like mobile number in my custom user table. Below is my models.py Model.py from django.db import models #from django.contrib.auth.models import User from django.contrib.auth.models import AbstractBaseUser , BaseUserManager # Create your models here. class AccountManager(BaseUserManager): def create_user(self, email,firstName,lastName,m_phone,password=None,**kwargs): if not email: raise ValueError('Email Id is a required Field') if not firstName: raise ValueError('First name is a required Field') if not lastName: raise ValueError('Last name is a required Field') if not m_phone: raise ValueError('Mobile Ph. no is a required Field') user = self.model(email=self.normalize_email(email), firstName=firstName, lastName = lastName, m_phone = m_phone, **kwargs) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email,firstName,lastName,m_phone,password): user = self.create_user(email=self.normalize_email(email), firstName=firstName, lastName = lastName, m_phone = m_phone, password = password) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(unique=True) firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) m_phone = models.CharField(verbose_name='Mobile Number' , max_length=50) l_phone = models.CharField(max_length=50) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) … -
Django translation not working on base html file?
I don't know what I am missing. I am working with django translation. The traslation works perfectly all apps other than the package folder, i.e app that contains settings.py. My file structure is like this: my-project/ manage.py locale/ mysite/ __init__.py settings.py lacale/ templates/ base.html urls.py profile/ __init__.py locale/ templates/ profile/ profile.html views.py urls.py Here are the settings file: MIDDLEWARE = [ .... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', .... ] LANGUAGE_CODE = 'es' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = ( ('en-us', _('English')), ('es', _('Spanish')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) My base.html looks likem This translation does not work: {% load static %} {% load i18n %} <!DOCTYPE html> <html lang="en"> <head> {% load i18n %} <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="author" content="Biplove Lamichhane"> <title>{% block title %}{% endblock title %}</title> </head> <body> <h1>{% trans "Base" %}</h1> {% block content %} {% endblock %} </body> My profile.html goes like this, This translation does work: {% extends 'base.html' %} {% load static %} {% load i18n %} {% block title %}Title{% endblock title %} {% block content %} <h2>{% trans "Check" %}</h2> {% endblock %} Also, I have correctly created django.po file and … -
How do i compute every product unitprice multipy by its quantity
I know how to use aggregate and annonate, (a little bit), but what i want is to compute every item product not the total average, how do i compute every product unitprice multipy by its quantity? this is my views.py This is the annotate total_amount_perproduct = CustomerPurchaseOrderDetail.objects.filter( id__in=cart.values_list('id') ).annotate( total_per_item=Count(F('unitprice') * F('quantity'), output_field=FloatField()) ) print('annotate', total_amount_perproduct) this is the result of annotate. annonate: <QuerySet [<CustomerPurchaseOrderDetail: 265>, <CustomerPurchaseOrderDetail: 266>]> this is the aggregate total = CustomerPurchaseOrderDetail.objects.filter(Status ='Active' ).filter( id__in=cart.values_list('id') ).aggregate( total=Sum( F('unitprice') * F('quantity'), output_field=FloatField(), ) )['total'] print('aggregate', total) This is the result: aggregate 198.0 -
How to connect two Django models?
New to Django and relational DBs. I'm building the classic Doctor appointment booking app and have come to a point where I don't know what to do. I watched online classes that mentioned no two models should not have ManyToMany relationships coming from both sides. So how can I circumvent the below? class Clinic(models.Model): doctors = # how to get list of all doctors in this clinic automatically from Doctor model class Doctor(models.Model): clinic = models.ManyToManyField(Clinic, related_name="doctor") -
Trying to insert date time value into django model but getting invalid format error
I am trying to save my date time values from the datetimepicker into the Django model. I am getting a time format error. This is the error : time data '2020-09-17T10:05' does not match format "yyyy-mm-dd'T'HH:MM" My code: name = request.POST["name"] date1 = request.POST["start"] startdate = datetime.strptime(date1, "yyyy-mm-dd'T'HH:MM") start = startdate.isoformat() date2 = request.POST["end"] enddate = datetime.strptime(date2, "yyyy-mm-dd'T'HH:MM") end = enddate.isoformat() e = Events(name=name, start=start, end=end) e.save();