Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I upload images on django?
I have been trying to upload an image in Django using a custom view and I'm failing. The admin panel is letting me upload though, what could be the problem? I have installed Pillow and made sure that the form has the multipart/form-data property. Am I supposed to make a separate model for images? models.py class Profile(models.Model): username = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.TextField(max_length=10) dob = models.DateField(null=True, blank=True) phone_no = models.CharField(unique=True, max_length=9) address = models.CharField(max_length=50) profile_pic = models.ImageField(null=True, blank=True, upload_to="profile_pic/") nrc_front = models.ImageField(null=True, blank=True, upload_to="nrc_front/") nrc_back = models.ImageField(null=True, blank=True, upload_to="nrc_back/") is_verified = models.BooleanField(default=False) is_group_admin = models.BooleanField(default=False) is_group_member = models.BooleanField(default=False) temp_code = models.CharField(max_length=6, null=True, blank=True) def __str__(self): return str(self.username) settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join( BASE_DIR / 'media' ) view.py def updateProfilePic(request): profiledata = get_profile_data(request) form = UpdateProfilePicForm() if request.method == "POST": form = UpdateProfilePicForm(request.POST, request.FILES) if form.is_valid(): profile_pic = form.cleaned_data.get("profile_pic") Profile.objects.filter(username=request.user).update(profile_pic=profile_pic) return redirect('profile') else: form = UpdateProfilePicForm() context = { "profiledata":profiledata, "form":form } return render(request, 'base/profile-update-picture.html', context) template {% extends 'base/base.html' %} {% block title %}Update Picture{% endblock %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <div class="form-container shadow p-3 mb-5 bg-white rounded mx-auto"> {% crispy form %} </div> </div> {% endblock %} browser rendering <form … -
How to convert Date().toLocaleString() to YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]
I am trying to make an axios post request to django datetimefield, it requires the datetime format of YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]. I am currently getting the format Sun May 29 2022 02:42:00 GMT+0800 (香港標準時間) from Date().toLocaleString() in reactjs. The (香港標準時間) means Hong Kong Time. Anybody has an idea on converting the date format in Reactjs? Much thanks. -
Cannot assign "'user_name'": "Class.user" must be a "Account_class" instance
enter image descripI am getting this error when I try to make a post requesttion here How to can I solve this problem? Here is my model: class Coffee(models.Model): name = models.CharField(max_length=60) ratings = models.CharField(max_length=5) taste = models.TextField() coffeeType = models.CharField(max_length=60) price = models.CharField(max_length=60) img = models.CharField(max_length=200) updated_at = models.DateTimeField(auto_now_add=True) shopName = models.CharField(max_length=60) coffeeShopID = models.CharField(max_length=200) location = models.CharField(max_length=200) user = models.ForeignKey(Account, on_delete=models.CASCADE, null=False, blank=False, related_name='user') def __str__(self): return self.name[0:50] class Meta: ordering = ['-updated_at'] Here is the serializer of that model: class CoffeeSerializers(serializers.ModelSerializer): class Meta: model = Coffee fields = '__all__' Here is views for post request: def addCoffee(request): data = request.data coffee = Coffee.objects.create( name=data['name'], ratings=data['ratings'], taste=data['taste'], coffeeType=data['coffeeType'], price=data['price'], img=data['img'], shopName=data['shopName'], coffeeShopID=data['coffeeShopID'], location=data['location'], user=data['user'] ) coffee.save() serializer = CoffeeSerializers(coffee) return Response(serializer.data) -
Email Verification on Django withou API
I'm trying to implement email verification using Django without an API. I included the following items in my settings.py file: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'stmp@gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'my_email@gmail.com' EMAIL_HOST_PASSWORD = 'my_password' DEFAULT_FROM_EMAIL = 'default from password' Below is my views.py file. I'm sending an email to the user who's registering here. from rest_framework.views import APIView from rest_framework.response import Response from .serializers import UserSerializer from django.contrib.auth.models import User from django.contrib.auth import authenticate from rest_framework.permissions import AllowAny from django.core.mail import send_mail class TestView(APIView): def get(self, request, format=None): print("API called") return Response("You did it!", status=200) class RegisterView(APIView): permission_classes = [AllowAny] def post(self, request, format=None): print("Registering User") user_data = request.data print(request.data) user_serializer = UserSerializer(data=user_data) if user_serializer.is_valid(raise_exception=False): user_serializer.save() send_mail( 'Verify Your All-in-one Account', 'Hi!', 'allinonehealthapp22@gmail.com', user_data['email'], fail_silently=False, ) return Response({'User': user_serializer.data}, status=200) return Response({'msg': "error: User not registered"}, status=400) class UserLoginView(APIView): permission_classes = [AllowAny] # convert user token to user data def get(self, request, format=None): if request.user.is_authenticated == False or request.user.is_active == False: return Response('Invalid credentials', status=403) user = UserSerializer(request.user) print(user.data) return Response("Testing", status=200) def post(self, request, format=None): print("Login class") # Looking for user's email or username user_obj = User.objects.filter(email=request.data['username']).first( ) or User.objects.filter(username=request.data['username']).first() # if user is valid, … -
Django ratelimit custom functions
How can I put a custom function for the method in django-ratelimit? I want it to be like this: I filled out a form. Then check if the length of the name is less than 5. If the length of the name is less than 5 then as many times as we fill the form it will never block the user. But if the length is bigger every time and he fills the form 5 times then the limiter will block the user from accessing the page. Something like flask-limiter cost function. Thanks. -
cannot underustand django custom authenticaton backend
I am trying to learn from book django 3 by example but i cannot understand few points in django custom authentication like why username and password is passed None and email=username and why we are using get_user Here is the code from django.contrib.auth.models import User class EmailAuthBackend(object): #Authenticate using an e-mail address def authenticate(self,request,username=None,password=None): try: user=User.objects.get(email=username) if user.check_password(password): return user return None except User.DoesNotExit: return None def get_user(self,user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExit: return None -
Django DetailView get one record from QuerySet
Please help me get one record from QuerySet object. views.py: from django.contrib.postgres.aggregates import ArrayAgg from django.http import JsonResponse, from django.views.generic.list import ListView from django.views.generic.detail import DetailView from movies.models import Book class BooksMixin(ListView): model = Book http_method_names = ['get'] def get_queryset(self): books = Book.objects.values().annotate(authors=ArrayAgg('authors__name',distinct=True) return books def render_to_response(self, context, **response_kwargs): return JsonResponse(context) class BooksDetail(BooksMixin, DetailView): def get_context_data(self, *, object_list=None, **kwargs): queryset = self.get_queryset() context = queryset.get(id=self.kwargs['pk']) return context urls.py: from django.urls import path from books import views urlpatterns = [ path('books/<uuid:pk>/', views.BooksDetail.as_view()), ] This works, but I want to get one record from the queryset inside the BooksDetail class more elegantly, without using the kwargs['pk'] filter. I tried to use construct like class BooksDetail(BooksMixin, DetailView): def get_context_data(self, *, object_list=None, **kwargs): queryset = self.get_queryset() context = super(BooksDetail, self).get_context_data(**kwargs) context['bla'] = queryset return context but got the error: 'BooksDetail' object has no attribute 'object' -
Access "upload_to" of a Model's FileFIeld in Django?
I have a Model with a FileField like that: class Video(MediaFile): """ Model to store Videos """ file = FileField(upload_to="videos/") [...] I'm populating the DB using a cron script. Is it possible to somehow access the "upload_to" value of the model? I could use a constant, but that seems messy. Is there any way to access it directly? -
Reduce database queries while render inclusion tag
I have model which represent tweets in my app and view which returns queryset with them. class Tweet(MPTTModel): text = models.CharField(max_length=140, db_index=True) pub_date = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, blank=True, related_name='liked_tweets', through='TweetLike') retweets = models.ManyToManyField(User, blank=True, related_name='retweeted_tweets', through='TweetRetweet') bookmarks = models.ManyToManyField(User, blank=True, related_name='bookmarked_tweets', through='TweetBookmark') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='tweets') parent = TreeForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='children') Each tweet renders with inclusion tag which includes another inclusion tag. This tag displays participants in the correspondence above the tweet text like in original twitter. @register.inclusion_tag('tweets/_reply_to_snippet.html') def reply_to(tweet, current_user): # Finds all ancestors for each tweet in queryset and then tweet owners. tweets_ancestors = tweet.get_ancestors().exclude(user=tweet.user) users_ancestors = CustomUser.objects.filter(tweets__in=tweets_ancestors). \ distinct() return { 'current_user': current_user, 'tweet_id': str(tweet.id), 'users': users_ancestors } And this tag hits database with new query for every tweet. I tried to play with prefetch_related in view, but seems it won't solve my problem. Now i have idea to add one more attr to view qs with users_ancestors or their ids, but didn't find right way to resolve this. -
Serializer data's "id" field returns null DRF
I've been running into an issue with a serializer I made for a particular model. This is the model: # Create your models here. class UserInfo(models.Model): id = models.IntegerField(primary_key=True, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=120, null=False) This is the serializer: class OnboardSerializer(serializers.ModelSerializer): class Meta: model = UserInfo fields = ('id', 'user', 'name', 'username') extra_kwargs = {'id': {'required': True}} This is the view: class OnboardAPI(generics.GenericAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = OnboardSerializer authentication_classes = (TokenAuthentication,) def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) When we try to run the OnboardAPI endpoint, we get the following error when we send this body { "id": 6, "user": 6, "name": "Muse" } django.db.utils.IntegrityError: null value in column "id" of relation "users_userinfo" violates not-null constraint DETAIL: Failing row contains (null, Muse, 6). It seems like the id column is not serialized, how do we fix this? Thank you! -
What is the propper way to debug gunicorn?
I am trying to deploy my very first Django applicatin on heroku. Gunicorn gives me this error: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> In this answer https://stackoverflow.com/a/55623889 command gunicorn app:application --preload -b 0.0.0.0:5000 is said to give detailed error message, but as its comments state it is not clear what words to replace with what. For instance somewhere I saw something similar called with <name of my app>.wsgi. To make matter worse name of my Django app in local is different from the one on Heroku. Also it is not clear to me should this be called strait from terminal (within virtual env) or should I be using some sort of gunicorn CLI. So what is the actual propper way to figure out what is failing gunicorn? -
display templates for each user Django
I have a side bar made up of 2 nav-items, during authentication I want parts of it to be visible to users, for example: user1: can see only the management part user 2: can see only the prediction part user3: can see only the management and prediction part I tried using pemrissions but that didn't work. but I think that's not what I'm looking for (permissions are related to models) I have no idea how to do it this way, An idea? -
How to use fetch data in another query
I transfer data from js to django by means of fetch post. I accept this data in a separate function. def fetch_post(request): context = { 'data': request.body } return HttpResponse() I need to pass this view data and create a context with the data from another function. class OrderTicketView(TemplateView): template_name = 'train_app/order_ticket.html' form = OrderTicketForm def get(self, request): context = { 'form': self.form, } return render(request, self.template_name, context=context) def post(self, request): context = { 'req': request.POST } return render(request, self.template_name, context=context) How to do it? -
how do I send a POST request via the command line in windows
I'm following this TUTORIAL for JWT in DJANGO here: https://www.geeksforgeeks.org/jwt-authentication-with-django-rest-framework/ I'm stuck because we are to make a POST request vial the command line. The tutorial is for Linux. How do I make an equivalent call on Windows via command line using the following $ http post http://127.0.0.1:4000/api/token/ username=spider password=vinayak I know in windows we would start with curl, but then I've tried multiple things such as curl -X POST .... and get errors. such as: Invoke-WebRequest : A parameter cannot be found that matches parameter name 'X'. At line:1 char:6 Thank you -
Django Rest Framework reverse serializer
Please I need a little help. I have a model like below class Person(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100) class Employee(models.Model): person = models.ForeignKey(Person, related_name='employee') code = models.CharField() In my EmployeeSerializer, how can I add the Person field Something like: class EmployeeSerializer(serializer.ModelSerializer): person = # Something the get **Person** instance code = serializers.IntegerField class Meta: model = Employee fields = [ 'id', 'person', 'code' ] -
Django - Edit referer when redirect
I'm using django3.1 with python3.6 I want to add a referer when redirecting URL. I'm using this code now, however, there is noting in referer. response = HttpResponseRedirect(target_url) response.set_cookie('name', name, max_age=9999, domain=None, samesite='None', secure=True) response['HTTP_REFERER'] = 'https://example.com' return response Is there any problem with my code? or it is impossible to add referer? -
RabbitMQ with Django Project and Scrapy to Push and Comume Message's
I've Django application that is working with Celery and using RabbitMQ as message broker. I've separate project for scrapy from where I scraped data and want to push this scrapped data into rabbitMQ then django will consume this RabbitMQ message's through celery. I need help to consume the message that pushed in rabbitMQ from scrapy project. code snippet. scrapy def process_item(self, item, spider): publish_message(item) return item def publish_message(data): import pika connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost', port=5672)) channel = connection.channel() channel.basic_publish(exchange='topic', routing_key='scrapy', body='Hello From scrapy!') connection.close() In django app, consumers.py import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', heartbeat=600, blocked_connection_timeout=300)) channel = connection.channel() def callback(ch, method, properties, body): print(" data =============== ", data) # I will call celery task here once code print the data to make sure its running. unfortunately its not running. :( return channel.basic_consume(queue='scrapy', on_message_callback=callback, auto_ack=True) print("Started Consuming...") channel.start_consuming() connection.close() celery.py from kombu import Exchange, Queue os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings.development') celery_app = Celery('my_project', broker='amqp://guest:guest@rabbit:5672', backend='rpc://0.0.0.0:5672') celery_app.config_from_object(f'django.conf:settings', namespace='CELERY') celery_app.autodiscover_tasks() celery_app.conf.update( worker_max_tasks_per_child=1, broker_pool_limit=None ) default_exchange = Exchange('default', type='topic') scrapy_exchange = Exchange('scrapy', type='topic') celery_app.conf.task_queues = ( Queue('scrapy', scrapy_exchange, routing_key='scrapy.#'), ) -
posts.models.Blog.DoesNotExist: Blog matching query does not exist
i am trying to use slug to navigate. here's the html tag <a href="{% url 'blog_details' blog.slug|slugify %}">Read More</a> urls.py path('details/<slug:slug>/', views.blog_details, name='blog_details'), models.py slug= models.SlugField(max_length=264,unique=True,null=True,allow_unicode=True) this is how i am creating auto slug def Creating_blog(request): form=BlogForm() if User.is_authenticated: if request.method=='POST': form=BlogForm(request.POST,request.FILES) if form.is_valid: blog_obj=form.save(commit=False) blog_obj.author=request.user title=blog_obj.blog_title blog_obj.slug = title.replace(' ','-') + '-'+ str(uuid.uuid4()) blog_obj.save() return redirect('index') return render(request,'blogs/creatingblog.html',context={'form':form}) this is the view of the blog details page def blog_details(request, slug): if User.is_authenticated: blog = Blog.objects.get(slug=slug) already_liked = Likes.objects.filter(blog=blog, user= request.user) if already_liked: liked = True else: liked = False comments=Comment.objects.filter(blog=blog) commet_form=CommentForm() if request.method=='POST': commet_form=CommentForm(request.POST) if commet_form.is_valid(): comment=commet_form.save(commit=False) comment.user=request.user comment.blog=blog comment.save() return HttpResponseRedirect(reverse('blog_details',kwargs={'slug':slug})) return render(request,'blogs/blogdetails.html',context={'blog':blog,'comment_form':commet_form,'comments':comments,'like':liked}) else: HttpResponseRedirect(reverse('login')) the problem is must be in C:\Users\ITS\Desktop\blogger\Blog\posts\views.py, line 51, in blog_details blog = Blog.objects.get(slug=slug) if i use pk=id instead of slug, it works. But whenever i am trying to catch with the slug the error rises. i am stuck for days here i can't find what's wrong. -
audio controls doens't appear while pass file from local storage - DJANGO
i want to pass audio file to template html from url. but when i add source, the audio controls doesn’t work or appear. so please help me to fix this. at my terminal and console, there’s no error message. i was using models to get the file to local storage. and here's my code: html: {% for record in rec %} <audio controls> <source src="{{record.audio.url}}" type="audio/mp3"> </audio> {% endfor %} views.py : def mp3_audio(request): rec = Audio_store.objects.all() return render(request, 'homepage.html' , {'rec': rec } ) models.py : from django.db import models from django.core.files.storage import FileSystemStorage from django.forms import widgets fs = FileSystemStorage(location='media/mp3') fss = FileSystemStorage(location='media/txt') class Audio_store(models.Model): password=models.FileField(storage=fss, null=True) audio=models.FileField(storage=fs, null=True) -
How to customize default user model fields django
I want to extend Django's User Model to include the fields DOB, Gender, Address and PhoneNo. This is what my Serializers.py file looks like: from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator from rest_framework_jwt.settings import api_settings class UserSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( required=True, max_length=32, validators=[UniqueValidator(queryset=User.objects.all())] ) first_name = serializers.CharField( required=True, max_length=32 ) last_name = serializers.CharField( required=True, max_length=32 ) # DOB = serializers.DateField( # required=True # ) # address = serializers.CharField( # required=True, # max_length=60 # ) # contactNo = serializers.IntegerField( # required=True, # # max_length=11 # ) password = serializers.CharField( required=True, min_length=8, write_only=True ) def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token class Meta: model = User fields = ( 'token', 'username', 'password', 'first_name', 'last_name', 'email', # 'DOB', # 'gender', # 'address', # 'contactNo', 'id' ) As you can see, I tried doing it through it, but that didn't work.. I also tried using OneToOneField() in models.py file to include the extra fields (it was empty and had no code) … -
How to fail a custom data migration?
I have written a data migration that initializes new tables with some rows. The objects have foreign keys to other tables, so I have to check that the foreign ids exist. If they don't, I would like to stop the migration with a error message. I have written two functions: forward and reverse. What is a recommended way of stopping a migration from within forward? def forward(apps, schema_editor): ... def reverse(apps, schema_editor): ... class Migration(migrations.Migration): dependencies = [ ("my_app", "0001_initial"), ] operations = [ migrations.RunPython(code=forward, reverse_code=reverse) ] -
django migration throws date format error
Trying to migrate using the following models.py from django.db import models from django.utils.text import slugify from django.utils import timezone # Create your models here. CATEGORY_CHOICES = ( ('action','ACTION'), ('drama','DRAMA'), ('comedy','COMEDY'), ('romance','ROMANCE'), ) LANGUAGE_CHOICES = ( ('english' , 'ENGLISH'), ('german' , 'GERMAN'), ) STATUS_CHOICES = ( ('RA' , 'RECRNTLY ADDED'), ('MW' , 'MOST WATCHED'), ('TR' , 'TOP RATED'), ) class Movie(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=1000) image = models.ImageField(upload_to='movies') banner = models.ImageField(upload_to='movies_banner') category = models.CharField(choices=CATEGORY_CHOICES , max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES , max_length=10) status = models.CharField(choices=STATUS_CHOICES , max_length=2) cast = models.CharField(max_length=100) year_of_production = models.DateField() views_count = models.IntegerField(default=0) movie_trailer = models.URLField() created = models.DateTimeField(default=timezone.now) slug = models.SlugField(blank=True, null=True) def save(self , *args , **kwargs): if not self.slug : self.slug = slugify(self.title) super(Movie , self).save( *args , **kwargs) def __str__(self): return self.title LINK_CHOICES = ( ('D' , 'DOWNLOAD LINK'), ('W' , 'WATCH LINK'), ) class MovieLinks(models.Model): movie = models.ForeignKey(Movie, related_name='movie_watch_link', on_delete=models.CASCADE) type = models.CharField(choices=LINK_CHOICES , max_length=1) link = models.URLField() def __str__(self): return str(self.movie) views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from django.views.generic.dates import YearArchiveView from .models import Movie, MovieLinks # Create your views here. class HomeView(ListView): model = Movie template_name = 'movie/home.html' def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['top_rated'] … -
Django : customizing FileField's current file in templates
I am rendering a simple form with a file field. class ReviewForm(forms.ModelForm): class Meta: model = Review fields = [ 'file', ] widgets = { 'file': forms.FileInput(attrs={'class': 'form-control'}), } While rendering, the form shows Current file - xyz.pdf besides the file input. However, I do not allow direct access to the files. All requests goes through the analytics_logger function before loading the file. So, I want to customise the Current file html from Current file - <a href="{0}">{1}</a> to Current file - <a href="{% url 'analytics_logger' {0} %}">{1}</a> How can I do it in Django 3.x? -
How to check validation on put method in django DRF
How to Perform Object-level validation in Django DRF PUT Method POST method It is working perfectly def validate(self, data): if len(data['name']) == len(data['discription']): raise serializers.ValidationError("Movie name and Discription are equal!") elif len(data['name']) > 10 : raise serializers.ValidationError("name is too big") return data -
Toggle nav-link active state in django
For changing the .nav-link activate state I wrote $(".nav-link").on("click", function(){ $(".nav-link.active").removeClass("active"); $(this).addClass("active"); }); But this won't work because the page reloads when clicking on the .nav-link. I can do something like var current_url = location.href; if (current_url == https://xyx.com/home) { $('.nav-link.home').addClass('active'); } else { $('.nav-link.home').removeClass('active'); } But when I was looking for another method I found this <li class="nav-item"> <a href="{{ route('home') }}" class="nav-link dropdown-toggle {{ request()->routeIs('home') ? 'active' : '' }}">Home</a> </li> <li class="nav-item"> <a href="{{ route('about') }} " class="nav-link {{ request()->routeIs('about') ? 'active' : '' }}">About</a> </li> This is Laravel code but I am looking something like this for Django.