Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django set auto-user from context, user field not be null, JWT
In my case,I use JWT authentication, and when I create new "Post"(my model), I want automatically set author to user that request it.But when I do it, I got an error { "author": [ "This field is required." ] } I know,I'm not passing user, but I want to set it automatically, and I dont know how. I just want to know how to avoid error, because when I pass value, that allows me to go ahead, the user is set automatically from context. Serializer class PostSerializer(FlexFieldsModelSerializer): class Meta: model = Post fields = ('title','content',author','category','likedBy') expandable_fields = { 'category': ('blogApi.CategorySerializer', {'many': True}), 'comments': ('blogApi.CommentSerializer', {'many': True}), 'likedBy': ('blogApi.LikedBySerializer', {'many': True}), } def create(self, validated_data): user = self.context['request'].user post = Post.objects.create( author=user, title=validated_data['title'], content=validated_data['content']) post.category.set(validated_data['category']) return post My create view class PostCreate(generics.CreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = [IsAuthenticated] Model class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField() category = models.ManyToManyField(Category, related_name='posts') author = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) likedBy = models.ManyToManyField(User, related_name='posts', blank=True) class Meta: ordering = ['-created'] def __str__(self): return self.title and when I create -
Related_name is returning an attribute error (NoneType) from a Django Forms. I'm trying to create a dynamic filter within forms
I'm using Django 3.1.4 with Python 3.7.8. I wanted to have form field for my ProductForm to automatically filter Category and Subcategory. I followed the suggest from https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html. However I keep getting an AttributeError, saying NoneType object has no attribute list. I used Django shell to see if my related_name would work. It the error keeps popping up. Here is my models.py: class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField( default=slugify(name), unique=True ) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name="list_of_subcategories" ) class Meta: verbose_name = 'Subcategory' verbose_name_plural = 'Subcategories' def __str__(self): return self.name Here is my forms.py: class ProductForm(ModelForm): class Meta: model = Product fields = [ 'sku', 'name', 'category', 'subcategory', 'short_description', 'description', 'price', ] def __init__(self, *args, **kwargs): super().__init__(*args,**kwargs) self.fields['subcategory'].queryset = SubCategory.objects.none() if 'category' in self.data: try: category_id = int(self.data.get('category')) self.fields('subcategory').queryset = Category.objects.filter(category_id=category_id).order_by('name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['category'].queryset = self.instance.category.list_of_subcategories.order_by('name') Here is my views.py: def loadSubcategory(request): category_id = request.GET.get('category') subcategories = SubCategory.objects.filter(category_id=category_id).order_by('name') return render(request, 'product/subcategory_drop_down.html', {'subcategories': subcategories}) def createProduct(request): if request.method == "POST": form = ProductForm(request.POST) if form.is_valid(): product_form = form.save(commit=False) product_form.company = request.user.company product_form.save() return redirect('dashboard:my_store') else: product_form = ProductForm() … -
Is it possible to deploy django + react app on digitalocean app platform?
I deployed my django app using digitalocean app platform(guide). I used js/jquery. And now I want to refactor my code and start using React. Is it possible to deploy django + react using app platform? -
django imagekit processors: changing Spec dependind on image dimensions
I want to generate thumbnails, whose bigger dimension is, say, 150px. Something like this: #models.py picture = models.ImageField(verbose_name=_('Image'), upload_to = "images") if image.width > image.height: picture_thumbnail = ImageSpecField(source='picture', processors=[ResizeToFit(**width**=150)], format='JPEG', options={'quality': 100}) else: picture_thumbnail = ImageSpecField(source='picture', processors=[ResizeToFit(**height**=150)], format='JPEG', options={'quality': 100}) Please give me an advice how to do it in django and imagekit (or, at least, other image processing package). Think that I need somehow get image field properties in my model... -
I want to change the default model of Token. I have added authentication.py file and while importing that on settings.py it shows an import error
ImportError: Could not import 'Token.custom_token.authentication.MyOwnTokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ModuleNotFoundError: No module named 'Token.custom_token'. Project Name: Token App name: custom_token Inside app-> authenticate.py file from .models import MyOwnToken class MyOwnTokenAuthentication(TokenAuthentication): model = MyOwnToken In settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'project_name.app_name.authentication.MyOwnTokenAuthentication', ] } In models.py class Organisation_User(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) organisation_id = models.CharField(max_length=10) organisation_name = models.CharField(max_length = 20) class MyOwnToken(models.Model): """ The default authorization token model. """ key = models.CharField(_("Key"), max_length=40, primary_key=True) organisation = models.OneToOneField( Organisation_User, related_name='auth_token', on_delete=models.CASCADE, verbose_name="Organisation_User" ) created = models.DateTimeField(_("Created"), auto_now_add=True) class Meta: verbose_name = _("Token") verbose_name_plural = _("Tokens") def save(self, *args, **kwargs): if not self.key: self.key = self.generate_key() return super(MyOwnToken, self).save(*args, **kwargs) def generate_key(self): return binascii.hexlify(os.urandom(20)).decode() def __str__(self): return self.key -
continue next codes after end of "if", no loop or while here
I have some codes about profile edit in Django views.py def account_edit(request): if not request.user.is_authenticated or request.user.is_staff or request.user.is_superuser: return redirect("/account/login") elif request.method == "POST": new_username = request.POST['username'] new_email = request.POST['email'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] phone_number = request.POST['phone_number'] location = request.POST['location'] if not new_username == request.user.username: if User.objects.filter(username=new_username).exists(): ctx = {'message_bad':'aaa'} else: username = request.user user_edit = get_object_or_404(User, username=username) user_edit.username = new_username user_edit.save() ctx = {'message_good':'aaa'} elif not new_email == request.user.email: if User.objects.filter(email=new_email).exists(): ctx = {'message_bad':'aaa'} else: username = request.user user_edit = get_object_or_404(User, username=username) user_edit.email = new_email user_edit.save() ctx = {'message_good':'aaa'} else: ctx = {} else: username = request.user user = get_object_or_404(User, username=username) ctx = {'user':user} return render(request, "account/account_edit.html", ctx) But after user_edit.username = new_username user_edit.save() Codes become stop, I want after finishing first if, Codes continue to work and save others -
How to reload configurations in Django (Python)
I'm new to Django. I made a URL shorter website like bitly for a test, and when users upload new URL, my program upload data to DB. The problem is that Django doesn't reload urls.py. So if users upload their URL, data is saved in DB, but urls.py doesn't reload, so 404 shows because urls.py is not reloaded, because there are no data about new URL in urls.py. I've searched in Google, I almost visited every website searched, but I couldn't find the answer. How do I reload Django configurations without turning off and on the django server? -
How can I change this code to upload multiple files in django and python?
My English is not good.. Hope you understand that.. I(beginner) use django and python, and I try to upload multiple files. finally i find working code but It is difficult to apply to the original code What am I doing wrong? (form.py, model.py is same each other) working ex code(views.py) def a(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) files = request.FILES.getlist("files") if form.is_valid(): for f in files: file_instance = Upload(file_upload=f) file_instance.save() return render(request, 'single_pages/about_me.html', {'form':form,}) # return HttpResponse(" File uploaded! ") else: form = UploadFileForm() return render(request, 'single_pages/about_me.html', {'form': form}) my Spaghetti code(views.py) def a(request, pk): if request.method == 'POST': comment_form = CommentForm(request.POST, request.FILES) files = request.FILES.getlist('files') if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.post = post comment.author = request.user comment.save() for f in files: file_instance = Comment(file_upload=f) file_instance.save() return redirect(comment.get_absolute_url()) else: return redirect(post.get_absolute_url()) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = {'content', 'file_upload', 'head_image'} files = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() head_image = models.ImageField(upload_to='blog/images/%Y/%m/%d/', blank=True) file_upload = models.FileField(upload_to='blog/files/%Y/%m/%d/', blank=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.author}::{self.content}' def get_absolute_url(self): return f'{self.post.get_absolute_url()}#comment-{self.pk}' def get_file_name(self): return os.path.basename(self.file_upload.name) def get_file_ext(self): return self.get_file_name().split('.')[-1] What should I do.. thank … -
Django create nested model
I want to create a Model in which I can store the same models as for example in a folder there can be several folders. I tried like this: class Service(models.Model): name = models.TextField(default="") price = models.IntegerField(blank=True, null=True) def __str__(self): return self.name class ServiceType(models.Model): services_types = models.ManyToManyField(ServiceType, null=True, blank=True) services = models.ManyToManyField(Service, null=True, blank=True) name = models.TextField(default="") But it didn't work. How can this problem be solved? -
Insert data on OneToOneField using django-rest-framework
I am new to this django-rest-framework, my problem is how am I going to insert a data with one-to-one relationship in the views.py. I can do the normal way of inserting data like the one below, def post(self, request,format=None): p = Person() p.firstname = "John" p.middlename = "K" p.lastname = "Rambo" p.save() e = Employee() e.code = "emp-002" e.person_id = p.id e.save() I cannot do the approach above because I want to learn more about DRF. To give you more idea please see below : I have this model class Person(models.Model): firstname = models.CharField(max_length=150, default="") middlename = models.CharField(max_length=150, default="") lastname = models.CharField(max_length=150, default="") class Employee(models.Model): person = models.OneToOneField(Person, on_delete=models.CASCADE,primary_key=True) code = models.CharField(max_length=100, default="") I have this serializer class PersonSer(serializers.ModelSerializer): class Meta: model = Person fields = ( 'id', 'firstname', 'middlename', 'lastname',) class EmployeeSer(serializers.ModelSerializer): person = PersonSer() class Meta: model = Employee fields = ('code','person') I have this view class SaveData(APIView): @transaction.atomic def post(self,request, format=None): p = PersonSer(data=request.data) if p.is_valid(): p.save() request.data['person'] = p.data['id'] request.data['code'] = "Emp-"+str(p.data['id']) """ I expect request.data now equal to { 'person' : 102, # we assume the newly created person id == 102 'code' : 'Emp-102', 'firstname' : 'John', 'middlename' : 'K.', 'lastname' : 'Rambo' } … -
How to add custom field to auth_permission model in django?
I am working with auth_permission model and to add extra fields in this model. class Permission(models.Model): name = models.CharField(_('name'), max_length=255) content_type = models.ForeignKey( ContentType, models.CASCADE, verbose_name=_('content type'), ) codename = models.CharField(_('codename'), max_length=100) Extra field I wanted to add is application_id = models.ForeignKey(ApplicationTbl, db_column='application_id', on_delete=models.CASCADE, blank=True, null=False) Can someone tell the work around to add it to auth_permission model. -
Send the response to user from other file instead of views.py form DRF
I am working on DRF in which I have created multiple pythons and importing that file into views.py but when I am trying to send the response to the user from another file it is not working I understand the behind the reason but is there any way to send the response to the user from other than view.py. view.py Structure #restframework view and all from concurrent.futures import ThreadPoolExecutor import other as o call FileView(APIView): #parseclass def post(self,request): o.func(d) Other.py from rest_framework.response import Response from rest_framework.status import status from django.conf import setting def func(d): return Response({"A":"OK"}) but Response is not coming to the user end. is there any way to send a response from other.py to the user instead of getting value and then send the response from the view.py? I am also implementing multithreading in my DRF. -
ModuleNotFoundError: No module named 'Productpages'
I m working on a Django project this is my first project so i don't understand Django well I create a app called pages and add it to settings.py I add a home view to views.py And I added it to url prattens But i got this error Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/mihin/PycharmProjects/Gshop/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/mihin/PycharmProjects/Gshop/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/mihin/PycharmProjects/Gshop/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/mihin/PycharmProjects/Gshop/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/mihin/PycharmProjects/Gshop/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/mihin/PycharmProjects/Gshop/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mihin/PycharmProjects/Gshop/venv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/mihin/PycharmProjects/Gshop/venv/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'Productpages' from django.shortcuts import render # Create your pages here. def home(request, *args, **kwargs): return render(request, 'products.html', {}) Here is my view.py it is … -
Error while creating forms on latest django version, ModelForm has no model class specified
I'm trying to make forms models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Restaurant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='restaurant') name =models.CharField(max_length=500) phone =models.CharField(max_length=500) address =models.CharField(max_length=500) logo =models.ImageField(upload_to='restaurant_logo/', blank=False) def __str__(self): return self.name forms.py from django import forms from django.contrib.auth.models import User from foodtaskerapp.models import Restaurant from django.forms import ModelForm class UserForm(forms.ModelForm): class meta: model = User fields = ("username","password","first_name","last_name","email") class RestaurantForm(forms.ModelForm): class meta: model = Restaurant fields = ("name", "phone","address", "logo") I'm getting this error: ValueError at /restaurant/sign-up ModelForm has no model class specified. -
Best way for writing validation code in django
For understanding purpose I will simplify my overall design. Suppose I have a table. ___________________________________ | id | start | end | ---------------------------------- | 1 | 2021-01-12 | 2021-01-30 | ----------------------------------- | 2 | 2021-01-11 | 2021-01-14 | ----------------------------------- | 1 | 2021-01-12 | 2021-01-15 | ___________________________________ In my views.py file I queried the table and got all row with id=1. And passed it as context to my html page. class BuyTicket(generic.ListView): template_name = "movie_user/buyticket.html" model = SetMovie def get_context_data(self, **kwargs): movies = MovieMaster.objects.filter(setmovie__isnull=False) context = super().get_context_data(**kwargs) idd = self.kwargs['pk'] set_movie = SetMovie.objects.filter(id=idd) #getting all rows with specific id from above table context['data_set'] = set_movie return context I am looping over the data (context['data_set']) from my views in my buyticket.html file. <div> {% for data in data_set %} <form method="POST"> {% csrf_token %} <label>Start Date:</label> <input type="text" readonly value="{{data.start_time}}"> <label>End Date:</label> <input type="text" class="" readonly value="{{data.end_time}} "> <input type="date" class="form-control" name="datee"> <input type="submit" class="btn btn-success" value="book"> </form> {% endfor %} </div> What I want to do is add validation to my only form field. <input type="date" class="form-control" name="datee"> This is a date input and it must lie between <input type="text" readonly value="{{data.start_time}}"> <input type="text" class="" readonly value="{{data.end_time}} "> Even If … -
How to do attribute filter in django models queryset
I have one model which I inherit in two other models class KycModel(models.Model): file_name = models.TextField(blank=True, null=True) class Pan(KycModel): pan_number = models.CharField(max_length=15, null=True) class Aadhar(KycModel): aadhar_no = models.CharField(max_length=15, null=True) I have to find total objects count in Pan and Aadhar models one way I can do with: Pan.objects.count() Aadhar.objects.count() but is there any way, to get all KycModel objects and apply filter or use Count annotation. a = KycModel.objects.all() pan_to = 0 aadhar_to = 0 for i in a: if hasattr(i, "pan"): pan_to += 1 if hasattr(i, "aadhar"): aadhar_to += 1 if I loop and apply hasattr(obj, "pan")...this will work but any better solution. -
How to show all the posts of America users if user is selected America ( In CharField Choices )
I am Building a BlogApp and I am stuck on a Problem. I want to show all the Post of U.S.A if request.user is selected U.S.A in CharField There's a one attribute named 'location' it have two choices 'America' and 'Australia'. I want it to shows only 'America Posts when user selects America'. When user selects 'America' then I want to show the all posts of only users that are selected America. if user selects 'Australia' then it finds all the users which are selected 'Australia' and show the posts of Australia users. views.py def showing_post(request,user_id): profiles = get_object_or_404(Profile,user_id=user_id) you = request.user shows = 'none' show = 'none' if profiles.location == 'America': show = Profile.objects.order_by('location') elif profiles.location == 'Australia': shows = Profile.objects.order_by('location') context = {'shows':shows,'show':show,'profiles':profiles} return render(request, 'opens.html', context) models.py country = [ ('America', 'America'), ('Australia',"Australia"), ] class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) location = models.CharField(max_length=30,choices=country,default='') opens.html {% if profiles.location == 'India' %} {% for p in show %} {{ p.location }} {% endfor %} {% endif %} The Problem When i check in the Page then it is showing all the users which selected the location of America and Australia, All are showing. What i am trying to do … -
How to generate 6 digits multiple OTP and insert into database at once with Django
I am generating 6 digits random OTP in my views.py and I just want to insert those many OTPs to be inserted into my Table at once using single QuerySet. Here is my code: home.html <form class="" action="" method="post"> {% csrf_token %} <div class="" style="text-align: center:"> Mobile : <input type="text" name="mobile" value=""> <input type="submit" name="submit" value="Generate OTP"> </div> </form> models.py class otpModel(models.Model): mobile = models.CharField(max_length=30, blank=False, null=True) otp = models.CharField(max_length=50, blank=False, null=True) def __str__(self): return self.mobile views.py import random from app_name.models import otpModel def registerOTP(request): if request.method == 'POST': mobile = request.POST['mobile'] for i in range(100): otp = random.randint(100000, 999999) otp = otpModel.objects.create(mobile=mobile, otp=otp) if otp: messages.info(request, 'OTP is saved!!!') return render(request, 'app_name/otp.html') else: return render(request, 'studentexams/otp.html') Here whenever I enter the Mobile number in the HTML form then only 1 OTP is inserted in the Table. Is there any solutions that I can insert multiple OTPs at a time using single QuerySet Please give the Code snippet for achieving this task to be done -
Making Django query if my class consists of a function? How do make a query which will return the sum of available_count for a particular device
class Magazine(models.Model): device = models.ForeignKey(RUDevice, on_delete=models.CASCADE, null=False, blank=False, related_name='ru_magazine', help_text="Select Device for magazine") magazine_number = models.PositiveIntegerField(_("Magazine Number"), default=0, help_text='Magazine number for selected Remote Unit') product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE, null=False, blank=False, related_name='magazine_product_type', help_text="Select product type") max_capacity = models.PositiveIntegerField(_("Maximum Capacity"), default=0, help_text='Select Maximum Capacity') def available_count(self): /*some code*/ return available_product I have tried: Magazine.objects.filter(device='some_device').aggregate(sum=Sum('available_count()')['sum'] -
How to show only one objects if there are few in Django?
I'm trying to user a list but still it shows all the values. allexpelorer1 = Destination.objects.filter(destination = pk).order_by('-pk') allexpelorer = [] for checkhu in allexpelorer1: if Destination.objects.filter(destination = pk, user_pk = checkhu.user_pk) not in allexpelorer: allexpelorer.append(checkhu) -
Django admin - How to display custom query results in default list view?
How can I write a custom query in Django admin and display the results in the default list view? Query: SELECT user,count(tag) as total_tags FROM group by user; Expected results in default list view: User Total tags John 30 Mark 15 -
How do I serialize ManyToMany Field data in Django?
So I'm working on Django back-end and React front-end. I have a many-to-many field in one of my models, and trying to serialize. I've googled some related issues and tried things out, but none worked. Let me show you my code first. models.py class Category(models.Model): objects = models.Manager category = models.CharField(max_length = 20) class Content(models.Model): objects = models.Manager() title = models.CharField(max_length = 100, null=True) category = models.ManyToManyField(Category) serializers.py class ContentSerializer(serializers.ModelSerializer): category_name = serializers.SerializerMethodField() class Meta: model = Content fields = [ 'title', 'category_name' ] def get_category_name(self, obj): categories = self.context['book'].category.all() return categories Finally, views.py @api_view(['GET']) def each_book(request, pk): this_book = Content.objects.get(pk=pk) serialized = ContentSerializer( this_book, context={ 'request':request, 'book' : this_book }, ) return Response(serialized.data) I keep on getting error saying Object of type Category is not JSON serializable. What do you think is the problem? Thanks a lot in advance. :) -
I am new to Django can anyone help me with the below task....?
Go through the sample JSON file given here - https://drive.google.com/open?id=1xZa3UoXZ3uj2j0Q7653iBp1NrT0gKj0Y This JSON file describes a list of users & their corresponding periods of activity across multiple months. Now, design and implement a Django application with User and ActivityPeriod models, write a custom management command to populate the database with some dummy data and design an API to serve that data in the JSON format given above. -
Sorting items by category in Django
I am a newcomer to Django and I want to know how can I categorize objects I've created in admin panel and sort them by those categories when rendered. This is what I tried but I don't know if it's how it works: class Post(models.Model): CATEGORY = ( ('popular', ('Popular Posts')), ('new', ('New Posts')), ('suggestions', ('Music Suggestions')), ) category = models.CharField('Post Category', max_length=40, choices=CATEGORY, default='popular') title = models.CharField('Title of the post',max_length=50) content = models.TextField('Page content', max_length=500) posted = models.DateTimeField('last updated') -
django.db.utils.NotSupportedError: NOWAIT is not supported on this database backend
I want to use select_for_update(nowait=True) in my Django project with MySQL database, but MySQL does not support NOWAIT. I don't have to wait until the transaction is complete; just raise an exception, if the object is locked. How can I achieve this?