Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can You do this kind of website with django
I currently learning django . What I want to know is that can I make a website like https://themoviesflix.co/ with django and how much knowledge in django I need to make it. -
Adding Collaborator functionality to my Keep notes app
I am trying to do a clone of Google's Keep Notes app using Django rest framework .I am done with half of the work. But I cant figure out how can I implement that adding collaborator functionality. Any helps ? -
Deserialize Django model with marshmallow
I have 2 models in my Django project: class Item(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=1024) price = models.PositiveIntegerField() class Review(models.Model): grade = models.PositiveSmallIntegerField() text = models.CharField(max_length=1024) item = models.ForeignKey('Item', on_delete=models.CASCADE, related_name='reviews') I want to be able to deserialize Item model with nested reviews in it (which is a queryset of reviews) I described marshmallow schemas in a following way: class ReviewSchemaID(Schema): id = fields.Int() grade = fields.Int() text = fields.Str() class ItemReviewsSchema(Schema): id = fields.Int() title = fields.Str() description = fields.Str() price = fields.Int() reviews = fields.List(fields.Nested(ReviewSchemaID())) But when try to deserialize django object to JSON: item = get_object_or_404(Item, id=item_id) item_data = ItemReviewsSchema().dump(item) I get the following error: TypeError: __call__() missing 1 required keyword-only argument: 'manager' How can I fix the error? -
Where can I find the documentation of Django-filter
There is Django little framework called Django-filter, it is used for filtering looping elements in HTML template. If you are a Django-filter master please help me. The documentation is very short and I couldn't find many things by googling. I want to know how can I set price (increasing and decreasing order), title (A-Z, Z-A). Thank you for your help. -
How Django methods are invokes?
I’m beginner in Django. And I don’t understand how build-in methods Django are invoked. Let’s say we have this view: class HomeNews(MyMixin, ListView): model = News template_name = 'news/home_news_list.html' context_object_name = 'news' paginate_by = 2 def get_queryset(self): return News.objects.filter(is_published=True).select_related('category') def my_method1(self, id): value = id + 123 return = value Will how these methods invoked in my app? I don't call these explicitly. Will these invoked automatically? For example not django code I will invoke like a.method() but here we don't invoke but these work anyway. Explain please, I didn't find any information about this. -
save context elements in database with django
hello im using API arasaac to get images and i display them on a html page, i would like to save the context elements used for each image but i dont know how do to that here it is the view code @login_required(login_url="/login") def search(request): query = request.GET.get('query') if query: picto = api_request(query) form = UserPictogramsForm() message = "voici les résultats pour la recherche %s !" % query empty_message = "Mince nous n'avons trouvé aucun résultat pour '%s'" % query context = {"picto": picto, "message": message, "empty_message": empty_message, } if request.method == 'POST': # save in db {% for image in picto %} <div class="border border-dark col-md-6"> <div> {form.id_picto} <img class="img-fluid d-flex flex-wrap" src="https://api.arasaac.org/api/pictograms/{{ image.0 }}" alt=""> </div> {% if image.2 %} <audio controls src="https://static.arasaac.org/locutions/fr/{{ image.1 }}.mp3"></audio> {% endif %} <p>{{ image.1 }}</p> <button type="submit" class="btn btn-success">Ajouter</button> </div> {% endfor %} </div> So i want that people who click on button the context's elements (image.0 etc..) to be saved in DB. -
Django Rest Framework create pdf file from html
I'm trying to create a pdf file from html content, i did it well with weasyprint pacakge from template.html as a schema to send object of data to this html file and render it as pdf, but now i'm making api endpoint, so the html template won't be in my project,i only will create the object and send it with response, is it right that backend developer create this html document only and return it with response, how about android or ios developers will handle this. -
Query JsonField Django
I have a Schedule model with JSONField: class Schedule(models.Model): shifts = JSONField( ... ) My JsonField data pattern looks like following: { 'id': {'time': ['start_time', 'end_time'], 'department_id': 'department_id'} for example { '31239': {'time': ['09:00:00, '18:00:00'], 'department_id': '8'}, {'8327': {'time': ['11:00:00', '20:00:00'], 'department_id': '1'} ... and I have timestamp variable which is always sharp i.e. 10:00:00 or 14:00:00 but not 12:32:11 Is there any way to retrieve objects which do not have timestamp inbetween their time intervals. For example if timestamp variable equals to 10:00:00 only second example ({'8327': {'time': ['11:00:00', '20:00:00'], 'department_id': '1'}) would be returned. I am doing it in python now, but looking for a way to do it on DB side. -
How to Reordering the objects from ManyToManyField in Django?
i have two models, one is Articles and second is Pool, if i try to Reorder the positioning of objects of Articles or Pool just need to change the model name into get_object_or_404(Articles, pk=int(b['pk'])). But i want to Reordering the position of Pool.articles from (ManyToManyField) inside of Pool articles. i'm confused how can i use the position Field in Pool model for change position of articles. I would be grateful for any help. models.py class Article(models.Model): title = models.CharField(max_length=200) position = models.IntegerField(default=0, blank=True) class Pool(models.Model): pool_title = models.CharField(max_length=200) articles = models.ManyToManyField(Article) views.py def SortAble(request): if request.method == 'POST': books = json.loads(request.POST.get('sort')) for b in arts: try: art = get_object_or_404(Pool.articles, pk=int(b['pk'])) art.position = b['order'] art.save() except KeyError: pass return HttpResponse('saved') -
KeyError in request.session in Django
I have a Django application and I'm trying to pass a parameter from a view to another. However, I'm getting KeyError. Here is my first view; @csrf_exempt def get_checked_values(request): selected_inputs = request.POST.get('selected_inputs') sub_features = json.loads(selected_inputs) request.session['sub_features'] = sub_features return JsonResponse({'status': 'SUCCESS'}) Here is my second view; def optimize_view(request): customer_name = str(request.user) sub_features = request.session['sub_features'] return HttpResponse('Success') I can get the selected_inputs parameter from the request and assign it to the request.session in get_checked_values view but I can't use it in optimize_view because of the KeyError. How can I fix this? -
django admin pass parameters between the save_model and save_related methods
in the save_related method i calculate a total of the prices of items entered in tabularline, this total must appear in the save_model method to save the total purchase. how could I do this ? -
Where to put partial templates for multiple models rendered into a single view?
I have a parent model, let's call it Folder, to which several children models link. All children are subclasses of a base class File. Let's call the children M_File(File) N_File(File), etc. class Folder(models.Model): name = models.CharField(...) meta_data_1 = … class File(models.Model): name = models.CharField(...) class M_File(File): custom_field_1: ... custom_field_n: ... class N_File(File): custom_field_1: ... custom_field_n: ... etc. I would like to build a FolderDetailView which renders also all related files. To render each file, I would like to use a custom template as the files are fairly different. This should be possible by passing all files to the FolderDetailView and looping over them in the template like so: {% for file in files %} {% if file.filetype == 'M_File' %} ...Markup to render M_File... {% if file.filetype == 'N_File' %} ...Markup to render N_File... etc. {% endif %} {% endfor %} Yet looking at this, I cannot help but think that this cannot be the best or pythonic way. Is there another, more elegant way of achieving this? I've been thinking whether it's possible to build something similar to what Forms do when they render themselves once added to the page like so {{ form }}. -
Deploy strategy for Celery in ECS
The way we currently deploy Celery in ECS is by calling update-service on every code change. This works fine as far as swapping out the old code for the new. The problematic scenario is when we have long-running Celery tasks, and the deploy causes those to get killed. This is because ECS only gives a container 30 seconds to shutdown (you can increase that to 10 minutes, but even that isn't long enough in some cases). The killed Celery tasks do get successfully restarted by the new Celery worker(s), but you can imagine if you deploy once an hour, and your task takes 1.5 hours to finish, it will never complete. Ideally the deploy would tell the existing Celery worker(s) to stop gracefully, i.e. finish running tasks but don't start any new ones. Then it would start new worker containers with the new code, so you have old and new running at the same time. Then, when the long-running tasks have finished, the containers with the old code would be removed. This seems like a problem that must have been encountered by others but I can't find anything describing this. Scripting this probably wouldn't be too bad but it feels … -
TypeError: 'NoneType' object is not callable using restframework
i'm building a customer user using restframework, but i got this error : TypeError: 'NoneType' object is not callable while making a post request using postman here is traceback: Internal Server Error: /auth/register/ Traceback (most recent call last): File "/home/dailycoding/Desktop/projects/my_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/dailycoding/Desktop/projects/my_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/dailycoding/Desktop/projects/my_env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/dailycoding/Desktop/projects/my_env/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/dailycoding/Desktop/projects/my_env/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/dailycoding/Desktop/projects/my_env/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/dailycoding/Desktop/projects/my_env/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/dailycoding/Desktop/projects/my_env/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/dailycoding/Desktop/projects/myapp/users/views.py", line 7, in post serializer = self.serializer_class(data=user) TypeError: 'NoneType' object is not callable here is models.py from django.db import models from django.contrib.auth.models import(BaseUserManager,AbstractBaseUser,PermissionsMixin) # Create your models here. class UserManager(BaseUserManager): def create_user(self,username,email,password=None): if username is None: raise TypeError("users should have a username") if email is None: raise TypeError("users should have an email") user = self.model(username=username,email=self.normalize_email(email)) user.set_password(password) user.save() def create_superuser(self,username,email,password=None): if password is None: raise TypeError("password should not be none") user = self.create_user(username,email,password) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser): username = models.CharField(max_length=255,unique=True,db_index=True) … -
how to stop djoser from sending activation email when user is updated?
How to stop djoser from sending an activation email when using "users/me" Base Endpoint with a "put" or "patch" methods??? I have a "Boolean field" inside the user model and I want to make updates for this field using the "users/me" Base Endpoint in djoser, but when I do that, djoser sends an activation email to the user account although it is already activated. please someone help -
Django model - how to avoid orphant related objects?
I have a modelling question. Suppose I have the following model: class Person(models.Model): # user = models.OneToOneField(User) name = models.CharField(max_length=50, blank=False, null=False, default=None, unique=True) ratings = models.ManyToManyField('Rating', related_name="persons" ) class Critic(models.Model): # user = models.OneToOneField(User) models.CharField(max_length=50, blank=False, null=False, default=None, unique=True) ratings = models.ManyToManyField('Rating', related_name="critics" ) class Movie(models.Model): title = models.CharField(max_length=50, blank=False, null=False, default=None, unique=True) def __str__(self): return f"{self.title}" class Rating(models.Model): movie = models.ForeignKey(Movie, models.CASCADE) value = models.SmallIntegerField(blank=False, null=False, default=None) def __str__(self): return f"{self.movie}:{self.value}" when I want to populate the Database, it's all fine, but there is one step where a rating object is created, then added to a user's list of ratings, see below. >>> from imdb.models import Person, Critic, Movie, Rating >>> m = Movie(title="Movie1") >>> m.save() >>> p = Person(name="p1") >>> p.save() >>> r = Rating(movie=m,value=5) >>> r.save() >>> p.ratings.add(r) >>> p.ratings.all() <QuerySet [<Rating: Movie1:5>]> Is this a correct pattern? Is it possible to ensure no orphant ratings? I.e. create a rating and add it to a user more or less atomically? I tried the following that didn't work: p.ratings.add(Rating(movie=m3,value=2)) #error p.ratings.add(Rating(movie=m3,value=2).save()) #no error, rating created, but not added Note, that I have a Critic with related ratings too, so not an option to have a user field … -
difficulty setting up django-channels
Please, I have a sample django app that I am building that enables a manager create users as counter or kitchen staff. Counter staff can take orders. When orders are taken by counter staff, it is automatically sent in real-time to the pending screen of all kitchen staff. Kitchen staff can fulfill an order. Manager can see all orders. But I want the orders to be updated real-time, without need to refresh the page, I have tried my best with django-channels but nothing is working. Below are the samples of my code for clarification Views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .forms import NewUserForm, NewOrderForm, UpdateOrderForm from .models import User, Order from datetime import datetime from django.contrib import messages # Create your views here. @login_required def dashboard(request): user = request.user if user.user_type == 'counter_staff': response = redirect('counter_page') return response elif user.user_type == 'kitchen_staff': response = redirect('kitchen_page') return response elif user.user_type == 'manager': response = redirect('manager_page') return response else: messages.error(request, 'You are not authorized to login, contact your manager') return redirect('login') @login_required def kitchen(request): user = request.user if user.user_type != 'kitchen_staff' and user.user_type != 'manager': message = 'You are not authorized to view this page' return … -
Django 3.1 JSONField attempts to deserialized dict
I am running into issues using the new django.db.models.JSONField where it appears the column comes back from the database already deserialized i.e. already a dict. The model attempts to deserialize the value again resulting an exception. TypeError: the JSON object must be str, bytes or bytearray, not dict This exception is being thrown from json.loads call in the from_db_value method on the JSONField class definition. def from_db_value(self, value, expression, connection): if value is None: return value try: return json.loads(value, cls=self.decoder) except json.JSONDecodeError: return value We are running postgres and the column is defined in the database as json i.e. not jsonb. My models that have columns that are jsonb do not appear to have this error. I do not appear to have the issue when the the column on the model is saved as a string. Only when the column is a dict. class MyModel(models.Model): data = models.JSONField() m1 = MyModel(data=json.dumps({"key": "value"}) m1.save() m1.refresh_from_db() m2 = MyModel(data={"key": "value") m2.save() m2.refresh_from_db() # Exception thrown here My guess is that it is being double encoded in this case. Whatever is causing it to be decoded into a dict is decoding it and then it's being decoded into a dict at the model … -
Django variable number of filters on ManyToManyField objects?
I'd like to filter objects on a ManyToManyField using two attributes of the objects that is pointed to by ManyToManyFeild. See the model below, this is a classical user-items relationship from django.db import models class Person(models.Model): # user = models.OneToOneField(User) name = models.CharField(max_length=50, blank=False, null=False, default=None, unique=True) ratings = models.ManyToManyField('Rating', related_name="persons" ) class Movie(models.Model): title = models.CharField(max_length=50, blank=False, null=False, default=None, unique=True) def __str__(self): return f"{self.title}" class Rating(models.Model): movie = models.ForeignKey(Movie, models.CASCADE) value = models.SmallIntegerField(blank=False, null=False, default=None) def __str__(self): return f"{self.movie}:{self.value}" So, I'd like to find all users who gave above certain rating to Movie1 AND above certain rating to Movie2. I can do this with cascading filters: >>> Person.objects\ .filter(ratings__movie__title='Movie1', ratings__value__gte=5)\ .filter(ratings__movie__title='Movie2', ratings__value__gte=1)\ .all() [[A<QuerySet [<Person: Person object (1)>]> But I am looking for a way to filter on any arbitrary number of ratings, not just 2. I have tried with Q (in the case single filter() for all cases), but the following doesn't work: >>> Person.objects.filter( Q(ratings__movie__title='Movie1') & Q(ratings__value__gte=5),\ Q(ratings__movie__title='Movie2') & Q(ratings__value__gte=1) ).all() <QuerySet []> Thanks for help -
Best way to use Index in Django and PostgreSQL
I am using Python, Django and PostgreSQL for my application development. My Database has millions of records and I have to generate reports in real-time (runtime)using those data. While generating those reports the application gets timed out and not able to generate reports. if the data is around 50k it is generating an excel file but when the data is in millions, the query is unable to run. Which is the best way to implement Index through Django Model or PostgreSQL Index? Please help me in optimizing the query to make it faster. Version PostgreSQL 13.1, compiled by Visual C++ build 1914, 64-bit EXPLAIN (ANALYZE,BUFFERS) Select V."MERCHANT_ID",V."ACCOUNT_NUMBER",V."GIFT_LIST_REF",(Select "store_id" FROM vd_store_master WHERE "store_id"=V."GIFT_LIST_REF") as owingin_store_id,(Select "store_name" FROM vd_store_master WHERE "store_id"=V."GIFT_LIST_REF") as owingin_store_name,(Select "franchisee_id" FROM vd_store_master WHERE "store_id"=V."GIFT_LIST_REF") as owingin_franchisee_id,(Select "franchisee_name" FROM vd_franchisee WHERE "franchisee_id"=(select "franchisee_id" FROM vd_store_master where store_id=V."GIFT_LIST_REF") ) as owingin_franchisee_name,(select "merchant_name" from vd_merchant_master where merchant_id=V."MERCHANT_ID") as merchant_name FROM vdaccount_card_assign V WHERE "MERCHANT_ID"='003561002966107' and "CARD_STATUS"='D' "QUERY PLAN" "Seq Scan on vdaccount_card_assign v (cost=0.00..2056093.85 rows=149948 width=1362) (actual time=0.144..7171.425 rows=154405 loops=1)" -
I am getting this error when i run migration with sudo premission in django
*Can anybody help me I get this error when I run migration with Sudo permission * File "/home/dell/.local/lib/python3.6/site-packages/django/db/migrations/graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0013_auto_20210105_1445 dependencies reference nonexistent parent node ('auth', '0012_alter_user_first_name_max_length') -
List out of range error in my code in Django. When i go to download a pdf file
I want to download a patients pdf file but when i click in download button this error is come. Please anyone can help me about this error .. views.py def download_pdf_view(request,pk): dischargeDetails = PatientDischarge.objects.all().filter(admitted=pk).order_by('-id')[:1] dict = { 'assign_doctor': dischargeDetails[0].assign_doctor, 'admitted': dischargeDetails[0].admitted.patient_name, 'phone': dischargeDetails[0].admitted.phone, 'address': dischargeDetails[0].admitted.address, 'symptoms': dischargeDetails[0].admitted.symptoms, 'release_date': dischargeDetails[0].release_date, 'medicine_cost': dischargeDetails[0].medicine_cost, 'other_charge': dischargeDetails[0].other_charge, 'days_count': dischargeDetails[0].days_count, 'room_bill':dischargeDetails[0].room_bill, 'total_bill': dischargeDetails[0].total_bill, } return render_to_pdf('hospital/pdf_template.html',dict) models.py: class PatientDischarge(models.Model): assign_doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) admitted = models.ForeignKey(Admitted, on_delete=models.CASCADE) release_date = models.DateField(auto_now_add=False) medicine_cost = models.IntegerField(null=True) other_charge = models.IntegerField() def __str__(self): return self.admitted.patient_name if all([self.admitted, self.admitted.patient_name]) else 0 def days_count(self): return self.release_date - self.admitted.admited_date if all([self.admitted, self.admitted.admited_date]) else 0 -
Django unable to translate language
I want to translate my website to CH, but no response after I followed the online instruction. Did I miss something? I have changed the language code in setting.py setting.py import os import django_heroku from django.utils.translation import gettext_lazy as _ LANGUAGES = ( ('en', ('English')), ('zh-Hant', _('Traditional Chinese')), ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', ... ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMP_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.i18n', 'django.template.context_processors.debug', ....]} #LANGUAGE_CODE = 'en-us' LANGUAGE_CODE = 'zh-Hant' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale') ] Added the tag for translation in html base.html: {% load i18n %} <!DOCTYPE html> <html> .... home.html: {% extends "base.html" %} {% load i18n %} {% block content %} {% trans "Let's translate this" %} .... Updated msgstr in ....\locale\zh-Hant\LC_MESSAGESdjango.po: msgid "Let's translate this" msgstr "來翻譯這個" -
How to access Django queryset when for loop is not possible
I'm making my portfolio site. Each project is developed with multiple technologies, such as a "website" created with Python, Django and Bootstrap. So I defined my models like this: class Technology(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = 'Technologies' class Project(models.Model): name = models.CharField(max_length=200) description = models.TextField() date = models.DateField() technology = models.ManyToManyField(Technology) image = models.ImageField(upload_to='projects') def __str__(self): return self.name views.py: def index(request): projects = Project.objects.all() return render(request, 'homepage/index.html', context={'projects': projects}) Now here's the challenge: In my template I want to display 6 projects with the project name and technologies extracted from the '''queryobject'''. However right now I have only one project. So: How to display one set of HTML tags for first project and another set (placeholders) for the rest? So the first project shows the data from database, and the rest 5 show a "coming soon" (please refer to attached screenshot)? And later when I add the second and third projects to the database, the output update itself accordingly? Since the "technology" field is a manytomany field, there is more than one value in it (Python, Django, Bootstrap for example). How to access it in my template? -
Why does my heroku app not appear on google search results
I have deployed my django project on heroku. I can access my it via my domain www.example.com and I have comfirmed domain ownership on google search console.I have provided sitemaps on google search console and requested indexing. Its been about two days and i can not see my website on google search results. I have also tried using site:my_domain.com but still cannot find any results