Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to handle authentication in django for multiple apps and functionality
I know authentication should be global. all apps in a django project should serve the same purpose, but I am in a situation where I need to restrict some parts of the app to some users. I have a screen that allows you to access different app functionality .i.e personal spending to-do list e-mail scheduler/ report scheduler users should be able to see all apps, click on them, log in and then access different functionalities based on who they are. the views should also be different when they're an admin or just a simple user. how can this be achieved in django? is it with groups ? -
How to fix gettext() got an unexpected keyword argument 'null' in Django
I have a model, a serializer, and a view like below, model # get user model User = get_user_model() class Task(models.Model): "A task can be created by the user to save the task's details" COLOR_CHOICES = ( ("red", _("Red")), ("gre", _("Green")), ("blu", _("Blue")), ("yel", _("Yellow")), ("pur", _("Purple")), ("ora", _("Orange")), ("bla", _("Black")), ("whi", _("White")), ("ind", _("Indigo")), ("lim", _("Lime")), ("cya", _("Cyan")), ) title = models.CharField(max_length=150, blank=False, null=False, help_text=_("Enter your task's title"), verbose_name=_("title")) description = models.TextField(max_length=500, blank=True, null=True, help_text=_("Enter your task's description"), verbose_name=_("description")) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="utask", verbose_name=_("User")) time_to_start = models.DateTimeField(verbose_name=_("The time that the task should be started"), help_text=_("Enter the time that you want to start your task")) deadline = models.DateTimeField(verbose_name=_("The time that the task should be done"), help_text=_("Enter the time that you'll have done your task until it")) priority = models.IntegerField(choices=[(0, _("Not important")), (1, _("Low")), (2, _("Medium")), (3, _("High"))], default=1, verbose_name=_("Priority"), help_text=_("Choose the priority of your task")) color = models.CharField(max_length=3, choices=COLOR_CHOICES, default="whi", blank=True, null=True, verbose_name=_("Color"), help_text=_("Choose the color or the theme of your task")) notification = models.BooleanField(default=True, null=False, blank=True, verbose_name=_("Notification"), help_text=_("Do you want to receive a notification when the task is getting closer to the deadline or when it's passed that?")) def __str__(self): return self.title class Plan(models.Model): "A plan is a … -
NOT NULL constraint failed: posts_subscribe.firstname
I am trying to retrieve data from a form using the Post method and store it in the database. However, when I click on the submit button, I keep on getting the following error: NOT NULL constraint failed: posts_subscribe.firstname Here is my views.py def subscribe(request): if request.method == 'POST': firstname=request.POST.get('firstname') secondname=request.POST.get('secondname') email=request.POST.get('email') phonenumber=request.POST.get('phonenumber') en= Subscribe(firstname=firstname, secondname=secondname, email = email, phonenumber = phonenumber) en.save() return redirect('/') return render(request, 'subscribe.html') My models.py class Subscribe(models.Model): firstname = models.CharField(max_length=30, blank = True) secondname = models.CharField(max_length=30, blank = True) email = models.CharField(max_length=30) phonenumber = models.IntegerField() Here is my template {% extends 'index.html' %} {% block subscribe %} <div class="card mx-5"> <h1 class="mx-5 mt-3"> Subscribe</h1> <form method="POST" enctype="multipart/form-data" action="subscribe"> {% csrf_token %} <div class="mb-3 mx-5"> <label for="firstname" class="form-label ">First Name</label> <input type="text" class="form-control form-control-lg" id="firstname" placeholder="firstname"> </div> <div class="mb-3 mx-5"> <label for="secondname" class="form-label">Second Name (Optional)</label> <input type="text" class="form-control form-control-lg" id="secondname" placeholder="secondname"> </div> <div class="mb-3 mx-5"> <label for="email" class="form-label">Email</label> <input type="email" class="form-control form-control-lg" id="email" placeholder="example@example.com"> </div> <div class="mb-3 mx-5"> <label for="phonenumber" class="form-label">Phonenumber</label> <input type="number" class="form-control form-control-lg" id="phonenumber" placeholder="0712345678"> </div> <div class="mb-3 mx-5"> <button type="submit" class="btn-primary"> Subscribe</button> </div> </form> </div> {% endblock %} And my url patterns urlpatterns= [ path('', views.index, name='index'), path('subscribe', views.subscribe, name ='subscribe'), path('allposts', views.allposts, … -
Django 4.x - Conditional order_by of a QuerySet
The Objective The objective is to conditionally order a QuerySet by one of three different date fields in the view based on another field in the model. Since conditional ordering cannot be accomplished with Class Meta I am exploring accomplishing this objective in the view. Here is the relevant excerpt from models.py: READING_PROGRESS = [ ('---', '---'), ('1) On Reading List', '1) On Reading List'), ('2) Reading In Progress', '2) Reading In Progress'), ('3) Completed Reading', '3) Completed Reading'), ] class ReadingProgress(models.Model): record = models.ForeignKey( LibraryRecord, related_name='record_in_reading_progress', on_delete=models.CASCADE, null=True, blank=True, verbose_name='Library record' ) user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True ) reading_progress = models.CharField( max_length=30, choices=READING_PROGRESS, default='---' ) date_added = models.DateField( auto_now=False, auto_now_add=False, null=True, blank=True, ) date_started = models.DateField( auto_now=False, auto_now_add=False, null=True, blank=True, ) date_completed = models.DateField( auto_now=False, auto_now_add=False, null=True, blank=True, ) class Meta: ordering = [ 'reading_progress', ] verbose_name_plural = 'Reading Progress' unique_together = ('record', 'user',) # Record metadata date_created = models.DateTimeField( auto_now_add=True ) def __str__(self): return f'{self.record.title} - {self.reading_progress}' The relevant fields in the model are: reading_progress date_added date_started date_completed Each date field corresponds to a status value. I want to be able to order_by the QuerySet in the view by the field reading_progress: When reading_progress == '1) … -
Make json from audiofile by python for waveform
I changed wave/mp3 to json with this program. https://github.com/bbc/audiowaveform audiowaveform -i test.mp3 -o test.json This json works for showing the audioform. this json is like this , list of numbers, something like sampling...?? {"version":2,"channels":1,"sample_rate":44100,"samples_per_pixel":256,"bits":16,"length":5090,"data":[-20873,7262,-18598,26482,-13960,24194,-23076,3223,-12630,9770,-5839,17146,-3843,15499,-18422,3016,-14348,10706,-5625,13476,-8492,6077,-7876,7949,-8651,11759,-5424,9001,-9093,13121,-7641,9079,-10181,9877,-9001,4323,-5322,12272,-10333,9653,-10368,8790,-10793,6460,-9629,10254,-4771,9144,-8782,5503,-5752,8029,-9959,5774,-7144,8220,-11004,7199,-9145,7306,-5096,8332,-9930,3956,-5333,8168,-7351,7254,-7515,7378,-9147,10247,-8226,5130,-4069,9229,-6821,4259,-3569,8908,-11316,7191,-11041,14220,-8429,12541,-11705,14970,-9908,13398,-12572,10855,-10676,13266,-8604,6577,-8318,8095,-13359,12057,-9709,7556,-6081,8561,-8062,5234,-4988,6821,-7739,7500,-9188,8139,-2619,7234,-7794,6233,-4604,8059,-7197,4767,-7006,8878,-5750,5308,-5475,4398,-6693,94..... Now I want to do the equivalent thing in django/python. Is there any good method or library?? -
Getting the original language or original text of date in Excel file
I have a Django application where I give users a Excel file for them to give me dates, i ask them to give me the date in DD/MM/YYYY format (the one used in Latin America) The problem is that if the language of the Excel file is in English, it uses the MM/DD/YYYY format. So for example if they write 01/05/2022, when i open the file in my application i receive 05/01/2022. So I want to know if there is a way to get the original language of the excel file, for me to put some conditions inside my application, or if i can get the original raw text of the file. I can't change the format that the application uses (because I receive excel files that are mainly in the spanish language) or ask my clients to write the dates in a different format, or ask them to change the language of the file. I am open for other type of solutions too. -
Django: How to show a PointField in a map from a html template?
I have a Django class in my models.py, similar to the following: class MyClass(Model): .... description = TextField() location = PointField() In my views.py: template = loader.get_template('my_class.html') context = { 'my_class': MyClass.objects.filter(....), } return HttpResponse(template.render(context, request)) Finally, from my my_class.html template I can easily print each of the properties in my MyClass object: {{ my_class.description }} But {{ my_class.location}} just prints something like POINT (-13.716858926262476 50.42083468131796). Is there an easy way to show the point in an OpenStreetMap map? (Similar to the map in the admin page when using OSMGeoAdmin) Do I need to create a form for that if this template is read-only? (I dont need to edit any of the fields) (I'm using Django 3.2 in case that is important) -
ModuleNotFoundError: No module named 'I4G022709FMQ'
i am working on a django project and this error pops up when i run python manage.py runserver i've tried the solutions of some related questions but they arent working. 'I4G022709FMQ' is the name of my project in which i installed django with startapp command created blog app. the first part of the error message when i ran manage.py the end part of the error message -
Password reset timeout djoser jwt
In django default authentication system there's an option called PASSWORD_RESET_TIMEOUT Which expiers the reset password link after a specific time. I have an authentication system based on djoser and simplejwt I wanted to know if there is an option like django's PASSWORD_RESET_TIMEOUT in djoser. And if there is, how should i declare that in my code? -
Django Validation Check Positive value Python
I am working this validation check in django , i have to check postiva values. I have values a,b,c,d if (a,b) also (c,d) positive value will not allowed, i wrote the code this way but do not know why is not checking the validation. I am working on django forms.py for i in range(count): a = int(self.data.get(f'runtime_set-{i}-a') or 0) b = int(self.data.get(f'runtime_set-{i}-b') or 0) c = int(self.data.get(f'runtime_set-{i}-c') or 0) d = int(self.data.get(f'runtime_set-{i}-d') or 0) if a ==b==c==d==0: continue if (a + b) > 0 and (c + d) > 0: raise ValidationError( "When A ,B is postive then positive C,D value is not allowed ") -
sitemap.xml <loc>https://example.com/?val1=1&val2=1</loc>
i did follow Django Sitemap Tutorial to create a sitemap.xml with GenericSitemap. That work good for Blog, But i need to add more links like: https://example.com/?author=NAME&taq=TAQ&Category=category and add link only if there is result for all 3 parameters author taq category models.py class Main_Category(models.Model): name = models.CharField(max_length=200, verbose_name=_("Main_Category")) class Tag(models.Model): name = models.CharField(max_length=200, verbose_name=_("Tag")) class Category(models.Model): name = models.CharField(max_length=200, verbose_name=_("Category")) Main_Category = models.ForeignKey(Main_Category, on_delete=models.CASCADE, null=True, blank=True) class Blog(models.Model): title = models.CharField() author = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE) main_Category = models.ForeignKey(Main_Category, on_delete=models.CASCADE) taq = models.ForeignKey(Tag, on_delete=models.CASCADE, null=True, blank=True) -
Django "after_db_save" signal
The post_save signal according to the documentation is "sent at the end of the save() method." but not after it. The Scenario Model A 's post_save signal is being used to call another service which creates a Model B whose field a_id is a foreign key to model A. But the service is getting a error stating that the PK of Model A does not exist. So is there a django signal which is triggered after the instance is saved in the database? If no, how should I implement this functionality? I've read about using transaction.on_commit() but how would I use it inside the signal? -
DJANGO REST web login not working with JWT if permission set to IsAuthenticated
The rest framework has its default web-based API-authentication path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), However, once JWT authentication is added and the permission is set to IsAuthenticated, you can no longer use the default or built-in API authentication. HTTP 401 Unauthorized Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Bearer realm="api" { "detail": "Authentication credentials were not provided." } I tried logging in but it still prompted me with the error message above. Currently, I am building my project with no front end or client, just the API. So the default or templates provided by Django Rest Framework and Django itself is what I am currently using Is there a way to solve this one? I know you have to attach the access token with your login credentials, so how can you do this with the default authentication of rest? Also when you add the following code the problem above can be solved. However, I do not know if this is the proper way to solve it. 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', Screenshots for context: Django Rest Framework with Login (indicating I am not logged yet) Django Rest Default or built-in login page -
displaying image from backend but whole image not display it only showing me quadrilateral blank why
static (settings.MEDIA_URL, document_rot=settings.MEDIA_ROOT) MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR/'media' {% for b in bottomwears %} {{b.title}}Rs. 500 {% endfor %} -
Reset autoincrement for id field after deleting all records django
How do I reset autoincrement for id(default field for models in django) after deleting all records in django? -
Must include AWSEBDockerrunVersion key in the Dockerrun.aws.json file
Trying to move my Docker Compose application to Elastic Beanstalk and having some issues. Been struggling with this for like a week now, come pretty far but still some big issues. I converted my docker-compose.yml to a Dockerrun.aws.json using container transform: { "AWSEBDockerrunVersion": 2, "containerDefinitions": [ { "entryPoint": [ "/client/entrypoint.sh" ], "essential": true, "memory": 512, "image": "danielnazarian/dans-backend:client", "links": [ "server_dans_backend:server_dans_backend" ], "mountPoints": [ { "containerPath": "/client", "sourceVolume": "_Client" }, { "containerPath": "/var/run/docker.sock", "sourceVolume": "VarRunDocker_Sock" }, { "containerPath": "/client/node_modules", "sourceVolume": "Node-Modules" } ], "name": "client_dans_backend", "portMappings": [ { "containerPort": 3000, "hostPort": 3000 } ] }, { "environment": [ { "name": "POSTGRES_DB", "value": "ABC" }, { "name": "POSTGRES_USER", "value": "ABC" }, { "name": "POSTGRES_PASSWORD", "value": "ABC" }, { "name": "POSTGRES_HOST", "value": "ABC" } ], "essential": true, "image": "postgres:14-alpine", "memory": 512, "mountPoints": [ { "containerPath": "/docker-entrypoint-initdb.d/dump.sql", "sourceVolume": "_ServerDump_Sql" } ], "name": "db_dans_backend", "portMappings": [ { "containerPort": 5432, "hostPort": 5432 } ] }, { "essential": true, "image": "danielnazarian/dans-backend:nginx", "memory": 512, "links": [ "server_dans_backend", "client_dans_backend" ], "mountPoints": [ { "containerPath": "/app/server/static", "sourceVolume": "Static" }, { "containerPath": "/app/server/static-debug", "sourceVolume": "Static-Debug" } ], "name": "nginx_dans_backend", "portMappings": [ { "containerPort": 80, "hostPort": 80 } ] }, { "entryPoint": [ "/app/server/entrypoint.sh" ], "essential": true, "image": "danielnazarian/dans-backend:server", "memory": 512, "links": … -
How to show validation errors in template using CreateView Django
I am using an extended User model and a generic CreateView. class SignUp(CreateView): form_class = forms.SignUpForm success_url = '/accounts/login/' template_name = 'accounts/signup.html' How do I access the form validation errors in my template? They must be there because when I do {{ form.as_p }} the errors show up. I have tried {{ form.errors }} and {{ field.errors }} but there is nothing in them. Is there a simple tag I can call in my template to show the errors? Thanks. -
Add pre-filled resizable text boxes (forms.Textarea) to the django form
I need to create a form, where text-boxes would be resizable (so Textarea widget has to be used) and pre-filled. I tried to pre-fill them through .initial and value attribute. Problem: If Textarea widget is used: text boxes are resizable but no value is shown forms.CharField(label='', widget=forms.Textarea(attrs={"rows": 1, "cols": 50, "value":column_data}) self.fields[f'inserted_value_{column_name}'].initial=column_data If TextInput widget is used: text boxes are not resizable but value is shown forms.CharField(label='', widget=forms.TextInput(attrs={"rows": 1, "cols": 50, "value":column_data}) There amount of form elements (always the same Text-box) is going to be dynamic, so they are created in def __init__ and should also get their value there. Theoretically value attribute should work, but it returns me empty text-boxes. -
Changing form action based on select option value
I am trying to change the form url_for action based on the selected option: Django template: <form name="List_select" id="List_select" method ="POST"> <div class="modal-body"> <label>Move Item</label> <select class="form-control" id="Lists"> <option value="{{ url_for('complete_item', titleID = item.id) }}">Move to Done</option> <option value="{{ url_for('doing_item', titleID = item.id) }}">Move to Doing</option> <option value="{{ url_for('revert_item', titleID = item.id) }}">Move to To Do</option> </select> <input class="btn btn-primary" type="submit" value="Move"> </div> JQuery $(function() { $(".Lists").change(function(){ value = $(this).val() $('.List_select').attr('action', value) }) }); When I try select an option and press the Move button, however I get: Method Not Allowed The method is not allowed for the requested URL. -
Quick fix: Flipping the side on which DMs are displayed on a social media platform
Within the DM function on my social media platform I would like the received messages to appear on the left hand side and the sent messages to appear on the right hand side. Currently it is the other way round. (Sent messages (light pink) = #D7A5EB, received messages (dark pink) = #CC64C3) Ì have been trial-and-erroring this for a while now, but it simply refuses to allow sent messages (I.e. the ones that the currently logged-in user sent) on the right hand side. thread.html: {% extends 'landing/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <div class="row"> <div class="card col-md-12 mt-5 p-3 shadow-sm"> {% if thread.receiver == request.user %} <h5><a href="{% url 'profile' thread.user.profile.pk %}"><img class="rounded-circle post-img" height="50" width="50" src="{{ thread.user.profile.picture.url }}" /></a> @{{ thread.user }}</h5> {% else %} <h5>@{{ thread.receiver }}</h5> {% endif %} </div> </div> {% if message_list.all.count == 0 %} <div class="row my-5"> <div class="col-md-12"> <p class="empty-text">No messages yet.</p> </div> </div> {% endif %} {% for message in message_list %} <div class="row"> {% if message.sender_user == request.user %} <div class="col-md-12 my-1"> {% if message.image %} <div class="message-sender-container ms-auto"> <img src="{{ message.image.url }}" class="message-image" /> </div> {% endif %} <div class="sent-message my-3"> <p>{{ message.body }}</p> … -
Drop a table in django with id
I need to drop a table in django using a model in code. After dropping a table, id of each record should start from 1. Is it possible? -
I'm stumped trying to figure out how to get the sum of all active and inactive investment balances using Django
I am trying to query "locked_total_balance" locked_total_balance = Investment.objects.filter(is_active=True).aggregate( total_balance=Sum('balance')) and "total_available_balance" total_available_balance = Investment.objects.filter(is_active=False).aggregate( total_balance=Sum('balance')) but its not working. Here is my model class Investment(models.Model): PLAN_CHOICES = ( ("Basic - Daily 2% for 180 Days", "Basic - Daily 2% for 180 Days"), ("Premium - Daily 4% for 360 Days", "Premium - Daily 4% for 360 Days"), ) user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True) plan = models.CharField(max_length=100, choices=PLAN_CHOICES, null=True) deposit_amount = models.IntegerField(default=0, null=True) basic_interest = models.IntegerField(default=0, null=True) premium_interest = models.IntegerField(default=0, null=True) investment_return = models.IntegerField(default=0, null=True) withdraw_amount = models.IntegerField(default=0, null=True, blank=True) balance = models.IntegerField(default=0, null=True, blank=True) locked_balance = models.IntegerField(default=0, null=True, blank=True) investment_id = models.CharField(max_length=10, null=True, blank=True) is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=True, null=True) due_date = models.DateTimeField(null=True) def __str__(self): return str(self.investment_id) -
Nginx exits with 127 status code, but before prints out: /bin/sh: python: not found
I'm building a web application with python, nginx and gunicorn. And docker-compose build command works fine, but when I run a built image as a container, I'm getting the next output: root@ubuntuos:/home/eliot/Documents/development/python/projects/BarAPI/JustPub# docker-compose up Creating network "justpub_default" with the default driver Creating justpub_db_1 ... done Creating justpub_web_1 ... done Creating justpub_nginx_1 ... done Attaching to justpub_db_1, justpub_web_1, justpub_nginx_1 nginx_1 | /bin/sh: python: not found db_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | db_1 | 2022-06-19 14:08:35.192 UTC [1] LOG: starting PostgreSQL 13.0 on x86_64-pc-linux-musl, compiled by gcc (Alpine 9.3.0) 9.3.0, 64-bit db_1 | 2022-06-19 14:08:35.192 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2022-06-19 14:08:35.192 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2022-06-19 14:08:35.196 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2022-06-19 14:08:35.200 UTC [22] LOG: database system was shut down at 2022-06-19 14:08:26 UTC db_1 | 2022-06-19 14:08:35.204 UTC [1] LOG: database system is ready to accept connections justpub_nginx_1 exited with code 127 web_1 | [2022-06-19 14:08:36 +0000] [1] [INFO] Starting gunicorn 20.1.0 web_1 | [2022-06-19 14:08:36 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) web_1 | [2022-06-19 14:08:36 +0000] … -
ValueError: Field 'id' expected a number but got 'update_Item'. Cart Javascript in django
I can't post my prodcutid, please helping me. And sometime my Javascrip can't update, I had alredy saved my javascrip code but in the my brower javascrip does not changed. Please help me to solve my probelm, I am newbiew in here, Thanks cart.js var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId :', productId ,'Action:', action) console.log('USER:', user) if (user == 'AnonymousUser'){ addCookieItem(productId, action) }else{ updateUserOrder(productId, action) } }) } function addCookieItem(productId, action){ console.log("Not logged in ...") if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 } } if (action == 'remove'){ cart[productId]['quantity'] -= 1 if (cart[productId]['quantity'] <= 0 ){ console.log('Remove Item') delete cart[productId] } } console.log('Cart:', cart) document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/" location.reload() } function updateUserOrder(productId, action){ console.log('User is logged in, sending data...') console.log('productIdCart:', productId) console.log('Action:', action) console.log('Cart:', cart) var url = 'update_Item' fetch(url, { method :'POST', headers : { 'Content-Type' : 'application/json', 'X-CSRFToken' : csrftoken, }, body:JSON.stringify({'productId': productId, 'action': action}) }) .then((response) =>{ return response.json(); }) .then((data) =>{ console.log('data:',data); // window.location.reload(data); location.reload() }); } prduk.html <button data-product="{{product.id}}" data-action="add" class="btn update-cart btntdt" style="padding-left:-20xp" >Tambah</button> Error … -
Can't get the picture to show in django
<img class="img-fluid" alt="Responsive image" src="{% static 'product.image.url' %}" /> Cant get the picture to show on the web page.