Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django popup error message on same email submit
am wondering how i can get a popup message to tell the user this email is already registerd. I got this in my models.py and the unique=True is blocking same email signup all i need is some code to let the user know it already signed up how can i do this? models.py from django.db import models class Subscriber(models.Model): email = models.EmailField(max_length=255, unique=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s' % self.email -
Adjust number of fields of the form based on the argument in the view
I have a form with 4 fields. class data_collect_form(forms.Form): data_entry1 = forms.IntegerField(widget = forms.NumberInput(attrs={"class":"form-control","initial":0})) data_entry2 = forms.IntegerField(widget = forms.NumberInput(attrs={"class":"form-control","initial":0}) data_entry3 = forms.IntegerField(widget = forms.NumberInput(attrs={"class":"form-control","initial":0}) data_entry4 = forms.IntegerField(widget = forms.NumberInput(attrs={"class":"form-control","initial":0})) Based on the argument "number_of_fields" in the view, I would like to delete last fields of this form. Here is the view: def add_submission(request, number_of_fields ): #delete number of fields according to number_of_fields argument if request.method == 'POST': form2 = data_collect_form(request.POST) else: form2 = data_collect_form() return render(request, 'main/second.html',{"form2":form2) I am sure it should be possible with the __init__ method, but I do not have understanding on writing it correctly. -
i have a proplem with django python
comments = project.masarif.filter(active=True) def sub_masarif(): for sub in comments: total = 0 xdd = sub.count total += (xdd) print(total) # 3 4 69 i need sum total < example print(total) # 76 -
Django Rest API login using multiple password
I have one type of login idea, One single User has multiple Accounts (OneToOne or Foreign Key). To save UserEmail I use the default User table. UserID is PrimaryKey on the User table. In the Account table, Account__UserID is ForeignKey assigned to the User table. Now Account table AccountID PrimaryKey is assigned as ForeignKey for other tables(e.g: Transaction table have Transaction ID, AccountID, TransactionAmount. In Transaction table AccountID ForeignKey of Account table). When the user login by using the User table UserPassword. The user gets a list of Account table data. Account table PrimaryKey AccountID as ForeignKey for Transaction table, so users now get List Account & List Transaction data (It's default login method). When the user login by using the Account table AccountPassword. The user gets only one Account data. so now user get only one Account & List Transaction data (Account-based login) Now I did the default login method, it's an easy one. My question is, how I can do Account-based login. -
How to integrate Django API with XMPP server (ejabberd)
I'm currently working on a project where I'm using Django rest framework (DRF) for the backend. I need to implement one to one chat on this application. For this, I'm using XMPP server. I'm using ejabberd as XMPP server. Now, I need to create users in the ejabberd server using my API built with DRF. I need to achieve following things with my API: create new users in the ejabberd server create rooms in the ejabberd server fetch all the available rooms. The username will be fetched or retrived from the frontend. Is there any Python API client or Django API client to do this in the ejabberd server? Like how there is simple-xmpp for node js I have seen many python packages for this. some of them are, pyjabberd xmppy django-xmpp I'm not sure which one to use and I don't know whether is it possible to implement the above using any of these packages. -
Starting RabbitMQ and Celery for Django when launching Amazon Linux 2 instance on Elastic Beanstalk
I have been trying to setup celery to run tasks for my Django application on Amazon Linux 2. Everything worked on AL1, but things have changed. When I SSH into the instance I can get everything running properly - however the commands upon deployment do not work properly. I have tried this in my .platform/hooks/postdeploy directory: How to upgrade Django Celery App from Elastic Beanstalk Amazon Linux 1 to Amazon Linux 2 However that is not seeming to work. I have container commands to install epel, erlang and rabbitmq as the broker - they seem to work. After that answer, @Jota suggests: "No, ideally it should go in the Procfile file in the root of your repository. Just write celery_worker: celery worker -A my_django_app.settings.celery.app --concurrency=1 --loglevel=INFO -n worker.%%h. Super simple." However would I include the entire script in the procfile or just the line: celery_worker: celery worker -A my_django_app.settings.celery.app --concurrency=1 --loglevel=INFO -n worker.%%h This seems to suggests it would just be the command: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-linux-extend.html Then where would the script be if not in the procfile with the above line? -
Disabling a crispy form field from showing errors
I have a form to perform searching. As I am using the primary key to search, The searching process is completed successfully BUT I used to get an error below the text field saying Invoice number already exists. I did some tweaks and stopped the form from showing errors but the text field still has a red outline whenever I perform the searching operation. How can I stop the form from doing that? The code in the forms.py that disabled the form to show field errors: class InvoiceSearchForm(forms.ModelForm): generate_invoice = forms.BooleanField(required=False) class Meta: model = Invoice fields = ['invoice_number', 'name','generate_invoice'] def __init__(self, *args, **kwargs): super(InvoiceSearchForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_show_errors = False self.helper.error_text_inline = False self.form_error_title=False The HTML code that deals with the search operation: <div class="myForm"> <form method='POST' action=''>{% csrf_token %} <div class="row"> <div class='col-sm-12'> <div class="form-row"> <div class="form-group col-md-3"> {{ form.invoice_number|as_crispy_field }} </div> <div class="form-group col-md-3"> {{ form.name|as_crispy_field }} </div> <div class="form-group col-md-3"> {{ form.generate_invoice|as_crispy_field }} </div> <div class="form-group col-md-3"> <br> <button type="submit" class="btn btn-primary">Search</button> </div> </div> </div> </div> </form> </div> The views.py related to the search operation: @login_required def list_invoice(request): title = 'List of Invoices' queryset = Invoice.objects.all() form = InvoiceSearchForm(request.POST or None) context = { … -
How to set the fetched value of dropdown to dropdown in edit module?
Here is the photo of dropdown where I want to fetch the data from database : - https://drive.google.com/file/d/1ko15oCmKSuOiCmkFq1v0INDGgk70EzF6/view?usp=sharing html page : - <label>Country</label> <select id="countryId"> <option value="{{vr.country}}" >Select Country</option> </select> <label>State</label> <select id="stateId"> <option value="{{vr.state}}">Select State</option> </select> <label>City</label> <select id="cityId"> <option value="{{vr.city}}">Select City</option> </select> I've done this so far to fetch the records from database but i'm not geeting the values in to the dropdown list. Also, I'm geeting all the other values correctly but not getting the value in dropdown only. So, what should I do to set default selected value in dropdown? (if anyone wants more details please comment after this post.) -
{% if user.is_authenticated %} Always return true
I am just trying to run a simple {% if user.is_authenticated %}. But it always returns true. what I want to do is to check if the user is logged in. if yes the Dashboard button should appear and if not the Register button should appear. Can you help me here! Here are my files: vews.py : from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages # Create your views here. def login(request): return render(request, 'authorisation/login.html', {}) def register(request): if request.method == 'POST': email = request.POST['email'].replace('', '').lower() password1 = request.POST['password1'] password2 = request.POST['password2'] if not password1 == password2: messages.error(request, "Passwords doesn't match") return redirect('register') if User.objects.filter(email=email).exists(): messages.error( request, "A user with the email address : {} already exists, please use a different email".format(email)) return redirect('register') newUser = User.objects.create_user( email=email, username=email, password=password2) newUser.save() auth.login(request, newUser) return redirect('home') return render(request, 'authorisation/register.html', {}) My HTML page : {% if user.is_authenticated %} <li class="nav-item"> <a class="btn btn-primary ml-lg-2" href="#">Dashboard</a> </li> {% else %} <li class="nav-item"> <a class="btn btn-primary ml-lg-2" href="{% url 'register' %}">Register</a> </li> {% endif %} It always returning The Dashboard -
How to use Bengali date in django
In Django Framework how to use Bengali months date. Bengali Month Like Baishak, Joishto etc.Someone help me. I know how to use local time. -
Setting the variable with the form and its zeroing after a few hours
I have created an app using Django, I have a variable that I set using a form for more security. But after a few hours, I check its value and see that it is zero. Every time I set the value, after a while the value becomes zero I have published this app on the host -
Multidimensional dictionary losing lower levels after for loop in the django template
I have a dictionary of players and their inventory. There is a lower level dictionary for each item with the needed values. On the template I would like to do a for loop through each item and get their dictionaries. I will give a simplified example which hopefully makes it clearer to understand. Please let me know if there is something unclear about my question or examples. views.py players = {} players[1] = {} players[1].update({ 'avatar': user.avatar, 'username': user.username, players[1]['items'] = {} players[1]['items'][item.id] = {} players[1]['items'][item.id].update({ 'item_name' = item.name, 'item_value' = item.value, }) }) template.html {% for item in players.1.items %} {{item}} <!-- Gives me item ids --> {{item.1.item_name}} <!-- I would expect that to give me the value of item_name, instead I get nothing --> {% endfor %} {{players.1.items.1.item_name}} <!-- This works as it gives me the result I am expecting --> -
django.db.utils.IntegrityError when sending post request with axios in vue
im new to web development so please explain your solution i am trying to send data to an endpoint in the api i created with the django rest framework in vue with axios but whenever i do i get this error : django.db.utils.IntegrityError: NOT NULL constraint failed: main_checkbox.label (i know im not building the api the way its supposed to be built but thats another problem) i can make a get request with axios no problem and i can even send post data via an html form with no problem (but i dont want to cause im creating a single page application with vue and don't want it to refresh when submitting) here is the vue code : <template> <div class="home"> <input type="text" name="label" id="" v-model="label" /> <input type="submit" value="Create" @click="createCheckbox" /> </div> </template> <script> import axios from "axios"; export default { data() { return { label: "", }; }, methods: { async createCheckbox() { let result = axios.post("http://127.0.0.1:8000/create/", { label: this.label, }); console.log(result); }, }, }; </script> the django views code : from rest_framework.response import Response from rest_framework.decorators import api_view from main.models import checkbox from main.serializers import checkboxSerializer @api_view(['POST']) def create(request): checkboxobj = checkbox.objects.create( state=False, label=request.POST.get('label')) serialized = checkboxSerializer(checkboxobj) … -
Django forms not passing form.is_valid() condition
In my views.py my have a view where a user can create a post with a title, media file and caption. When i check if form.is_valid(): it always returns as false and i cannot see the issue with my form. views.py def your_profile(request): if request.method == "POST": form = CreatePost(request.POST) if form.is_valid(): title = form.cleaned_data.get("title_input") media = form.cleaned_data.get("media_input") caption = form.cleaned_data.get("caption_input") context = {"title": "Your Profile"} return render(request, "myApp/your_profile.html", context) forms.py class CreatePost(forms.Form): title = forms.CharField(max_length=30) media = forms.FileField(max_length=350) caption =forms.CharField(max_length=300) html <form action="" method="post"> <input type="text" name="title_input" id="title_input"> <label for="title_input">Title</label> <input type="file" name="media_input" id="media_input"> <label for="media_input">Media</label> <input type="text" name="caption_input" id="caption_input"> <label for="caption_input">Caption</label> <input type="submit" value="POST!"> </form> -
Why createsupersuer not loggin without any error in Django?
I have made super user like this: python manage.py createsuperuser username: something email: something password: something i checked the database and is_superuser=True is_staff=True is_active=True run my project: python manage.py runserver and call this address: http://127.0.0.1:8000/admin When enter username and password not loggin and not show any red message as error in the page. I don't know get error or redirect to the page. -
Django startserver/make migaration is picking wrong username rather than mentioned in settings.py file
I am new to django,i am facing issue like below,there is no soorya user in mysql database,but still it giving error when i try to do makemigrations and runserver.. Here is the output of mysql server database user select user,host from mysql.user output: mysql.infoschema localhost mysql.session localhost mysql.sys localhost rest localhost root localhost ======================= FYI. I had created a new mysql connection(soorya) by this name and deleted it as i was facing issue with django connection with mysql can any body help me on this. C:\Users\soorya\AppData\Local\Programs\Python\Python310\Lib\site-packages\django\core\management\commands\makemigrations.py:121: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (1045, "Access denied for user 'soorya'@'localhost' (using password: YES)") warnings.warn( No changes detected -
Django models normalization
having a simple ordinary model like this class Order(models.Model): open = models.DecimalField(max_digits=10, decimal_places=8) high = models.DecimalField(max_digits=10, decimal_places=8) low = models.DecimalField(max_digits=10, decimal_places=8) close = models.DecimalField(max_digits=10, decimal_places=8) time = models.DateTimeField() active = models.BooleanField(default=False) complete = models.BooleanField(default=False) works for my case but as there's only up to 1 active order at the same time, keeping it consistent is a challenge. don't wanna use transaction so the idea of separating active attribute would be a solution. I wondered if there's any better idea? for example, adding active as a database related attribute or something like a hook (believe me when I say I don't know if that's an option) -
How could I rework Django migrations without affecting database?
Basically I'm working on a project which already has a database managed with Django. I have noticed there are issues from the past. Duplicate migrations(eg.: 0011_auto_20210524_1314, 0011_auto_20210531_1728.), also there aren't all model fields recorded in migration history. The idea is that I would like to even split project into more apps than it is for now. So what I exactly would like to do is to go back to migration zero, delete all migrations and makemigrations again meanwhile models will be split into multiple apps. The issue is that database is containing a lot data and I can't affect them. Anyone have an idea how to reach it somehow "clean"? I've been thinking about --fake zero, delete migrations(Delete also from DB.), make new set of migrations, set flag managed = False and migrate so the migration would be "applied". I'm aware of inspectdb, but not sure if that would help due to moving models across multiple apps. Any other suggestions or thoughts please? -
How to make model for sub-category and category for product in django?
I have to make product model in django where when we select the the main category which is foreign key then we have to select sub category, problem is that it will show the all sub category. it have to show the sub category as per main category selected Main Category Model Here we just have three fields class Category(models.Model): image = models.ImageField(upload_to="maincategory",null=True) icon = models.CharField(max_length=200,null=True) title = models.CharField(max_length=200,null=True) def __str__(self): return self.title Sub Category Model here we give the Main category as foreignkey class SubCategory(models.Model): main_category = models.ForeignKey(Category,on_delete=models.CASCADE) title = models.CharField(max_length=200,null=True) def __str__(self): return self.main_category.title + " - " + self.title Product Model In The Product model i will give two foreign key for main and sub category maincategory = models.ForeignKey(Category,on_delete=models.CASCADE,null=True,blank=True) subcategory = models.ForeignKey(SubCategory,on_delete=models.CASCADE,null=True,blank=True) class Product(models.Model): sts = ( ("PUBLISH","PUBLISH"), ("DRAFT","DRAFT"), ) vendor = models.ForeignKey(Vendor,on_delete=models.CASCADE) maincategory = models.ForeignKey(Category,on_delete=models.CASCADE,null=True,blank=True) subcategory = models.ForeignKey(SubCategory,on_delete=models.CASCADE,null=True,blank=True) title = models.CharField(max_length=200,null=True) description = models.TextField() price = models.IntegerField(null=True,default=0) discount = models.IntegerField(null=True,default=0) stock = models.IntegerField(null=True,default=0) size = models.CharField(max_length=200,null=True,blank=True) color = models.CharField(max_length=200,null=True,blank=True) date = models.DateTimeField(auto_now_add=True) slug = AutoSlugField(populate_from='title',unique=True,null=True,default=None) status = models.CharField(choices=sts,null=True) def __str__(self): return self.vendor + " - " + self.title So how to create model where select subcategory as per main category in admin panel django -
What model of raspberry pi good for local web server
Hello i need some useful information about running a local web server in a raspberry pi and the best embedded system that can handle my device what i mean? Well i've created a website using django + redis + celery + postgresql So what i want to do with this website is to Turn on/off LED lamp using a BreadBoard. this is done by celery ... actually there is a task (celery-beat-schedule) that should turn off/on some specific LED lamps and the django is the firmware that creates those tasks and controls my device For example: Imagine i have a task that represent the main job of the device (turning on/of) a i can create and run this tasks using django-celery-beat But The main question is how can i run this in a embedded system like raspberry pi. actually what are the best hardware like CPU RAM this website can run on that and does not crashed? For example, is Raspberry Pi zero w suitable for running this web server and setup? And there is no limit to the implementation? Of course, let me say this too. I don't want to spend too much otherwise I think the Raspberry Pi … -
Django - Consecutive Request Override Session Attribute
I want to generate an invoice for each order, and in some cases, there are two generated invoices for one order. For those cases, the first invoice request fails and I receive a 400 error with "invalid signature" message (as I defined in my view logic), while the second remaining success. My views.py from django.core import signing from django.contrib import messages class OrderView(MyMultiFormsView): forms = {‘create’: OrderForm} … # view logic for get method: display a list of orders def post(self, request, *args, **kwargs): form = self.forms[‘create’](request.POST, request.FILES, prefix=‘create’) if form.is_valid(): order = form.save() messages.success(request, signing.dump(order.id)) if order.is_paid: messages.info(request, signing.dump(order.id)) return redirect(request.get_full_path()) … # not valid: render form and show errors class ExportView(View): http_method_names = [‘get’] actions = { 'invoice': { 'url_token': 'print-invoice', 'session_prop': '_invoice_token', }, 'receipt': { 'url_token': 'print-receipt', 'session_prop': '_receipt_token', }, } def get(self, request, *args, **kwargs): if kwargs['action'] not in self.actions: return render(request, '400.html', {'msg': 'undefined action'}, status=400) action = self.actions[kwargs['action']] if kwargs['token'] == action['url_token']: try: token = request.session.pop(action['session_prop']) sign = signing.load(token) except: return render(request, '400.html', {'msg': 'invalid signature', status=400) return getattr(self, kwargs['action'])(sign) else: request.session[action['session_prop']] = kwargs['token'] print(request.session.__dict__) redirect_url = request.path.replace(kwargs['token'], action['url_token']) return redirect(redirect_url) def invoice(self, sign): inv = Invoice(sign) # inv.as_file() returns a pdf file with … -
Django: Problem with passing parameters from a template {% url %} to a view
I have this urlpath: path('download/<str:fpath>/<str:fname>', views.download, name='download'), And this is the view: def download(request, fpath, fname): # some code In template, I have this href tag and I want to pass those strings as arguments to the download view. <a href="{% url 'download' 'lms/static/lms/files/homework/Math 1/3/3' 'hmm.pdf' %}">click me</a> But I get this error: NoReverseMatch at / Reverse for 'download' with arguments '('lms/static/lms/files/homework/Math 1/3/3', 'hmm.pdf')' not found. 1 pattern(s) tried: ['download/(?P<fpath>[^/]+)/(?P<fname>[^/]+)\\Z'] How can I fix this? -
How do I return a 401 response in a SimpleJWT Custom Token when using the Django Rest Framework?
I would like to return a 401 message if the user is not enabled. When I try returning a response instead of a token it doesn't work which I understand to be because the serializer is expecting the token. How do I customise it to send a 401 response if the user is not enabled please? My custom token class is as below: from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView from rest_framework import status from rest_framework.response import Response class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): if user.is_enabled: token = super().get_token(user) # Add custom claims token['name'] = user.name token['gender'] = user.gender return token else: return Response({'detail':'Account not enabled'}, status=status.HTTP_401_UNAUTHORIZED) class CustomTokenObtainPairView(TokenObtainPairView): serializer_class = CustomTokenObtainPairSerializer The URL root looks like: re_path(r'^authenticate/',CustomTokenObtainPairView.as_view(), name='authenticate'), -
NotSupportedError at / deterministic=True requires SQLite 3.8.3 or higher
I am trying to deploy a Django application using the default SQLite database to Elastic Beanstalk. The application works fine locally, however, on server, I get the error as : Any idea what's wrong? Can we not deploy SQLite app on AWS EBS? Here is my project structure that is getting deployed ├── .ebextensions │ ├── django.config ├── app │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── __init__.py │ ├── models.py │ ├── static │ │ └── app │ │ ├── app.js │ │ ├── logo.svg │ │ └── style.css │ ├── templates │ │ └── app │ │ ├── hello.html │ │ ├── index.html │ │ └── job_detail.html │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── env │ ├── All Virtual env related files ├── images │ ├── Photo_on_5-9-14_at_2.31_PM.jpg │ ├── Photo_on_5-9-14_at_2.32_PM.jpg │ └── Photo_on_5-9-14_at_2.32_PM_v4McLzE.jpg ├── myproject-test │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── requirements.txt ├── staticfiles │ |-- All static files collected using collectstatic │ ├── app │ │ ├── app.js │ │ ├── logo.svg │ │ └── style.css │ └── subscribe … -
Is there a way to pass a secret variable into a static JS File?
I have looked everywhere for a way to pass a secret variable into an API call that I make in a JS file on Django, but can't figure out a way. Is anyone familiar with this?