Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django django.db.utils.IntegrityError: duplicate key value
I have a problem with simple user model.I wrote a test for email normalize function and in response i've got a " django.db.utils.IntegrityError: duplicate key value violates unique constraint "core_user_username_key" DETAIL: Key (username)=() already exists. " When I added a "user.delete()"after "self.assertEqual(user.email, expected)" all test passed.What is wrong ? Is that test creates users with the same username field ? Models.py class UserManager(BaseUserManager): """Manager for user""" def create_user(self, email, password=None, **extra_fields): user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user class User(AbstractUser, PermissionsMixin): """User model""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' test.py class ModelTest(TestCase): def test_create_user_with_email(self): """Testing creating user with email address""" email = 'testaddress@example.com' password = 'testpassword1234' user = get_user_model().objects.create_user( email=email, password=password, ) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) def test_user_email_normalized(self): """Testing email normalize function""" test_emails = [ ['test1@EXAMPLE.Com', 'test1@example.com'], ['TesT2@exaMple.com', 'TesT2@example.com'], ] for email, expected in test_emails: user = get_user_model().objects.create_user(email, 'password123') self.assertEqual(user.email, expected) user.delete() -
socket.gaierror: [Errno -2] Name or service not known when try to establish socket connection with js client to django running in docker container
1- I have a django project which is running in docker container in localhost on port 8000 2- And I have a react app which is running in localhost on port 3000 I want to establish socket connection between react app and django with this command react app const chatSocket = new WebSocket( 'ws://' // + window.location.host + 'localhost:8000' + '/ws/room/' ); chatSocket.onmessage = function(e) { const data = JSON.parse(e.data); if (data.message) { // document.querySelector('#chat-messages').innerHTML += ('<b>' + data.username + '</b>: ' + data.message + '<br>'); } else { alert('The message is empty!'); } }; chatSocket.onclose = function(e) { console.log('The socket close unexpectadly'); }; const handleNewUserMessage = (message) =>{ chatSocket.send(JSON.stringify({ 'message': message, 'username': username, 'room_name': roomName })); console.log("received"); } and django files are like below: asgi.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import chat.routing from .settings import ASGI_APPLICATION os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Irangard.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ) }) routing.py from django.urls import path from chat.consumers import ChatConsumer websocket_urlpatterns = [ path('ws/room/', ChatConsumer.as_asgi()), ] consumers.py class ChatConsumer(WebsocketConsumer): def connect(self): # self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_name = 'emad12' self.room_group_name = 'chat_%s' % self.room_name # Join room async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) … -
Two variables in for loop for django form request
As the title says I am trying to use 2 variables in for loop in a django view. The django view takes 2 inputs from the html form and insert the received data into the django model. I tried using zip() and itertools.product() but they do not seem to work, I also tried nesting them as well as using 2 different for loops, but that also does not seem to work, is there a way to do this? Code as follows, template.html {% extends 'staff/base.html' %} {% load crispy_forms_tags %} {% block title %}Sem-1 Attendance{% endblock %} {% block content %} <h1>Semester 1 Attendance:</h1> <hr /> <form method="POST"> {% csrf_token %} <select name="subject" class="select form-select" id="id_subject"> <option value="ENGINEERING MATHEMATICS">ENGINEERING MATHEMATICS</option> <option value="FUNDAMENTALS OF COMPUTER">FUNDAMENTALS OF COMPUTER</option> <option value="FUNDAMENTALS OF ELECTRICAL &amp; ELECTRONICS ENGINEERING LAB" > FUNDAMENTALS OF ELECTRICAL &amp; ELECTRONICS ENGINEERING LAB </option> <option value="IT SKILLS LAB">IT SKILLS LAB</option> <option value="ENVIRONMENT SUSTAINABILITY"> ENVIRONMENT SUSTAINABILITY </option> </select> <table class="table table-bordered"> <thead> <th>Roll Number</th> <th>Status</th> </thead> <tbody> {% for x in at1 %} <tr> <td> <input class="form-control-plaintext" type="text" name="roll_no" id="roll_no" readonly value="{{ x.roll_no }}" /> </td> <td> <input class="form-check-input" type="checkbox" value="absent" id="absent" name="absent" /> <label class="form-check-label" for="flexCheck"> Absent </label> </td> </tr> {% … -
Openpyxl Django
Trying to automate modifying an Ecxel file using openpyxl lib and below code works: def modify_excel_view(request): wb = openpyxl.load_workbook('C:\\my_dir\\filename.xlsx') sh1 = wb['Sheet1'] row = sh1.max_row column = sh1.max_column for i in range(2, row + 1): # ...some_code... wb.save('C:\\my_dir\\new_filename.xlsx') return render(request, 'my_app/convert.html', {'wb': wb}) But how to implement a similar method without static (hardcoding) path to file and a filename? Like choosing xlsx file from modal window? Saving modified copy on a desktop by default? (Maybe like 'ReportLab library': response.write(pdf)=>return response. And it saving on the desktop by default.) Thank you in advance! -
Django server won't load
I am trying to run my django server using the python manage.py runservercommand. Keep getting this error in my shell. The development server is refusing to load. The image is the error message I'm getting -
Can't access Django admin page it gives an error as below
enter image description here enter image description here enter image description here Can't access Django admin page it gives an error as above . Please help me! -
Django register users
I'm building a social media app and I want to create users without using the user creation form so I can build my own form. I am using. User.objects.create_user() however when I put User.objects.create_user(username=request.POST['un']) I get this error 'UNIQUE constraint failed: auth_user.username'. When I just pass a string it works fine however when I use the form data it doesn't. -
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?