Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
perfoming right join with django queryset
I just need to apply right join with query set. vdata = (VisVisitData.objects. .select_related('vpvalue','vparameter') .filter(vpvalue__vparameter=9,) .values(name=F('vpvalue__parameter_value'), visit_day=F('visit__visit_day'), question=F('vparameter'), value_id=F('vpvalue')) .annotate(data=Count('vpvalue_id')) .order_by('visit__visit_day')) above code generate following join statement. FROM `vis_visit_data` INNER JOIN `vis_visit_parameter_values` ON (`vis_visit_data`.`vpvalue_id` = `vis_visit_parameter_values`.`vpvalue_id`) LEFT OUTER JOIN `vis_visits` ON (`vis_visit_data`.`visit_id` = `vis_visits`.`visit_id`) But I need to do right join instead of Inner Join with vis_visit_parameter_values and vis_visit_data table. below is the snapshot of sql in which I want to make changes. INNER JOIN vis_visit_parameter_values ON (vis_visit_data.vpvalue_id = vis_visit_parameter_values.vpvalue_id) -
Django Auto add id field in database i don't want it
Django auto add id field in database i don't want to add id field in my database please help fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), -
Django 2 filter by age range with filters.py
I am currently filtering users by exact age which is not ideal and need to filter instead by age range. Age is inputted by the user and is a field in the Profile model. Right now I'm using {{ filter.form }} to render out a filters.py form that has multiple filter options. filters.py class ProfileFilter(django_filters.FilterSet): class Meta: model = Profile fields = { 'age': ['exact'], 'gender': ['exact'], } Is there a simple way to do this in filters.py? Or should I make the Age field a select field where the user selects the range that best fits their age? Etc 20-30s and then exact filter that instead? -
Django - How to make an upvote button?
Currently logged in users can upvote x amount of times. The idea of fixing it is to create a new model called Vote. And it will have foreignkeys for user and product. When someone goes to upvote, you check and see: is there vote object with this user id and product id, and if there is, you don't allow him to upvote again; and if it is not, then you can go ahead and create that, and just increase total_votes on one. But actually, i ran into it and cant figure it out and solve. So, there is my models.py from django.db import models from django.contrib.auth.models import User class Product(models.Model): title = models.CharField(max_length=255) pub_date = models.DateTimeField() body = models.TextField() url = models.TextField() image = models.ImageField(upload_to='images/') icon = models.ImageField(upload_to='images/') votes_total = models.IntegerField(default=1) hunter = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def summary(self): return self.body[:100] def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') class Vote(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) voteproduct = models.ForeignKey(Product, on_delete=models.CASCADE) And my views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .models import Product, Vote from django.utils import timezone @login_required(login_url="/accounts/signup") def upvote(request, product_id): if request.method == 'POST': product = get_object_or_404(Product, pk=product_id) product.votes_total += 1 product.save() return redirect('/products/' + … -
how to query get posts filtered with same category in django functional based view
I am trying to list out all posts with same catgory on my home page in django. I want title to be category title and then below title it should render all the posts related to that catgory. I did this in class based view by finding help on stackoverflow but I want to know this in functional based view to understand this. models.py from tinymce import HTMLField from django.db import models from django.contrib.auth import get_user_model from slugger import AutoSlugField from django.urls import reverse # Create your models here. User = get_user_model() def upload_location(instance, filename): return "%s/%s" %(instance.slug, filename) class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username class Category(models.Model): title = models.CharField(max_length=20) slug = AutoSlugField(populate_from='title') def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length = 100) slug = AutoSlugField(populate_from='title') overview = models.CharField(max_length= 200) timestamp = models.DateTimeField(auto_now_add=True) content = HTMLField() comment_count = models.IntegerField(default=0) view_count = models.IntegerField(default=0) author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField( upload_to=upload_location, null=True, blank=True) category = models.ManyToManyField(Category) featured = models.BooleanField() previous_post = models.ForeignKey('self', related_name= 'previous', on_delete=models.SET_NULL, blank=True, null=True) next_post = models.ForeignKey('self', related_name= 'next', on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return self.title views.py I tried to do this but this gives me error something like this TypeError at / … -
Django - reverse not found for included URL pattern
I've got the following in an old Django 1.8 (sorry...) site: url(r"^racing/(?P<type>(dog|horse|pigeon))/", include("racing.urls")), which pulls in the racing URLs: urlpatterns = patterns("racing.views", url(r"^(?P<season>\d+)/$", "season_view", name="season_home"), } The view function defines a default for the type argument: def season_view(request, season, type="horse") Which, to my mind, means I should be able to (in a template) do: {% url "season_home" season=nav.season.year %} But it's throwing an error: Reverse for 'season_home' with arguments '()' and keyword arguments '{u'season': 2019L}' not found. 1 pattern(s) tried: [u'racing/(?P<type>[-\\w]+)/(?P<season>\\d+)/$'] What am I missing? -
Python is stop working when try to stop the django server
When i try to start the django server a pop up is appearing like this: After closing the pop-up mentioned above then only sever starting Then there is a message poping like this every time i stopped server. -
Issue with deplpying django and heroku-postgress using django-heroku
So I have this app I wish to deploy to Heroku. I use django-heroku so it can run my postgres-sql stuff automatically. I added release: python mannge.py migrate to my Procfile. After the build, I get a deployment failed error, saying Release command failed. On opening the log, I have this error: psycopg2.ProgrammingError: cannot cast type timestamp with time zone to integer LINE 1: ...LUMN "established" TYPE integer USING "established"::integer ^ My model with the established field is like this: from django.db import models # Create your models here. class FederalMinistry(models.Model): full_name = models.CharField(max_length=400) short_name = models.CharField(max_length=20) description = models.TextField() established = models.PositiveIntegerField() # logo = models.ImageField(upload_to='fed_min_logos', blank=True, null=True, default='N/A') current_minister = models.CharField(max_length=500) permanent_secretary = models.CharField(max_length=500, default='N\A') headquarters = models.CharField(max_length=100, default='Abuja') twitter = models.URLField(blank=True, null=True, default='N/A') website = models.URLField(blank=True, null=True, default='N/A') class Meta: verbose_name_plural = 'Federal Ministries' def __str__(self): return self.full_name Please why am I getting the error and his to fix it. I have no knowledge of postgres. -
How to make a gmail like application using django?
I want to make a e-mail service application using django. I am currently using django version of 2.0.6 and python version 3.6.7. I mean user can be able to send mail,reply and forward mails and also add attachments to a mail. Is there any specific way of doing it without using any third-party-application. Any suggestion anyone? Thank you -
Request.data or Request.query_params to access params in POST?
I'm building a simple API and I'm trying to test POST request. Post request should create a new record based on only one param: title. I'm using manage.py test for testing and I've set up the client: client = rest_framework.test.APIClient() Problem: it works fine when I'm giving the URL manually ("snatch" is a title of a movie). response = client.post('/movies/?title=snatch', format='json') In this case I can access the title in my view request.query_params.get('title') and request.data.get('title'). But when I'm trying to pass the title in data argument: response = client.post('/movies/', data={'title':'snatch'}, format='json') This should access '/movies/?title=snatch', but instead accesses only '/movies/'. I can access the title through request.data.get('title'), but not through request.query_params.get('title'). How should I access the params sent in POST request? Is accessing through request.data a correct way? Can someone give me a better explanation of the differences and use cases? -
I want to call validate_even method in during validation of username but it shows name 'validate_even' is not defined
I am stuck to create custom validation for username my forms.py from .models import User from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ValidationError from PIL import Image from django.utils.translation import ugettext_lazy as _ class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') phone = forms.CharField(max_length=30, help_text='Phone number', required=False) # vv = forms.CharField(max_length=100, help_text='custom', required=False) picture = forms.ImageField() username = forms.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='required.',validators=[validate_even], max_length=150), class Meta: model = get_user_model() fields =('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'phone','picture') my models.py is from django.db import models from django.contrib.auth.models import AbstractUser from PIL import Image from django.contrib.auth.validators import UnicodeUsernameValidator class User(AbstractUser): pp = models.CharField(max_length=100, blank=True, null=True) xx = models.CharField(max_length=100, blank=True, null=True) dd = models.CharField(max_length=100, blank=True, null=True) vv = models.CharField(max_length=100, blank=True, null=True) picture = models.ImageField(upload_to = 'uploads/', default = 'var/www/html/typo3/uploads/no-img.jpg') username = models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='baal required.',validators=[validate_even], max_length=150), my validators.py is import re from django.core import validators from django.utils.deconstruct import deconstructible from django.utils.translation import gettext_lazy as _ from django.core.exceptions import ValidationError def validate_even(value): if value % 2 != 0: raise ValidationError( _('%(value)s is not … -
POST requests in axios for creating object in django restframework api
I am new to working with APIs and currently have created a restframework API for creating and views posts that belong to a user. A post has a text field and a favorite-tags field. My posts view is a class based view defined as 'class PostList(generics.ListCreateAPIView):' I am using vue.js for the frontend and I am able to make a successful get request from the frontend as follows: this.$http.get('posts/',{headers: {Authorization: 'Token ' + this.$store.getters.getToken }}) However, I am not sure how to send the data of the post to the backend in this call for the restframework api. How can I send a text field from the frontend. Currently when I try something like this : this.$http.post('posts/',{headers: {Authorization: 'Token ' + this.$store.getters.getToken }, data: {'text': 'asdasd' }}) I get a 401 status code error -
Django Rest Framework - ListCreateAPIView Prints Nothing
I have create a API for list and create using django rest framework. But it is not printing anything in Web browsable api. I don't what is the problem. When i am printing queryset and serializer variable it is giving proper output as QuerySet. Views.py from rest_framework.response import Response from rest_framework import generics from .serializers import MovieSerializer from movie.models import Movie from rest_framework.permissions import IsAuthenticated class MovieList(generics.ListCreateAPIView): queryset = Movie.objects.all()[:10] serializer_class = MovieSerializer permission_classes = (IsAuthenticated,) def list(self, request): # Note the use of `get_queryset()` instead of `self.queryset` queryset = self.get_queryset() # print(queryset) serializer = MovieSerializer(queryset, many=True) # print(serializer.data) return Response(serializer.data) Serializers.py from rest_framework import serializers from movie.models import Movie class MovieSerializer(serializers.Serializer): class Meta: model = Movie fields = [ 'popularity', 'director', 'genre', 'imdb_score', 'name', ] See the image for reference. -
django select option in table
: - ) I'd like to use select option in table with django. but it doesn't work. enter image description here myview.py def Data_Handling(request) : if request.method == 'POST' : form = getValue(request.POST) else : form = getValue() global excel_data_name agrs = {"excel_data_name" : excel_data_name, "form" : form } return render(request, 'ex01/data_handling.html', agrs ) myforms.py class getValue(forms.Form) : value = forms.ChoiceField(widget=forms.Select(choices=("A", "B", "C"))) myhtml <td> <form method = "post" action = ""> {% csrf_token %} {{ form.as_p }} </form></td> And, how can i get a selected value in each row? -
Conditional template tags in email template
I'm getting some strange results in the email that results from my email template when I include conditional template tags. Does using conditional template tags in an email template cause problems? eg. email_template.html {% if userisactive == True %} You are active! <br><br> {% endif %} Thanks so much! -
How to use Django with angular material?
I want to know how can use Django with angular material. Is there any suggestions? -
get_%field%_display without instance
I have a model like this class Item(models.Model): STATUS_VALID = 1 STATUS_INVALID = 2 STATUS_UNKNOWN = 3 STATUS_CHOICES = ( (STATUS_VALID, _("Valid")), (STATUS_INVALID, _("Invalid")), (STATUS_UNKNOWN, _("Unknown")), ) status = models.PositiveSmallIntegerField(choices=STATUS_CHOICES, default=STATUS_UNKNOWN) I already know that I can use instance.get_status_display() to get string value for an instance, but how can get this value without an instance, I mean something like this Item.get_status_display(Item.STATUS_VALID) -
Django Aggregation Count
I'm trying to filter my model with an aggregate function. I have a Model A and a Model B with a foreign key on the model A. annotate_pool = queryset.annotate(nb_bets=Count('bets')).all() for obj in annotate_pool: bets_obj = obj.bets.all() bets_length = len(bets_obj) print(obj.nb_bets, bets_length) And the annotation doesn't give me the same result as the function length. 1 1 1 2 1 2 1 2 1 2 1 1 1 1 2 2 What is going on? Why Count doesn't give me a wrong result. Thank you in advance. -
Django Postgres not reading DB password from environment variable
I have set the environment variable for DB password in the .bash_profile file but the same is not being read by the PASSWORD field of PostgreSQL. Also, I can print the password in production.py file successfully but the same won't be used by PostgreSQL. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '********_db', 'USER': '*****_name', 'PASSWORD':os.environ.get("RS_DB_PWD"), } #The below will show the password correctly. print(os.environ.get("RS_DB_PWD")) -
When overriding "perform_destroy" getting {"detail":"Method \"POST\" not allowed."}
New to Django and trying to implement a REST api. Here is the code: from views.py class reg_event(generics.CreateAPIView): queryset = event_registration_stub.objects.all() serializer_class = serializers.EventRegistrationStubSerializer def perform_create(self, serializer): serializer.save(parent_volunteer=self.request.user) class reg_event_delete(generics.DestroyAPIView): queryset = event_registration_stub.objects.all() serializer_class = serializers.EventRegistrationStubSerializer def perform_destroy(self, serializer): instance.delete(parent_volunteer=self.request.user, parent_event=self.kwargs["parent_event"]) Here is the serializer: class EventRegistrationStubSerializer(serializers.ModelSerializer): parent_volunteer = serializers.ReadOnlyField(source='parent_volunteer.id') class Meta: model = event_registration_stub fields = ('id', 'parent_event', 'parent_volunteer') And from urls.py url(r'^register_user_for_event/$', views.reg_event.as_view(), name='register_user_for_event'), url(r'^delete_user_for_event/$', views.reg_event_delete.as_view(), name='delete_user_for_event'), register user for event works. However the following: curl -X POST -d "parent_event=1" -H 'Authorization: Token 21cc749c43bf80f27598987cd5a9926d988ba64c' http://127.0.0.1:8000/api/delete_user_for_event/ returns "POST /api/delete_user_for_event/ HTTP/1.1" 405 41 I tried looking at 405 POST method not allowed But I'm not sure what is wrong with my urls. Is my perform destroy incorrect? Any help would be appreciated. -
Updating application Django
I have an app (Digital Ocean) and it doesn't update. I have checked on terminal the file (urls.py) and it's like this urlpatterns = [ # path( # 'ctrl_diario/', # DiarioListView.as_view(), # name='hoje', # ), path( 'hoje/', consulta_hoje, name='hoje' ), ] The old version is comment out but it keeps showing instead of new version I am using github and everything is working fine but my site does not update. -
how to reply email from django default admin to the contact?
This code saves the contact information in the admin panel.Now i want reply to these contacts. How can admin replies to these email came from contact form from default django admin .Is it possible to send email from default django admin models.py class Contact(models.Model): name = models.CharField(max_length=250) email = models.EmailField() subject = models.CharField(max_length=250, blank=True) message = models.TextField() def __str__(self): return self.name urls.py path('contact/', views.contact, name="contact"), admins.py admin.site.register(Contact) views.py def contact(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): contact = form.save(commit=False) contact.save() messages.success(request,'Your message has been sent.') return redirect('colleges:contact') else: messages.error(request,'Error in form.Try Again') return redirect('colleges:contact') else: form = ContactForm() return render(request, "colleges/contact.html",{'form':form}) forms.py class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ['name','email','subject','message'] contact.html {% extends "colleges/base.html" %} {% load bootstrap4 %} <title>{% block title %}Contact{% endblock %}</title> {% block content %} <br><br><br> <div class="container"> <div class="row"> <div class="col-lg-6 offset-lg-3 col-sm-10 offset-sm-1"> <div class="card my-5"> <center>{% bootstrap_messages %}</center> <div class="card-header text-center"> Contact </div> <div class="card-body"> <form action="" method="post"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" class="btn btn-success text-center w-100 mb-3" value="Contact"> </form> </div> </div> </div> </div> </div> {% endblock %} settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER ='my_email' EMAIL_HOST_PASSWORD = 'my_pass' EMAIL_POST … -
How to pass obfuscated IDs in admin URLs?
I have started learning Django and I got a project requirement to obfuscate the IDs in URL. After researching, I found opaque-id meets my requirement. I was able to use that library to obfuscate my IDs in my URLs. Now I have to obfuscate the IDs that are part of admin interface using this library function. Since admin interface is part of django core, any help/advise as to where to customize the admin URLs, especially in the CRUD operations of every model. I have the function ready to obfuscate that will take ID as input and give me encoded output. Now I was this encoded ID to be displayed in admin URLs. Say, I have an app named book_store with a model named book. The admin URL to edit a book record with ID 3 looks like "http://localhost:8000/admin/book_store/book/3/change/". I don't want to show ID 3, instead it should have the encoded output as 'FB3457' "http://localhost:8000/admin/book_store/book/FB3457/change/". I'm looking for a generalized solution that will be applicable for all models that are part of my django project/app. Thanks in advance! -
PUT/PATCH failed to update because of unique constraint field in model and on_delete=CASCADE is not setting in the models
My model: class news_ids(models.Model): status = StatusField() class news_headlines(models.Model): newsId = models.ForeignKey(news_ids, related_name = 'news', on_delete=models.CASCADE) lang_code=LanguageField() headline=models.CharField(max_length=100,unique=True) My serializer: class NewsSerializer(QueryFieldsMixin,serializers.ModelSerializer): class Meta: model=news_headlines fields=('lang_code','headline') class NewsIDSerializer(QueryFieldsMixin,serializers.ModelSerializer): news = NewsSerializer(many=True) class Meta: model = news_ids fields = ('id','news','status','default_language') def create(self, validated_data): """Create function to post the data""" def update(self, instance, validated_data): """ Update function to put/patch the data""" When I try to edit the lang_code using put/patch I am getting an error that headline field is already existing. Even after specifying on_delete=CASCADE in the model It is not effecting in my migrations and tables in the database How to achieve this in Django? -
Optional Field on base class but mandatory on child class in DJango
i would like to know if its possible to have 2 classes (base=person and a child=user) where i have a property (email) nullable on base but it must be set for child class class Person(models.Model): name = models.CharField(max_length=60, ) identification = models.CharField(max_length=20, unique=True) email = models.CharField(max_length=60, null=True) #<~~~~ Email can be null def __str__(): return self.name class User(Person): email = models.CharField(max_length=60, ) #<~~~~ Email CAN'T be null If i leave it like this i get this error: django.core.exceptions.FieldError: Local field 'email' in class 'User' clashes with field of the same name from base class 'Person'. Thanks.