Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django queryset filter check if ManyToMany Field contains specific object
I have these two models : class Project(models.Model): name = models.CharField(max_length=50) users = models.ManyToManyField(User) class User(models.Model): name = models.CharField(max_length=25) I want to get a queryset containing all the Projects with a specific user in the 'users' ManyToManyField I tried this : Project.objects.filter(users__contains=user), but it's not working Does someone know how can I do it ? -
Database admin page
After uploading the site to hosting I tried to access the admin page But I was not allowed to enter Error: FATAL: password authentication failed for user "postgres" Do I have to change my data in settings.py ? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbtst', 'USER': 'postgres', 'PASSWORD':'******', 'HOST': 'localhost', 'PORT': '5432', } } -
How to return Http response and render with context at the same time?
In my web application made with django, I am trying to upload a excel file and it will do a certain calculation from the data of the file and will auto export the updated file. But at the same time I want to show specific information into a template. Here is the code from my views.py that I tried context = {'mttr_count': mttr_count, 'mttr_avg': mttr_avg, 'data':sheet} response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="mttr.xls"' rendered = render_to_string('mttr/mttr-output.html', context) response = HttpResponse(rendered) wb.save(response) return response But it does not give the desired result. How do I make it so that upon file upload and pressing the submit button, it will render the 'mttr.html' template with data in 'context' and will also download the modified file? -
Django email field invalid for international email (in non-english)
I am using django REST framework. This is my user model extended from AbstractUser class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) I am now trying to check for multiple languages my models can work. When I validate the user object serializer using if user_serializer.is_valid(): it gives me false. I tried entering the user details by django admin panel but there it says Email is invalid All other fields like models.CharField work perfectly fine with other languages. But this email field does not work. Any help is appreciated. -
Django typehinting
I created a empty migration, which now looks like this: def forwards(apps, schema_editor): Foo = apps.get_model('app', 'Foo') FixedResponse.objects.create(name='Bar') def backwards(apps, schema_editor): Foo = apps.get_model('app', 'Foo') Foo.objects.filter(name='Bar').delete() class Migration(migrations.Migration): dependencies = [ ('app', '0035_fixedresponse'), ] operations = [ migrations.RunPython(forwards, backwards) ] Since there is no Django documentation anywhere on this topic( Migrations specific) or best practice, I want to know how do I type hint the code above? -
How to write row names while exporting django querysets to csv?
The below function exporting into csv properly but one thing missing is the header of those value. How to write header of those values ? class Echo: def write(self, value): return value def some_streaming_csv_view(request): rows = MyModel.objects.values_list("value1", "value2") pseudo_buffer = Echo() writer = csv.writer(pseudo_buffer) writer.writerow(["name1", "name2"]) # didn't work response = StreamingHttpResponse( (writer.writerow(row) for row in rows), status=200, content_type="text/csv", ) response["Content-Disposition"] ='attachment; filename=filname.csv' return response -
How to customize Date and Time field in django forms
How to customzie the default dateTime field in django forms to be more friendly to the user forms.py: class new_album_form(forms.ModelForm): class Meta: model = album fields = ['album_name', 'album_artist', 'released_at', 'price', 'is_approved'] My field output in the form I want it to be like this -
Google Drive API not prompts for authorize access?
I am building a website where I can store my files on google drive using google drive API. In development, I use Windows, where my code runs smoothly. In windows, google ask me for authentication and after login, everything works perfectly. I can upload files and also create folders. I have deployed my website on ubuntu os on hostinger. Now when I try to upload or create a folder it not asking me for authentication. I think my browser wait for authentication and the authentication window opens in my Linux machine where I have hosted my site. -
Django restricting users from updating/deleting other users posts
views.py @login_required(login_url='/login') def updatepost(request,pk): post = Post.objects.get(id=pk) form = PostForm(instance=post) if request.method =='POST': form = PostForm(request.POST, request.FILES, instance=post) if form.is_valid(): form.save() return redirect ('mainpage') context = {'form':form} return render( request, 'postform.html', context ) postform.html {% include 'main.html'%} {% block content %} {%if user.is_authenticated%} {% if user.id == post.user.id%} <div> <form method="POST" action =""> {% csrf_token %} {{form.as_p}} <input type="Submit" value ="Submit"/> </form> </div> {%endif%} {%endif%} {% endblock content %} I am trying to restrict user who is logged in - from updating , deleting other users posts. However when I Try to use {% if user.id == post.user.id%} , the page becomes blank even for the user who is editing his own post. The same goes for deleting. It works on mainpages - where posts are displayed (it hides edit and delete buttons). What is the reason that the post is not showing inside the template ? I don't understand that even {{post.user}} in postform.html does not appear , neither on deleteform etc. - why this data of objects of a post is not being sent to postform.html ? -
how to deal with different ways to write the same thing
I wanna know if Django has any module to deal with this problem. I have multiple ways of writing the same city name in a Postgresql database that came from scraping different websites. The field "city name" could be "S. Diego" or "San Diego". My question is if I could have a module that could normalize always to "San Diego" in both situations and I could add some normalization when some new word appear like "S Diego", and maintain this workflow. Thanks -
How to add dependent Choice Field? (If a certain choice is picked on field 1, field 2 will exclude it from its choices)
I am trying to create a student model and form where each student has to have 6 subjects, no more no less. Of these 6 subjects, 1 subject from each of 3 specific categories is mandatory. For example, English Category: Language & Literature OR Literature -- MIN 1 BUT MAX 1 Language Category: Spanish OR French OR Arabic OR Mandarin -- MIN 1 BUT MAX 1 Science Category: Biology OR Chemistry OR ... -- MIN 1, NO MAX For the 3 other subjects required, students can pick subjects from any of the Science, Society, and Art categories (which are present in choices.py). However, I want to make it so that in the form, Students cannot have the same subject appearing more than once in their choices. Furthermore, how can I present the choices for the less restrictive choicefield of all three different 'categories' in 1 choice field? (For example, 'option1' is an attribute of Student just like 'english' from which students can pick any option from Scienec, Society, and Art, but cannot pick the same subjects twice.) PS: I tried finding an answer by myself, read the Django docs over and over and researched the question but found no answer. … -
Use ASP.NET Session inside Django Project
I have one website which is ASP.NET website and inside that project one django project is hosted for only one url. Till now this url is available openly but now i want to put authentication for this url and only allow accessibility when the user is logged in and redirect to login.aspx when logged out. I am having Session object in asp.net and based on this session object, i am allowing the accessibility of any url. Can anyone tell how to use this session object from asp.net in django project? -
Django model forms inheritance
I want to create child class UpdateMealdayForm that inherits from CreateMealdayForm. From my understanding I can simply overwrite fields attribute with the field name I want to use, but what if I wanted to add a new field to my child class that is not specified in a MealDay model? forms.py: class CreateMealdayForm(ModelForm): class Meta: model = MealDay fields = '__all__' widgets = { 'day': forms.DateInput(attrs={'type':'date'}), } labels = { 'day': 'Choose a date: ' } error_messages = { 'day': { 'unique': "You have already set up mealday for that day" }, } class UpdateMealdayForm(CreateMealdayForm): class Meta(CreateMealdayForm.Meta): fields = ['example_field'] -
Post method is not working in my HTML forms
my form is like this <h1>Signup below</h1> <form action="result" method="post"> {% csrf_token %} <h3>Username</h3> <input type="text" name="username" /> <h3>Email</h3> <input type="email" name="email"> <h3>Password</h3> <input type="password" name="password"> <h3>Rententer your password</h3> <input type="password" name="password2"> <input type="button" /> </form> and in my view folder code for this url is this def register(request): username=request.POST['username'] email=request.POST['username'] password=request.POST['username'] verify_password=request.POST['verify_password'] return render(request,'result.html') but whenever I run this code it shows screenshot of the error message -
Is it possible to change the Django.Form normalization type?
I have a Form class in a Django project with a few MultipleChoiceFields which I feed it choices of (int, str). When the form performs the data cleanup on the input values of the MultipleChoiceFields, the input values are of type int but to my surprise, when they get cleaned, the the django to_python() normalizes them to strings. Is there a way for me to specify what the normalization type should be for a FormField? Hopefully without having to create a child class and overwrite the original behavior? -
Django shell writes record in wrong db
There is two projects in our server: the first project is test project, the second project is not test project. All projects uses mssql db. The first project uses test db, the second project uses db that is not test. The first project reads environment variables from .env file. The second project reads environment variables from .bash_profile. When I ran django shell in the first project and created record using sql query record was created in db that is not test. How could this happen? -
Django Rest Framework. What is queryset and serializer_class?
Let's say I have the following viewset: class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer I am wondering what does the queryset and serializer_class do here? I can assume queryset is about how the models' order will be displayed (such as ordering, filtering and so on), but I may be wrong. Please correct me, and, if possible give broad explanation. -
centos apache httpd PIL: failed to map segment from shared object
So I'm trying to deploy a django web project to apache httpd through mod_wsi on centos 9. In fact I did and it worked, I was able to access the login page of the host website, at least the login page only; anything post login resulted to 500 internal server error which on the logs was due to missing write permission on the sqlite db I was using. The entire thing only worked after I changed SELinux from enforce to permissive and later on when I rebooted the server computer all hell broke loose with SELinux, apparently it went back to enforce and brought with it even more errors on top of the initial write permission. I later learnt that SELinux is quite troublesome when httpd operates on files outside it default directory '/var/www/html'; FYI I had the django files in the '/var/www' folder. I went ahead and copied the files from '/var/www' to '/var/www/html' whence the error in the title section became about. Here is the complete log: [Tue Oct 18 08:34:42.324342 2022] [wsgi:error] [pid 4367:tid 4412] [client 105.27.237.117:57201] mod_wsgi (pid=4367): Failed to exec Python script file '/var/www/html/TempHumidityMonitor/WeatherMonitorPlatform/WeatherMonitorPlatform/wsgi.py'., referer: http://x.x.x.x/ [Tue Oct 18 08:34:42.324791 2022] [wsgi:error] [pid 4367:tid 4412] … -
How to Fetch random ngrok url using django and open it on raspberry pi automatically
I am making a project of video chat app with Django framework i use ngrok for custom url of this app by ngrok http http://localhost:8000 command. I need to fetch ngrok custom url of ngrok and open it automatically when my raspberry pi open.I know how to run programs automatically while turning on the raspberry pi.but how my raspberry pi automatically open the web browser and paste ngrok random url here and open browser permissions of camera and microphone. Kindly help me on this i read servel things on internet but did't find a soultion to this problem, -
django admin Postoffice queued mails are not editable
I am working on two separate django apps. We are sending mail in django. Due to some mistakes in the mail sometimes it is required to edit the queued mail. But for some the one of the apps allow to edit the queued mail whereas the other apps won't allow to edit the contents. I am new to django and don't know how to solve this thing. -
Filter child class date field in DRF
I'm new in DRF , i need to child class filed filter in parent view models.py class Customer(Base): name = models.CharField(max_length=100) phone_number = models.CharField(max_length=100, blank=True, null=True) comments = models.CharField(max_length=255, blank=True, null=True) class Cart(Base): user = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="cart") cart_number = models.CharField(max_length=500, default=increment_cart_number, null=True, blank=True) total_summa = models.FloatField(default=0) is_saved = models.BooleanField(default=False) class Base(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True filters.py class CustomerListFilter(rest_framework.FilterSet): name = rest_framework.CharFilter(lookup_expr='icontains') class Meta: model = Customer fields = [ 'name', 'phone_number', ] I need to filter the list of customer's carts according to the dates of the carts -
Unable to display a Bootstrap 5 stepper in a Django
I am having a problem getting the vanilla flavored stepper Bootstrap function to display properly in Django and wondered if there is something I am missing. Other Bootstrap elements such as alerts work fine. None of the formatting for the stepper is being picked up and I am just getting the text displayed vertically e.g.as follows without the bullet points 01 Basic Information 02 Personal Data 03 Terms and Conditions 04 Finish Step 1 Step 2 Step 3 Step 4 I have a Base html where I have the Bootstrap cdns. e.g. <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> I wish to display the stepper in index.html which extends base.html. Within a div with class="container-fluid", I have another div where I have inserted the standard horizontal stepper code i.e. <div class="row mt-4"> <p> <div height="800px" class="stepper" id="stepper2"> <div class="steps-container"> <div class="steps"> <div class="step" icon="fa fa-pencil-alt" id="1"> <div class="step-title"> <span class="step-number">01</span> <div class="step-text">Basic Information</div> </div> </div> <div class="step" icon="fa fa-info-circle" id="2"> <div class="step-title"> <span class="step-number">02</span> <div class="step-text">Personal Data</div> </div> </div> <div class="step" icon="fa fa-book-reader" id="3"> <div class="step-title"> <span class="step-number">03</span> <div class="step-text">Terms and Conditions</div> </div> </div> <div class="step" icon="fa fa-check" id="4"> <div class="step-title"> <span class="step-number">04</span> <div class="step-text">Finish</div> </div> </div> </div> … -
Django tests : doesn't work for testing case for is_staff user
That seems to be a silly question explained by some stupid error, but I could not figure it out for the moment. General situation : I have a little Djano app used as small database for some items. Items could be viewed, edit or deleted. View is available for all users, but edit/delete only for Staff users. It was implemented and during manual test it works fine (if I'm not staff user I get 403 for edit/delete pages, then if I become staff user : I could edit/delete). But the automatic test Fail and I could not figure why. Here is the test code : def createTestUserAndLogin(self): self.user = User.objects.create_user(username='testuser', password='qwerty') login = self.client.login(username='testuser', password='qwerty') def createTestStaffUserAndLogin(self): self.user = User.objects.create_user(username='staffuser', password='qwerty_staff', is_staff=True) login = self.client.login(username='testuser', password='qwerty_staff') self.assertTrue(self.user.is_staff, "User is not staff") def test_delete_item_as_non_staff_user(self): test_serial = "AA1111" new_item = Item(serial_number=test_serial) new_item.save() self.createTestUserAndLogin() url = reverse("delete_item", kwargs={'pk':new_item.id}) resp = self.client.get(url) self.assertEqual(resp.status_code, 403) self.client.logout() def test_delete_item_as_staff_user(self): test_serial = "AA1111" new_item = Item(serial_number=test_serial) new_item.save() # Could delete with Staff user self.createTestStaffUserAndLogin() self.assertTrue(self.user.is_staff, "User is not staff") url = reverse("delete_item", kwargs={'pk':new_item.id}) resp = self.client.get(url) self.assertNotEqual(resp.status_code, 403) confirm_data = {'delete': 'yes'} resp = self.client.post(url, confirm_data) self.assertEqual(Item.objects.all().count(), 0) If I launch manage.py test on these tests I … -
Trigger long process in Django view
I have a view (start_job_view) in Django that should trigger a very long process. I'd like the view to return immediately and add a message to the user ("your job has started" using the message framework) and I'd like that when the long process terminates it sends a new message to the user ("your job has finished"). How can I do this? Note: I am not keen to add Celery to my project for this only task... -
How to monitor if the django sslserver is down
We are starting our server using django using the below command and it works fine. Python3 ./manage.py runsslserver www.abc.com:8443 —certificate abc.vet —key abc.pem But sometimes it automatically crashes . I would like to understand about how to monitor this , do we have any prebuilt monitoring in django itself The approach I have is a shell script where I can constantly check if process is up using Ps -ef Is there anything inbuilt in django to monitor if this sslsevrr is up ? Regards Tejas