Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django unit test constraints
So I have a problem in writing my unit tests for a Check and Unique constraint. Here are the their definition: # assert that a partner can have only one headquarter constraints = [ models.UniqueConstraint( fields=['partner', 'active'], condition=models.Q(headquarter=True), name='HQ already set.' ) ] # assert every partner contant has at least one of email/phone number pair defined constraints = [ models.CheckConstraint( check= ( models.Q(email__isnull=False) & models.Q(phone_number__isnull=False) ), name='E-mail or phone number should be set.' ) ] And the unit test asserts which fails: from django.db.utils import IntegrityError .... # HQ already defined so it should work with self.assertRaises(Exception) as raised: partnerHQCopy.save() self.assertEqual(IntegrityError, type(raised.exception)) ..... # The contact added has both email and phone number None with self.assertRaises(Exception) as raised: partnerContact.save() self.assertEqual(IntegrityError, type(raised.exception)) And the traceback: ====================================================================== ERROR: test_unique_hq_for_partner (partners.tests.PartnerModelsTestCases) ---------------------------------------------------------------------- ..... sqlite3.IntegrityError: UNIQUE constraint failed: partners_partnerbranch.partner_id, partners_partnerbranch.active ..... django.db.utils.IntegrityError: UNIQUE constraint failed: partners_partnerbranch.partner_id, partners_partnerbranch.active ====================================================================== ERROR: test_partner_contact_no_email_no_phone (partners.tests.PartnerModelsTestCases) ---------------------------------------------------------------------- ..... sqlite3.IntegrityError: CHECK constraint failed: E-mail or phone number should be set. ..... django.db.utils.IntegrityError: CHECK constraint failed: E-mail or phone number should be set. -
Django HTML can't read the values of the dict
When I pass a simple dict (myDict = {"key": "value"}) throught render to html, it creates an error as the html can't read the values of the dict .. {{ myDict["key"] }} <!--- prompts an error--> django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '['key']' from 'myDict['key']' Why didn't I pass the value directly? Because my question is not about this particular example. I'm searching for a more effecient way to use in case I wanted to pass bigger dicts and avoid writing down a for loop and if conditions on every line. -
How to deal with multiple rows of same table in django orm?
I have this table: User |Book name | count ------*----------*------ user1 | A | 4 user2 | A | 5 user1 | B | 6 user2 | B | 9 I have this table, Now I want to fetch all the users which have a total book count of less than 10. How can I write such a Django or query which involves dealing with two rows of the same table? -
How to use django-river transition approval in ListView or DetailView
I successfully implement django-river transition approval in my admin page so different groups can submit the approval and so on following the demo tutorial https://github.com/javrasya/fakejira I'm attempting to utilize the river-action "Transaction approval" on my ListView or DetailView so the users can submit on the approval using my ListView url instead of entering the admin page. My current ListView as below: class WorkOverRequestSubmitListView(ListView): model = WorkoverRequest context_object_name = 'submit_wor_list' template_name= 'wor/workovers_submit_list.html' Would you suggest what I should edit and add to my project to make this work! -
Set the value of a variable in django template using 'with' tag for checking in an 'if' condition. But get's error : 'endif', expected 'endwith'
I have set a variable as False in django templates, then sets the variable to True in an if condition both using 'with var=True/False' I use seperate 'endwith' tags for each 'with' tag. But I'm getting an error saying 'endif', expected 'endwith'. Template code as below: {% date_range as the_days %} {% for day in the_days %} {% with is_order_day=False %} {% for order in orders % {% if order.created_at.date == day.date in orders %} {% with is_order_day=True %} {% endif %} {% endfor %} {% if is_order_day %} <p>{{day.date}}</p> {% endif %} {% endwith %} {% endwith %} {% endfor %} thanks in advance. -
Django how to change the name of Custom User Model in error messages in a form
I have created a sign up form called UserRegistrationForm using UserCreationForm in djnago and have a custom user model name CustomUserModel. When I sign up using wrong credentials, the error messages show "Custom user model with this User name already exists.". I would like it to be something like "Username already exists". How can I do that? Forms.py class UserRegistrationForm(UserCreationForm): user_name = forms.CharField(max_length=150) email = forms.EmailField() first_name = forms.CharField(max_length=120) last_name = forms.CharField(max_length=120, required=False) date_of_birth = forms.DateField( widget=forms.DateInput( format='%d/%m/%Y', attrs={'type': 'date', 'min': '1900-01-01', 'max': str(timezone.now().year)+'-'+str(timezone.now().month)+'-'+str(timezone.now().day)}, ) ) gender = forms.ChoiceField( widget=forms.Select, choices=(('M', 'Male'), ('F', 'Female'), ('T', 'Transgender'), ('N', 'NonBinary')), initial='N', ) def is_valid(self): form = super(UserRegistrationForm, self).is_valid() print("*******************************") print(self.errors) print("*******************************") return form Here is a picture to help you understand my problem here the error states "Custom user model with this User name already exists." I want to change this message -
How to remove a library whose initial migration is being depended on?
So my model used to inherit from a Message class of django-postman library. Therefore my 0001_initial migration looks like this: class Migration(migrations.Migration): initial = True dependencies = [ ('postman', '0001_initial'), ] operations = [ migrations.CreateModel( name='Message', fields=[ ('message_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='postman.Message')), ('created_at', models.DateTimeField(auto_now_add=True)), ('deliver_at', models.DateTimeField(blank=True, null=True)), ('content', models.TextField(blank=True, null=True)), ], bases=('postman.message',), ), ] Now I want to totally remove my own Message model. I can remove it normally and run makemigrations which creates 0004_delete_message that looks like this: class Migration(migrations.Migration): dependencies = [ ('postman', '0001_initial'), ('my_app', '0003_migrate_data_to_new_model'), ] operations = [ migrations.DeleteModel( name='Message', ), ] Now the issue is that I totally want to remove django-postman library, including from my INSTALLED_APPS. This creates the issue of both of these migrations not being applicable because they both depend on postman.0001_initial which doesn't exist anymore. Is there clean way of going about that deprecation while still keeping my migrations working or do I have to manually edit my 0001_initial and run CreateModel for the model introduced in postman.0001_initial, and change bases of my model to point to that model I created? -
Django dependent dropdown with ajax. Do I need to divide my model to 3 different models in order to implement dependant dropdown?
I have model in my django that describe cars. It have fields: make model price I want to let users to create queries for them through django forms and I wanted to implement dependent dropdown. When user selects "make" then available "models" change. I saw some tutorials but it seems that all of them would divide my model car into three different models but foreign keys. I suppose it would look something like this: Makes: - name Models: - make (foreign key) - name Car: - price - make (foreign key) - model (foreign key) I am wondering, is it possible to somehow implement this dependant dropdown in django forms while keeping only 1 cars model? And if so, what should I google? Thanks. -
custom validator for charfield do not raise any error
I have done a validator that is supposed to check the input from a charfield: def postnvali(value): if not value.isalnum(): raise ValidationError(_('postnummer måste vara siffror')) it is used in the following model: class Adress(Model): street=CharField(max_length=100) snumb=CharField(max_length=15) town=CharField(max_length=100) postn=CharField(max_length=5,validators=[postnvali]) def __str__(self): return 'city: ' + self.town class Meta: ordering=('street','town') but when using admin and entering the wrong format, nothing happens, no error message. why? -
Session data becomes null in second view in django
I do have session backend in my settings.py SESSION_ENGINE = "django.contrib.sessions.backends.db" how do i track of that my_car session variable in second view ? -
Get HTML form in Django fuction
I know there are explanations out there regarding this, but I didn't understand how to implement it in my code, so I am asking again. I get the following error ViewDoesNotExist at /answer_question/ 'False' is not a callable or a dot-notation path When I click the "Post your answer" button in my post.html form. It is like a Stack Overflow website. I have an URL called answer_question/ in urls.py path('answer_question/', views.answer_question, name="answer_question"), Then I made a function in views.py def answer_question(request): return render(request, 'store/homepage.html') def post(self, request): form = HomeForm(request.POST) if form.is_valid(): text = form.cleaned_data["post"] print("TEXT = " + str(text)) This has to make a new answer in the database. models.py class Answer(models.Model): title = models.CharField(max_length=200, null=True) context = models.TextField(max_length=1702, blank=True, validators=[MaxLengthValidator(1702)]) date = models.DateField(("Date"), default=date.today) author = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) def __str__(self): return self.title As for the syntax I looked at: https://www.youtube.com/watch?v=wzZiONbtwiA and https://docs.djangoproject.com/en/3.1/topics/forms/ <form action="/answer_question/" method="post"> <div class="blogpost"><br><br> <textarea name="answer-title-input" cols="20" rows="1" class="answer-title" maxlength="20" placeholder="Write a title here..." id="id_context"></textarea> <br><br><hr><br> <div class="blogpost-content"> <textarea name="answer-context-input" cols="80" rows="10" class="answer-input" maxlength="300" placeholder="Write an answer here..." id="id_context"></textarea> <br> <br> <button type="submit" class="submit-answer-button">Post your answer</button> -
How can we identify wether the client is viewing my website from a mobile or a desktop?
wondering if any of you could help me out... My issue is that I need to adjust the size of an image and rearrange the positions of elements in HTML depending on wether the client is using a phone or a larger screen such as a laptop. I need a function which can detect if the user is viewing my website using a mobile or a desktop. I searched the internet and found very very long solutions to them and I feel there should be a shorter one. I am using django (python) for my server and HTML, CSS and JAVASCRIPT for the front end. If anyone could provide me a function to do so, I would be very thankful to you. Thanks in advance -
I want to make dynamic task scheduling chatbot system in flask python
I am making a dynamic task scheduling chatbot system in flask python. which actually helps managers to assign tasks to their employees. Now I want to know how to make responsive system between manager and employee and they both are going to interact with chatbot integration provided by facebook.Please help me by giving such kind of sample code. import os import sys import json import requests from flask import Flask, request app = Flask(__name__) TOKEN = Page_Access_token VERIFY_TOKEN = verification_token params = { "access_token": TOKEN } headers = { "Content-Type": "application/json" } @app.route('/webhook', methods=['GET']) def verification(): # Webhook Verification if request.args.get("hub.challenge"): if not request.args.get("hub.verify_token") == VERIFY_TOKEN: return "Verification token mismatch", 403 return request.args["hub.challenge"], 200 return "Hello", 200 @app.route('/webhook', methods=['POST']) def webhook(): # Messaging Events data = request.get_json() log(data) if data["object"] == "page": for entry in data["entry"]: for messaging_event in entry["messaging"]: if messaging_event.get("message"): #Messaging Event receiveMessage(messaging_event) else: # Unknown Event log("Webhook received unknown messaging_event: " + str(messaging_event)) return "ok", 200 def sendMessage(recipient_id, message_text): # Definition of sendMessage - A function to send Text Messages to user log("sending message to {recipient}: {text}".format(recipient=recipient_id, text=message_text.encode('utf-8'))) # encode('utf-8') included to log emojis to heroku logs message_data = json.dumps({ "recipient": { "id": recipient_id }, "message": { … -
The view mysiteapp.views.addpost didn't return an HttpResponse object. It returned None instead
my views.py file i just try to update form data form dashboard so i'm not getting what's going wrong to the code can someone please help me to solve def addpost(request): if request.user.is_authenticated: if request.method == 'POST': forms = addpostForm(request.POST) if is_valid(): forms.save() forms =addpostForm() else: forms = addpostForm() return render(request,"addpost.html",{'form':forms}) else: return HttpResponseRedirect('login') addpost.html file <form action ='' method='POST'> {% csrf_token %} {{form.as_p}} <input type='submit' class='btn btn-success btn-sm' value ='Add' > <input type='submit' class='btn btn-danger btn-sm' value ='Cancel' > </form> my forms.py class addpostForm(forms.ModelForm): class Meta: model = post fields = ['title','desc'] labels ={'title':'Title','desc':'Description'} widgets = {'title':forms.TextInput(attrs={"class":'form-control'}),'desc':forms.Textarea(attrs={"class":'form-control'}),} -
How to apply a migration operation in runtime?
Having a dynamically created instance of django.db.migrations.operations.base.Operation (CreateModel operation in particular) which is encapsulated in a SeparateDatabaseAndState as a database operation only (with no state operations to tamper with the normal migration system), how can I execute the operation in runtime (i.e., without using migration files)? The requirement is to be able to create and drop tables at runtime which are highly compatible with Django-defined models and database-DDL-independent at the time of creation. These tables will be named using a special prefix to not collide with normal Django tables, and they will be limited in numbers. (And yes, I am aware of possible design and performance issues; this may seem a bad-practice, there are alternative solutions, and so on!) If this is not possible, an alternative question will be: How to get the raw SQL statement from a dynamically created instance of django.db.migrations.operations.base.Operation? -
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module with MySQL installed
Hardware configuration I'm configuring my new MacBook Air with Apple silicon M1 chip and obviously mac os 11 Big Sur. Environment I have installed mysql@5.7 with homebrew and use python@3.6.5 installed with pyenv@1.2.21. The issue I work with Django framework and the last step for me is to configure the MySQL database on localhost. MySQL server is running and I can use it from the shell and access it by SequelPro. When I run python manage.py migrate I have this problem : django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? The database configuration is: DATABASE environment Does someone have the same problem? -
overriding save method to save ip address in django models
I am working on a Django project and I need to save the user's IP address in my database. I can get user's ip address with request.META.get("REMOTE_ADDR"). Currently, I have to provide an IP address in my save and edit views. I was looking for a clean solution so that I can override the models save() method and let models save IP address every time a new record is added or any record is updated. But Django models don't have access to request. Is there any workaround for this? or do I have to provide an IP address in my every saves and edits view. -
What is the right way to create .env file on remote machine(like AWS instance)?
I have a Django project where the settings file refers to a .env file(in root). The .env file contains all the sensitive data like Database password, Debug value. As a security measure, this .env file has been added to .gitignore and wouldn't be uploaded to GIT repository. Now, how do I add this file to the root of a remote host like AWS instance? -
Django AWS RDS environment variables not setting in Elastic Beanstalk
I'm using Amazon Linux 2 in an AWS Elastic Beanstalk instance to host my Django web server. When using SSHing into my environment, I cannot run manage.py commands because os.environ doesn't contain environment variables for my RDS db. So when in my settings.py file I try to access the database like so: if 'RDS_DB_NAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'home', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', } } It thinks I am still on localhost and it gives me an error. How do I get around this? Is there a way to load in my RDS environment variables via the /opt/elasticbeanstalk/bin/get-config environment command or is there another way that doesn't require SSH? -
message not showing in template
i am trying to make my new blog and as so many blogs there is a registration form so i added a login page and in the views.py of the login i added a message.error but when i use the for statement in the template it doesnt show views.py: from django.shortcuts import render from .forms import RegisterForm from django.shortcuts import redirect from django.contrib import messages def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username and password: user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Username or Password is Incorrect') else: messages.error(request, 'Fill out all the Fields Please') return render(request, 'register/login.html',{}) my template: <div class="form-floating mb-3"> <input type="text" class="form-control" id="floatingInput" placeholder="name@example.com" name="username"> <label for="floatingInput">Username</label> </div> <div class="form-floating"> <input type="password" class="form-control" id="floatingPassword" placeholder="Password" name="password"> <label for="floatingPassword">Password</label> </div> {% if messages %} {% for message in messages %} <h4 class="{{ message.tags }}" style="color: red;">{{ message }}</h4> {% endfor %} {% endif %} when i use the for loop it doesn't show any message on my page but when i only use {{ messages }} it show me this : ** <django.contrib.messages.storage.cookie.CookieStorage object at 0x0000014473D5C490> ** -
'post' object is not iterable in django and it is showing error but i'm not getting what's going wrong on code
TypeError at /dashboard 'post' object is not iterable i am just try to get data from db table and show on dashboard in dabel form my dashboard.html page {% if posts %} <table class="table table-dark table-hover"> <thead> <tr> <th scope="col" style="width:3%">ID</th> <th scope="col" style="width:30%">Title</th> <th scope="col" style="width:55%">Description</th> <th scope="col" style="width:15%">Action</th> </tr> </thead> <tbody> {% for post in posts %} <tr> <td>{{posts.id}} </td> <td>{{posts.title}}</td> <td>{{posts.desc}}</td> <td><a class="btn btn-primary" type="submit" value="Submit">Edit</a> <form action ='' , method ='POST' class='d-inline'> {% csrf_token %} <input type='submit' class='btn btn-danger btn-sm' value ='Delete' > </form> </td> </tr> {% endfor %} </tbody> </table> {% else %} <h4 class =' text-center alert alert-warning'>No Records </h4> {% endif %} </div> </div> {% endblock content %} my views.py def dashboard(request): if request.user.is_authenticated: posts= post.objects.all() return render(request,'dashboard.html',{'posts':post}) else: return HttpResponseRedirect('login') urls.py path('dashboard',views.dashboard,name='dashboard'), -
How to limit choices on the Django filter based on the request.user
I have a multi company setup. The user is logged into to a specific company. Every company has its own set of ledger accounts and transactions. On the transaction list I created filter options so that the user can filter based on "Description", "Transaction date" and "Ledger account". The problem with the Ledger Account is that the choices available is the accounts from all the companies. I ant to limit the choices to only show the Ledger Accounts from the current company that the user is logged into. User model: class custom_user(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) company_group = models.CharField(max_length=6, null=True) current_company = models.ForeignKey(tcompany, on_delete=models.CASCADE, null=True) Note the current_company as a ForeignKey. Leger Account Model: class tledger_account(models.Model): id = models.AutoField(primary_key=True) slug = models.SlugField(max_length=30, null=True) description = models.CharField(max_length=30, unique=False) gl_category = models.CharField(max_length=30, choices=category_choices, verbose_name='category', db_index=True) note = models.CharField(max_length=25, blank=True, default=None) active = models.BooleanField(default=True) company = models.ForeignKey(tcompany, on_delete=models.PROTECT) class Meta: indexes =[ models.Index(fields=['company', 'description']) ] unique_together = ['company', 'description'] Note the company as a ForeignKey. Views.py: class TransactionlistView(ListView): model = ttransactions template_name = 'accounting/transaction_list.html' def get_form_kwargs(self): … -
How to Query data from MySQL database with Django following model update
After updating posts model field in MySQL database using using Django framework, I'm unable to query posts from the Database. Whenever I run the command python manage.py runserver, all seems to be well with the server. However, when enter the post url to display the list of posts I uploaded on the database before updating the model field, I get 1054, "Uknown column 'start_post.author_id' in the 'field list' I have spent a couple of hours try to figure out why I'm getting the error but I still don't get it. In model.py I had: title = models.CharField() preamble= models.Charfield() body = models.TextField() createdAt = models.DateTimeField(auto_now_add=True, blank=True) I updated the above model to: title = models CharField() author = models.ForeignKey(User, on_delete=models.CASCADE) introduction = models.charfield () body = models.TextField() createdAt = models.DateTimeField(auto_now_add=True, blank=True) def get_absolute(self): return reverse ('post-details', kwarks={'pk': set.pk}) views.py •••• class PostListView(Listview): model = Post template_name = 'start/start.html' context_object_name = 'posts' ordering = ['createdAt'] start.html ••• {% for post in posts %} <h3>{{ post.title }}</h3> <i>{{ post.createdAt }} </I> <p>{{ post.introduction }}</p> <p>{{ post.body }}</p> {% endfor %} •••• before updating it everything was working appropriately. But after updating it I'm unable to access the list of posts on browser, … -
my images array is empty when I pass student to actions in redux but it is working in postman
I am trying to add image files to images array using React but I am getting an empty images array. My backend is written in Django. It is working fine when Im using postman to insert image files but I am getting an empty array when using react. AddNewStudent.js file const AddNewStudent = () => { const [Name, setName]= useState('') const [Enrollment_No, setEnrollmentNo]= useState('') const [Registration_No, setRegistrationNo]= useState('') const [Semester, setSemester]= useState('') const [Year, setYear]= useState('') const [Course_Name, setCourseName]= useState('') const [Course_Code, setCourseCode]= useState('') const [studentImages, setStudentImages]= useState([]) const dispatch= useDispatch() const submitForm= (e) => { e.preventDefault() const images=[] for (let image of studentImages){ images.push({ image }) } console.log(images) const student={ Name, Enrollment_No, Registration_No, Semester, Year, Course_Name, Course_Code, images } console.log(student) dispatch(addStudent(student)) } const handleStudentImages = (e) => { setStudentImages([ ...studentImages, e.target.files[0] ]) } return ( <CCard> <CCardHeader> Add New Student </CCardHeader> <CCardBody> <CForm action="" method="post" onSubmit={submitForm}> <CFormGroup> <CLabel htmlFor="nf-name">Name</CLabel> <CInput type="text" id="nf-name" name="nf-name" placeholder="Name" autoComplete="name" onChange={(e) => setName(e.target.value)}/> </CFormGroup> <CFormGroup row className="my-0"> <CCol xs="6"> <CFormGroup> <CLabel htmlFor="nf-enrollmentno">Enrollment No</CLabel> <CInput type="text" id="nf-enrollmentno" name="nf-enrollmentno" placeholder="Enrollment Number" autoComplete="enrollment_no" onChange={(e) => setEnrollmentNo(e.target.value)}/> </CFormGroup> </CCol> <CCol xs="6"> <CFormGroup> <CLabel htmlFor="nf-registrationno">Registration No</CLabel> <CInput type="text" id="nf-registrationno" name="nf-registrationno" placeholder="Registration Number" autoComplete="registration_no" onChange={(e) => setRegistrationNo(e.target.value)}/> </CFormGroup> </CCol> </CFormGroup> … -
How to sync my local database of my web app to database of my deployed web app?
So my project is a school distributed system based on django web framework. My web app will be deployed in every school on their local computers. And all of the data on those computer will by synced with a main server on my side. What I want is how to implement a solution that would help me sync files/data with my server such that if some file/data is changed on a local computer it'll replicate itself in our server and if I change some file/data on my server, it'll update on those local computers whenever they get an internet connection.