Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to exclude show filters for specific endpoint in drf-yasg
I have some ViewSet with filterset_fields and ordering_fields attributes. Also i have extra action in that ViewSet, that uses as a shortcut to get list with some filtration. I assume to use that extra action without handling any additional filter(or may be ordering) options. But in default way drf-yasg genereates parameters schema for that extra action with filterset_fields and ordering_fields. How i can ignore filterset_fields and ordering_fields attributes for specific endpoint? -
How to write test with foreign/manytomany key - Django
Please help me understand writing a test model for book model with foreign key. I am working on the local library project tutorial done by MDN. Right now it is giving me error Error is as follows ERROR: setUpClass (catalog.tests.test_models.BookModelTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/test/testcases.py", line 1201, in setUpClass cls.setUpTestData() File "/Users/rishipalsingh/Projects/notes/mdndjango/mdn/catalog/tests/test_models.py", line 68, in setUpTestData Book.objects.create(title='who sold my safari', author=['first_name', 'last_name'], summary='book is about the story of person who found out that his safari is sold', genre='name', Language='name') File "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/db/models/query.py", line 451, in create obj = self.model(**kwargs) File "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/db/models/base.py", line 485, in __init__ _setattr(self, field.name, rel_obj) File "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py", line 215, in __set__ raise ValueError( ValueError: Cannot assign "['first_name', 'last_name']": "Book.author" must be a "Author" instance. Book code for your reference is as follows class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book') isbn = models.CharField('ISBN', max_length=13, unique=True, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>') genre = models.ManyToManyField( Genre, help_text='Select a genre for this book') language = models.ManyToManyField( Language, help_text='Select Language for this book') def get_language(self): return ', '.join(language.name for language in self.language.all()) get_language.short_description = 'Language' class Meta: … -
Random NoneType Exception when running Django + Guardian with PGPOOL-II
I have kinda complex topic today I would like to share with you. We are running a "massive" Django Backend with high focus on High Availability. For legal reasons we had to change our infrastructure provider and started hosting main database internally (on our kubernetes cluster) instead of using one of the popular Database as a Service offerings. Long story short, with bringing pgpool-II into the game we suffer from random NoneType errors that nobody can explain. Actually the plan was to write a guide how to setup a scalable, ha & production-rdy deployment on k8s.However,for now it seems that there are issues to solve/understand, beforehand. Consider the following setup: We are deploying Django-Applications with Guardian as Docker-Containers to k8s Django 3.2.3 Gunicorn 20.1.0 with uvicorn Workers (0.13.4) ASGI 3 Protocol (asgref 3.3.4) Django-Guardian 2.3.0 Our PostgreSQL Cluster is based on the latest bitnami/postgresql-ha image Pgpool-II (2.2) and PostgreSQL (11.12) Follow best practices we use django's signal logic to execute permission assignment as part of the post_save for various models. What we see now that maybe 1 out 50 requests fails with an NoneType exception. If you check the error trace I linked then u will see the "real" problem … -
submitted data through form but not stored in database
I have created models.py as well as views.py, wanted to submit data through the front page and those need to store in the database but failed to sent data. when I click to submit after fillup the form it goes to the else block which is mentioned in views.py but not checking if statement. help appricated. models.py from django.db import models # Create your models here. # creating modeles here and storing in database acts as mysql class Contact(models.Model): usn = models.CharField(max_length=50, primary_key=True) name = models.CharField(max_length=50, default="") sem = models.CharField(max_length=50, default="") phone = models.CharField(max_length=50, default="") email = models.CharField(max_length=50, default="") def __str__(self): return self.name views.py from django.shortcuts import render, redirect, HttpResponse from django.conf import settings from .models import Contact # Create your views here. def index(request): if request.method=="POST": usn = request.POST.get('usn','') name = request.POST.get('name','') sem = request.POST.get('sem','') phone = request.POST.get('phone','') email = request.POST.get('email', '') if usn and name and sem and phone and email: contact = Contact(usn = usn, name = name, sem = sem, phone = phone, email = email) contact.save() else: return HttpResponse("Enter all details") return render (request, 'index.html') -
drf-spectacular: Specify empty payload using @extend_schema
Consider that I have a simple view as, # serializers.py class EmptyPayloadResponseSerializer(serializers.Serializer): detail = serializers.CharField() # views.py from rest_framework.views import APIView from rest_framework.response import Response from drf_spectacular.utils import extend_schema from .serializers import EmptyPayloadResponseSerializer class EmptyPayloadAPI(APIView): @extend_schema(responses=EmptyPayloadResponseSerializer) def post(self, request, *args, **kwargs): # some actions return Response(data={"detail": "Success"}) When I render the schema, I have got the following error response, Error #0: EmptyPayloadAPI: unable to guess serializer. This is graceful fallback handling for APIViews. Consider using GenericAPIView as view base class, if view is under your control. Ignoring view for now. So, how can I tell to @extend_schema decorator that I'm intended to pass nothing as payload? -
How to do f string for exec?
This is my Django app name SFC This is its models.py: from django.db import models import time color = ( ('1','果盤'), ('3','港灣'), ('5','輕快感'), ('6','鵝卵石'), ('7','調味料'), ('8','農收'), ('9','開瓶'), ('10','潛水'), ) # The Chinese in the tuple name color is a noun describe the color. # Create your models here. class class_site(models.Model): school_name = models.CharField("學校英文縮寫",max_length=10,default='CKJH') Class = models.CharField("班級",max_length=5,default='802') page_name = models.CharField("網頁名稱",max_length=10,default='八我啊二班') color = models.CharField('配色',max_length=8,choices=color,default="6") logo = models.ImageField('網站logo',null=True) def __str__(self): return self.school_name+self.Class+self.page_name and it's another app name WT This is its models.py: from django.db import models from SFC.models import class_site # Create your models here. for i in class_site.objects.all(): code=f'''class {i.school_name + i.Class}subject(models.Model): subject = models.CharField('科目名',max_length=10) class {i.school_name + i.Class}WorkType(models.Model): subject = models.ForeignKey({i.school_name + i.Class}subject , on_delete=models.CASCADE) work_name = models.CharField('功課名稱',max_length=10,default='習作') common_name = models.CharField('功課俗名',max_length=10,default='國習') class {i.school_name + i.Class}ExamType(models.Model): subject = models.ForeignKey({i.school_name + i.Class}subject , on_delete=models.CASCADE) work_name = models.CharField('考試名稱',max_length=10,default='大卷') common_name = models.CharField('功課俗名',max_length=10,default='國卷') ''' exec(code) It send me: class CKJH802WorkType(models.Model): ^ IndentationError: unindent does not match any outer indentation level I tried not to use f string but i tkink it may be work by using f string. What's wrong with models.py of WT? -
Better way of creating through table record Django
I have two models with a through table: class Subscriber(models.Model): first = models.CharField(max_length=30) last = models.CharField(max_length=30) email_confirmed = models.BooleanField(default=False) class Newsletter(models.Model): title = models.CharField(max_length=100, default="Tiffany's Dynamic Digest") body = models.TextField(null=False, blank=False) subscribers = models.ManyToManyField('Subscriber', through='NewsletterEngagement') class NewsletterEngagement(models.Model): subscriber = models.ForeignKey(Subscriber, on_delete=models.CASCADE) newsletter = models.ForeignKey(Newsletter, on_delete=models.CASCADE) To create a record in the NewsletterEngagement model I have the following code: subscriber = Subscriber.objects.get(pk=1) newsletter = Newsletter.objects.get(pk=1) m1 = NewsletterEngagement.objects.create(subscriber=subscriber, newsletter=newsletter) To my mind (although I am very inexperienced) this requires 3 trips to the database, is there a more efficient way of creating the record? -
Is there way to speed up the updating large amount of data in MongoDB? [pymongo]
I am trying to update one data source based on another data source and give the user a preview of updated data. I am using Django and MongoDb for these implementations. First: I extracted the main data source to a temporary collection and limited it to 100 elements. ( It is enough for just a preview. ) catalog_collection.aggregate( [ { '$limit': 99 }, { '$out': tmp_output } ] ) Now I need additional data source to make updates on. The problem is it is usually a large data set contains up to 20.000 product data. It is an XML file so I downloaded it and write it to a temp file. ( Here I have doubts because I could insert it to another temp collection and merge them together. I suppose it is faster? ) Second: With the two data, I need to get the join field (let's suppose it is id field) and its value, and update them. Basically this: UpdateMany({ "id": {"$eq": second_data['id'] }},{"$set": {"price": second_data['price']}}) So what I am doing is, looping through the elements of second data, trying to find if there is the same id element on the first data source. If there is, I … -
Django survey form wont render questions
I have been trying to recreate this survey form in my application: Django survey with forms I only have one survey saved and this is the only one I need for my app (it should only include one survey at the end of a research). I have made a few changes, but I am having trouble to render the questions to the UI. Currently the evaualtions.html file shows "No questions" which indicates that the code somehow works, but still something is missing to get the questions to the page. This is what I have: models.py MC = 'MC' TX = 'TX' CATEGORY = ( (MC, 'Multichoice'), (TX, 'Text'), ) One = '1' Two = '2' Three = '3' Four = '4' Five = '5' MULTICHOICE = ( (One, 'Least'), (Two, 'Less than average'), (Three, 'Average'), (Four, 'More than average'), (Five, 'Most'), ) class Questionnaire(models.Model): questionnaire_name = models.CharField(max_length=100, verbose_name="Questionnaire", null=False, default=None, blank=False) def __str__(self): return self.questionnaire_name class Question(models.Model): questionnaire = models.ManyToManyField(Questionnaire) question_text = models.CharField(max_length=200, verbose_name="Questionnaire name", null=True, default=None, blank=True) question_category = models.CharField(max_length=2, verbose_name="Question category", null=False, choices=CATEGORY, default=None, blank=False) def __str__(self): return self.question_text class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) class MultiChoiceAnswer(Answer): answer = models.IntegerField(choices=MULTICHOICE) def __str__(self): return self.answer evaluation.html -> This is … -
Django - Good database design practice: Should auxiliary fields be linked to the base user model or the employee model?
My current database design uses the Django default User model for authentication (and authentication only). I also have an Employee model that has a one-to-one relationship with the User model and holds information such as the company they are at, the date they joined the company etc. I have another model called Roles - it contains information regarding various "roles" that an employee at that company might need to fulfil. My question is: should the Roles model be linked by a foreign key to the Employee model or to the User model? There are several other models similar to the Roles model that need to be linked to either the Employee or the User but I am not sure which is best practice. In my mind it makes sense to link it to the Employee - this would make handling the event of a User moving companies far easier. But I have heard it is good practice to link everything to one central/base table - in this case the User. Any advice would be much appreciated. TIA -
What is the best way to store long text and tabular documents in a database with full text search
My application stores millions of legal documents, ranging from 1 page to 3000 pages long. Currently my model looks like this: class Document(models.Model): title = TextField() content = ArrayField(TextField()) search_vector = SearchVectorField(null=True) So a sample document use case looks like this: doc = Document(title="Legal brief", content=["page 1 text...", "page 2..."]) The reason for using an array is that I include an HTML horizontal line with a page number at the bottom of every page in the application. Then I'm using a custom Postgres trigger function that uses the array_to_string function to roll the list of pages into a single tsvector and keep the search_vectors field updated for full text search and ranking. My question is should I refactor my model to include a Page object, and store each text page in a separate object type? The use case is such that I never access a single page individually, and the document once created is static - they never ever change. My primary concern is to make search as fast as possible, especially across the entire database (all millions of documents), and my secondary concern is that a tiny portion of my documents are very long (1000+ pages) and do not … -
Using ajax with django failed with 404 error
I'm trying to use ajax to prevent refreshing the website when someone hit the like button on the page. Since I am new to ajax, I've tried some method to link Django with ajax. I know that I should pass csrftoken to Django when using form or ajax, but it turns out not working. Chrome console shows the error message of Failed to load resource: the server responded with a status of 404 (Not Found) with the current page url and the csrftoken, something like http://127.0.0.1:8000/event/TuffGeRykWO2jZAEGl6DNIxmwXH3x5tMjCvx6SHv5TsS7DpOCB3j4fBvF0BEFamu And here's are my code of ajax // pug file #likebutton(style="background-image: url('/static/file/like-bg-n.png')") button(type="image", src="{% static 'file/like-bg-n.png' %}", alt="Submit Form",name="event_id", value="{{ event_detail.id }}") span#like-img {% endif %} script. $(document).ready(function(){ $("#likebutton").on("click", function() { like_handler("{% url 'like' %}", "{{ csrf_token }}", "{{ event_detail.id }}"); }) }) // js file function like_handler(CSRF, URL, event_id) { $.ajaxSetup({ data: { csrfmiddlewaretoken: CSRF } }); var csrftoken = $('[name="csrfmiddlewaretoken"]').val(); $.ajax({ type: 'post', url: URL, data: { event_id: event_id, 'csrfmiddlewaretoken': csrftoken }, dataType: 'json', success: function(data) { data = JSON.parse(data); if (data.status == '200') { console.log('success') if (data.add) { $('#likebutton').attr("src", "/static/file/like-bg-y.png") $('#member').append( "<a herf='{% url 'profile' request.user.userextend.pk %}'> \ <img class='member interested' src='{{ request.user.userextend.img.url }}'/></a>" ) } else if (data.remove) { $('#likebutton').attr("src", … -
Migration error(Migration is applied before its dependency accounts.0001_initial on database 'default')
I'm trying to migrate my custom user model and I run makemigrations command to make migrations for new models. But when I run migrate command it throws this error : raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'. Trace back: Traceback (most recent call last): File "C:\Users\enosh\venv_ruling\ruling\manage.py", line 22, in <module> main() File "C:\Users\enosh\venv_ruling\ruling\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\commands\migrate.py", line 95, in handle executor.loader.check_consistent_history(connection) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\migrations\loader.py", line 306, in check_consistent_history models.py from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): """extend usermodel""" class Meta: verbose_name_plural = 'CustomUser' I just mentioned user model in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
Please help me to convert following flask to django code
I have to convert this code to django @app.route("/<filename>") def send_image(filename): return send_from_directory("static", filename) here, filename is a absolute path with image name I have to make this without forms! -
How to store date input in SQLite database in Django?
I have a sqlite3 database table column with a Date field, the format of the date I am trying to store is 2021-01-01. But it's not storing the date and returning None when I am printing the table information in the template. Thank You in models.py: date_input = models.DateField() in forms.py: date_input = forms.DateField(widget=forms.widgets.SelectDateWidget(),required=True) -
Django: How to get latest record?
What I want to do is that for a particular Cylinder Id , if cylinder is issued then the user name and the issue date will be displayed in cylinder List ans also if cylinder is returned then the return date will be displayed in cylinder List so for that i used prefetch_related and in template i iterate the issue and return model like this :- {%for cy in cylinder %} <tr bgcolor="#e6f0ff" align="center"> <td align="center" height="10" width="50"><a style="border-width: 0px" href="{{cy.get_absolute_url}}">{{cy.cylinderId}}<a></td> <td align="center" height="10" width="50">{{cy.EntryDate}}</td> <td align="center" height="10" width="50">{{cy.gasName}}</td> <td align="center" height="10" width="50"> {{cy.cylinderSize}}</td> <td align="center" height="10" width="50"> {{cy.Status}}</td> <td align="center" height="10" width="50">{{cy.Availability}}</td> {% if cy.issue_set.all%} {% for issue in cy.issue_set.all %} <td align="center" height="10" width="50">{{issue.issueDate}}</td> <td align="center" height="10" width="50">{{issue.userName}}</td> {% endfor %} {% else %} <td align="center" height="10" width="50">-</td> <td align="center" height="10" width="50">-</td> {% endif%} {% if cy.return_set.all%} {% for return in cy.return_set.all %} <td align="center" height="10" width="50">{{return.returnDate}}</td> {% endfor %} {% else %} <td align="center" height="10" width="50">-</td> {% endif%} </tr> {% endfor %} </tbody> {% else %} But another problem is happening that if I reissue the same cylinder/return again the same cylinder Id, so in cylinder list table it is showing all issue and return entries created … -
Django cart.get_total_price [<class 'decimal.ConversionSyntax'>]
I have a cart app in my Django Ecommerce web-site and when I click on update, when I need to update item quantity in the cart, I get an error [<class 'decimal.ConversionSyntax'>], which highlights this snippet in onlineshop/base.html:{{ cart.get_total_price }}GEL base.html: {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>{% block title %}My Shop{% endblock %}</title> <link href="{% static "css/base.css" %}" rel="stylesheet"> </head> <body> <div id="header"> <a href="/" class="logo">My Shop</a> </div> <div id="subheader"> <div class="cart"> {% with total_items=cart|length %} {% if total_items > 0 %} Your cart: <a href="{% url "cart:cart_detail" %}"> {{ total_items }} item{{ total_items|pluralize }}, {{ cart.get_total_price }}GEL </a> {% else %} Your cart is empty {% endif %} {% endwith %} </div> </div> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> cart.py: from decimal import Decimal from django.conf import settings from onlineshop.models import Product class Cart(object): def save(self): self.session.modified = True def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID]={} self.cart = cart def add(self, product, quantity=1, override_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id]={'quantity':0, 'price':str(product.price)} if override_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def remove(self, product): product_id … -
how to use keycloak in django rest framework with custom authentication
A better title for this question would be: how to use keycloak in django grpc framework. I want to handle user registration with keycloak. this is the my service without keycloak: class UserService(Service): def Create(self, request, context): serializer = UserProtoSerializer(message=request) serializer.is_valid(raise_exception=True) serializer.save() # some code for sending activation email return serializer.message and I'm using a custom user. I have created a realm and client in keycloak admin console. what is the best way of relating these two? shall I try using drf-keycloak-auth or python-keycloak? -
Django Error - ImportError: cannot import name 'first_app' from 'first_project'
I am new to Django and was starting with the new Project. I faced this issue while I was trying to pass in application URLs. ImportError: cannot import name 'first_app' from 'first_project' (E:\Project\DjangoProject\first_project\first_project_init_.py) view.py inside the first_app urls.py inside the first_app urls.py inside the first_project -
"MyVar" is not definedPylancereportUndefinedVariable
goal: I am trying to create I, reusable class, for Django and I created a variable called MyVar inside it in order to overwrite it later when I re-use this class ItemsView. Problem: when i use MyVar inside MySerializer it says "MyVar" is not definde class ItemsView(OtherClass): MyVar = 'any ...' class MySerializer(OneMoreClasse): class Meta: model = MyVar fields = '__all__' -
Python code only works after a change in print statement
So I am running into the weirdest problem right now... My code only works once. After that, I need to change a print statement within the code or it does not work anymore. I'm calling perform_city_actions_in_order from an outside class and from there, as you can see I am calling get_city_action_queue that should return a list of database objects. When it works, it then performs an action on the object and changes the status so it will not match the queries in get_city_action_queue anymore. But when a row in the database table is changed so that it should match the queries, get_city_action_queue does not return it anymore if I don't change a print statement within the code. Also, if I change a print statement within perform_city_actions_in_order it also works but only once. class CityHelper: def get_city_action_queue(city, actions_until_time=datetime.now()): queue = [] fields = city.resource_fields.all().filter(status="Under Construction", action_done_time__lte=actions_until_time) | city.resource_fields.all().filter(status="Upgrading") buildings = city.buildings.all().filter(status="Under Construction", action_done_time__lte=actions_until_time) | city.buildings.all().filter(status="Upgrading") queue.extend(fields) queue.extend(buildings) print("this needs to change between executions for the above code to work") return queue def perform_city_actions_in_order(city, actions_until_time=datetime.now()): print("city", city) queue = CityHelper.get_city_action_queue(city, actions_until_time) print("before", queue) queue.sort(key = lambda x:x.action_done_time) print("after", queue) for action in queue: print("perfofming ", action) if(action.__class__.__name__ == "ResourceFieldModel"): ResourceHelper.upgradeResourceField(action) elif(action.__class__.__name__ == … -
How can I color a title in django's sqlite database?
When I add a new card I would like that every time I can choose the title color. This is my code: from django.db import models #Create your models here. class Aziende(models.Model): immagine = models.ImageField() nome = models.CharField(max_length=250) prezzo = models.FloatField() descrizione = models.CharField(max_length=250) def __str__(self): return self.nome How can I do? Thanks in advance! -
how can create letsencrypt ssl using python in own hosting
we want to create an automatic free letsencrypt ssl using python. I want a ssl provider in own hosting. own hosting framework: Django os: ubuntu -
Django no spaces between letters in textfield
So I am trying to create a guitar website and here, spaces are very important between letters as different chords are played at different times, so when I entered all my information from the admin panel in the textfield of my Songs model I entered all the spaces correctly, but when the song is being rendered all those spaces are gone, and all the chords are written one after another. What can I do to fix this? My admin panel: My website: My models.py: class Songs(models.Model): title = models.CharField(max_length = 100) lyrics = models.TextField() author = models.CharField(max_length = 100) favorited_by = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='favorite_songs' ) track_image = models.CharField(max_length=2083) def __str__(self): return self.title def get_absolute_url(self): return reverse('/', kwargs={'pk': self.pk}) -
Celery task not waiting for database updates
Can someone explain why I can't get the updated database records in the Celery task_success signal? #consumers.py @database_sync_to_async def save_to_db(game) Result.objects.create(game=game) class GameConsumer(AsyncWebsocketConsumer): ... async def save_result(self, event): await save_to_db(self.game) #tasks.py @shared_task(name="run_game") def run_game(): ... async_to_sync(channel_layer.group_send)( 'game', { 'type': 'save.result' } ) return(game) @task_success.connect def task_success_handler(sender=run_game, result=None, **kwargs): game_results = Game.objects.get(id=result.id).results.all() async_to_sync(channel_layer.group_send)( 'game', { 'type': 'end.game', 'data': game_results }