Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 } -
How to resolve django rest framework login issue
I want to login a user but i don't know what is happening. Anytime i create a new user it shows that the user has been saved but anytime i try to authenticate the user with the django authenticate method i keep getting that the user has provided invalid credentials here is my LoginAPIView. class LoginView(GenericAPIView): serializer_class = LoginSerializer def get(self, request, format=None): return Response() def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) here is my login serializer. class LoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(max_length=255, min_length=4) password = serializers.CharField(max_length=68, min_length=6, write_only=True) username = serializers.CharField(max_length=255, min_length=3, read_only=True) tokens = serializers.CharField(max_length=255, min_length=3, read_only=True) # def get_tokens(self, obj): # user = User.objects.get(email=obj['email']) # return { # "refresh": user.tokens()['refresh'], # "access": user.tokens()['access'] # } class Meta: model = User fields = ["email", "password", "username", "tokens"] def validate(self, attrs): email = attrs.get("email", "") password = attrs.get("password", "") user = auth.authenticate(email=email, password=password) if not user: raise AuthenticationFailed("Invalid credentials, try again") if not user.is_active: raise AuthenticationFailed("Your account is disabled contact admin") if not user.is_verified: raise AuthenticationFailed("Your account is not verified") return { "email": user.email, "username": user.username, "tokens": user.tokens() } return super().validate(attrs) What do i do? -
How t return a json response in GET request?
Looking for some help as i am new to python and django ,I am trying to return a response in JSON of an API GET request as the data is to be returned is dictionary made from different instances of different model. but few things are not getting converted in JSON like datetime amount in decimal throwing an error saying not serializable.Also how can i get all the transfer for that perticular order in a list and each instance in a dictionary like[{},{}] views.py @api_view(['GET']) def details(request,id): if request.method=='GET': order = get_object_or_404(Orders,id=id,applications=application) collection = get_object_or_404(Payments,orders=id,direction='COLLECTION',is_active=True) transfer = get_object_or_404(Payments,orders=order,direction='TRANSEFER',is_active=True) content = { 'orders': { "id":id, "purpose_code":order.purpose_code, "amount":order.amount, 'collection_payments':{ "id":collection_payments.id, "amount":collection_payments.amount, "datetime":collection_payments.datetime, 'transfer': [ { "id":transfer.id, "amount":transfer.amount, "datetime":transfer.datetime, } ] } } } return Response(content, status=status.HTTP_200_OK) models.py class Orders(models.Model): id= models.AutoField(primary_key=True) applications = models.ForeignKey(Applications, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=19, decimal_places=4) class Payments(models.Model): id = models.AutoField(primary_key=True) orders = models.ForeignKey(Orders, on_delete=models.CASCADE) direction = models.CharField(max_length=20,choices=[('COLLECTION','COLLECTION'), ('TRANSFER','TRANSFER')]) amount = models.DecimalField(max_digits=19, decimal_places=4, verbose_name='Price in INR') datetime = models.DateTimeField(auto_now=False,auto_now_add=False) is_active = models.BooleanField(default=True) -
How to store taken date input in SQlite3 database in Django?
I have a sqlite3 database table with a Datefield, the format of the date trying to store is 2012-01-01, though it's not storing the date and returning None when I am showing the table information in the template, what is the best method to fix this? -
How to extract a method from Django HTML?
My website (built with django) has pagination to not have to load too much content at once. The buttons to jump between the pages should always look the same. I found the following code on the internet which works great: {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% if page_obj.has_next %} <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a> {% endif %} {% endif %} Unfortunately I have to put this in each of my HTML files and have duplicated code. Is there a way to extract these few lines somewhere else and then only link to them in the respective HTML files? -
Django session not available on different view
Description: I can't access a session cookie set in one view from another one: views.py class Login(APIView): def post(self, request): request.session["user"] = "admin" print(request.session.get("user")) #outputs 'admin' return Response() class Files(APIView): def get(self, request): print(request.session.get("user") #outputs None return Response() How can I make session cookies available between requests? -
update object with pre_save signal subquery django
i need to display previous balance of users , i have used pre save signal to assign to the old balance before the transaction happens class Payment(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) client_seller = models.ForeignKey(ClientSeller,on_delete=models.CASCADE,blank=True) type_of_payment = models.CharField(choices=type_of_payment,max_length=60,default=retrieve) price = models.DecimalField(max_digits=20,decimal_places=2) previous_balance = models.DecimalField(max_digits=20,decimal_places=3,blank=True,default=0) class ClientSeller(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=40,unique=True) balance = models.DecimalField(decimal_places=3,max_digits=30,default=0) i need to assign previous_balance in Payment to balance in ClientSeller , balance in ClientSeller i change every time , but i need to show the users what was previous balance when a transaction happens def pre_save_balance(sender,instance,*args,**kwargs): if not instance.pk: Payment.objects.update( previous_balance = Subquery( Payment.objects.filter(client_seller__name=instance.client_seller.name).annotate( pre_balance=F('client_seller__balance') ).values('pre_balance')[:1] ) ) pre_save.connect(pre_save_balance,sender=Payment) but it only show the default previous_balance value which is 0 !? is there something i have missed ? or not understanding in pre_save signal good ?! thank you for helping