Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
how to increment a like button in django with ajax?
i have a post in a community and i have implemented the like button in django + ajax but i notice that when i do like a post it increments all the post's likes.how can i solve it ? here is my template: {% for post in posts %} <div class="w3-container w3-card w3-white w3-round"> <a target="_blank" href="{{ post.author.profile.avatar.url }}"> <img src="{{ post.author.profile.avatar.url }}" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:60px"></a> <h4> <a href ='{% url 'profile' post.author.pk %}'>{{ post.author.profile.prenom|title }} {{ post.author.profile.nom|title }}</a> </h4> <span class="w3-opacity">{{ post.created|date:"d-m-Y H:i" }}</span> <br> <hr class="w3-clear"> <p> {{ post.contenu }}</p> <button type="button" class="btn btn-default btn-sm"> {{ post.comment_set.count }} <a href='#'><span class="glyphicon glyphicon-comment"></span> </a> </button> {% if request.user in post.liked.all %} <button type="button" class="btn btn-default btn-sm"> <span id='{{ post.id }}'>{{ post.liked.count }} </span> <a name="{{ post.id }}" style="color: blue;" class="likin" id="co"><span class="glyphicon glyphicon-heart"></span> j'aime</a> </button> {% else %} <button type="button" class="btn btn-default btn-sm"> <span id='{{ post.id }}'>{{ post.liked.count }} </span> <a name="{{ post.id }}" style="color: black;" class="likin" id="co"><span class="glyphicon glyphicon-heart"></span> j'aime</a> </button> {% endif %} {% if request.user == post.author %} <button type="button" class="btn btn-default btn-sm"> <a href='{% url 'delete' post.id community.id %}'><span class="glyphicon glyphicon-trash"></span> </a> </button> {% endif %} <br> <br> </div> <br> {% empty %} … -
How to restrict access to Chatting service only to registered websites
I am making a chatting service (something like Zendesk) and a website must be registered in order to use the service. There will be a frame which the website owner places in the .html file and the rest is up to me. Problem Anyone can start using the service right now (by reading the requests and copying them in Postman). I want a method to restrict access only to those websites that have registered to use the service. Failed solutions (to give an idea of what I am trying to do) A stupid idea was to read and send the website URL with JavaScript and check if it exists in the database, but that can easily be forged. I also tried generating unique tokens for each registered website, but the token is something that must be send with the request for validation and since it is something that public can see (the token is placed with the frame) that token is indeed meaningless. (Maybe I don't understand how tokens work) At this point, seems like this is inevitable, any Ideas? (Back-end is written in Django 3.1 and My database tables look like this, if it helps - Ignore the details, … -
How can I connect Django with Gulp SCSS broswer-sync?
I am trying to use SCSS using gulp with Django and I want to make this auto sync with using browser-sync. However, Django localhost cannot find the both CSS and template html files. Here's the gulpfile.js that I wrote. const gulp = require(‘gulp’); const sass = require(‘gulp-sass’); const browserSync = require(‘browser-sync’).create(); ... const watch = () => { browserSync.init({ server: { notify: false, port: 8000, proxy: ‘localhost:8000’ } }); gulp.watch(‘./static/scss/**/*.scss’, style); gulp.watch(‘./templates/**/*.html’).on(‘change’, browserSync.reload); gulp.watch(‘./static/js/**/*.js’).on(‘change’, browserSync.reload); }; exports.watch = watch; Also, my templates html and CSS file location are as follows: myproject ㄴstatic ㄴcss ㄴstyle.css ㄴscss ㄴstyle.scss ㄴtemplates base.html ㄴshop shop.html cart.html ㄴreservation ... How can I connect to my Django local host with using gulp? port is 8000 -
Django: Can I send HTTP response before executing post_save signal?
I have a form page when I submit it, Django executes a post_save signal and I am executing a workflow there. I am facing one issue that till workflow is not being executed it is not sending HTTP response to the front end. One solution can be using Celery to append the workflow in the queue. But I want to know if the HTTP response can be sent before the signal workflow execution? -
я генерирую pdf из html, локально все работает!! развернул на сервере, фотка загруженная через браузер не подгружаеся пдфке. использовал weasyprint [closed]
я генерирую pdf из html, локально все работает!! развернул на сервере, фотка загруженная через браузер не подгружаеся пдфке. использовал weasyprint html_string_front = render_to_string('pdf_student_front.html', data) html_front = HTML(string=html_string_front, base_url=request.build_absolute_uri()) result_front_student = html_front.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT + '/css/student-front.css')], presentational_hints=True) в чем может проблема -
django how to fetch all users in django allauth
I installed django allauth. And then build a User model in models: class User(AbstractUser): age = models.PositiveIntegerField(default=0, verbose_name='pv', blank=True) class Meta: verbose_name = "用户信息" verbose_name_plural = verbose_name def __str__(self): return self.username in settings: AUTH_USER_MODEL = 'news.User' After migrate, system doesn't create a User table,I can only see a auth_user table in database, and my users is in auth_user, but I have no idea how to fetch them out from auth_user, because I can't build a User model base on the auth_user table, and I don't know how to fetch the table in django. Any friend can help?