Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: html input type=input and checkbox
I have a problem with send data from input type='number' to django view. I have a page with products, each of them has a checkbox and a quantity selection (input type='number') <form action="{% url 'create-order' %}" method="POST"> {% csrf_token %} <table class="table table-responsive table-borderless"> <thead> <th>&nbsp;</th> <th>Quantity</th> </thead> <tbody> {% for item in items %} <tr class="align-middle alert border-bottom"> <td> <input type="checkbox" id="check" name="item" value="{{ item.id }}"> </td> <td> <input class="input" min="1" value=1 type="number" name="quantity"> </td> </tr> {% endfor %} </tbody> </table> <div class="submitButton"> <button type="submit" class="lgbtn green">Go to order</button> </div> </form> Submit button go to view: def create_order(request): quantities = request.POST.getlist('quantity') items = request.POST.getlist('item') return JsonResponse({ 'quantities': quantities, 'items': items }) For example, I have 6 products with id = 1, 2, 3, 4, 5, 6. And if I choose 1, 2, 3 and set quantities: 3, 4, 5, then I get: items = [1, 2, 3] # it's OK quantities = [3, 4, 5, 1, 1, 1] # but I need [3, 4, 5] Ideally, I want items and quantities to be in the same object (For example [(1, 3), (2, 4), (3, 5)] or dict {1: 3, 2: 4, 3: 5}), but not necessarily, but in any … -
Modify one to many relationship in Django
I have two models in a one to one relationship: class GPSDevice(models.Model): device_name = models.CharField(max_length=50) class SessionGPS(models.Model): start= models.IntegerField() end= models.IntegerField() gps_device = models.OneToOneField(GPSDevice, on_delete=models.CASCADE, related_name="sesion_gps_device") I realized I have a mistake, a GPSDevice can have many SessionGPS. The problem is that to correct this I should delete the one to one relation in SessionGPS and add a ForeignKey field in GPSDevice: class GPSDevice(models.Model): device_name = models.CharField(max_length=50) session_gps = models.ForeignKey(SessionGPS, on_delete=models.CASCADE, related_name="sesion_gps") #added class SessionGPS(models.Model): foco = models.BooleanField(default=False) inicio_sesion = models.IntegerField() fin_sesion = models.IntegerField() #gps_device = models.OneToOneField(GPSDevice, on_delete=models.CASCADE, related_name="sesion_gps_device") deleted I have already data in the database and I fear that migrating this can produce a mess in the database as have happened before to me. Is there another way, like doing something in the SessionGPS model? -
Flutter Web Sign in with google WITHOUT firebase gives null access token
im trying to implement google sign in with my flutter application which sends the access token to my django back end. I have everything working except, I seem to keep getting null access token. I get the ID token but that I can't send to my back end. is there some problems with trying to get the access token for flutter web (WITHOUT firebase). GoogleSignInAccount? googleaccount = await _googleSignIn.signIn(); final googleauth = await googleaccount.authentication; everything normally works fine for my mobile apps but this is me not using firebase for web. any help would be appreciated. -
How to integrate FastAPI into Django project to use Django's ORM?
I am trying to integrate FastAPI into my Django project which shall serve as an extra app (reason is that I want to use Django's ORM). Now when I run uvicorn wsgi:app --reload it returns ModuleNotFoundError: No module named 'superpower' The only tutorial I found was this which is fairly outdated. Note that I included the FastAPI app electron into the INSTALLED_APPS in my django settings. Running the command uvicorn applications.electorn.wsgi:app --reload from the project root returns ModuleNotFoundError: No module named 'applications' -
A booking form in django that fills a dropdown menu with available times
I am able to display the available times in a dropdown menu, but when I submit the form it wont save to the database. I have two forms, the first the user selects a date and the second is where the available dates should show up in a dropdown menu. models.py Slots = ( ('9.00 - 10.00', '9.00 - 10.00'), ('10.00 - 11.00', '10.00 - 11.00'), ('11.00 - 12.00', '11.00 - 12.00'), ('12.00 - 13.00', '12.00 - 13.00'), ('13.00 - 14.00', '13.00 - 14.00'), ('14.00 - 15.00', '14.00 - 15.00'), ('15.00 - 16.00', '15.00 - 16.00'), ('16.00 - 17.00', '16.00 - 17.00'), ('17.00 - 18.00', '17.00 - 18.00'), ) class Booking(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slot = models.CharField(max_length=15, choices=Slots) booking_date = models.CharField(max_length=15, default='foo') def __str__(self): return f'{self.user} has booked a PT at {self.slot} on {self.booking_date}' views.py def DateView(request): form = DateForm(request.POST or None) if form.is_valid(): request.session["dateSelected"] = str( form.cleaned_data["booking_date"]) #sends user to next form return redirect('create') context = { 'form': form } return render(request, "bookingapp/date_form.html", context) def BookingView(request): instance = Booking(booking_date=request.session.get( 'dateSelected'), user=request.user) form = BookingForm(request.POST or None, instance=instance) # get all times from bookings on the provided date booked_slots = Booking.objects.filter(booking_date=request.session.get( 'dateSelected')).values_list('slot', flat=True) available_slots = [] for slot in … -
how to redirect to homepage in django-microsoft-auth if there is no next parameter?
I registered the app in Azure AD and configured my Django app so I can log in using a Microsoft account. The problem I am facing is changing the redirect from the admin page to my homepage. Mu redirect URI on Azure looks like this: https://localhost:8000/microsoft/auth-callback/ What do I need to do to change the redirect to https://localhost:8000/home -
Django ListView display items with for loop. Mirror every 2nd
I am working on a django product overview page. I display categories with a listview. I use a Bootstrap grid with two columns to display the categories as follows: picture | Info I now ant every 2nd column to be mirrored so the end resukt will be like this: Picture | Info Info | Picture Picture | Info How do I run a loop to make this work? My code looks like this: <div class='container'> {% for category in categories %} <!-- Check is subcategory exists. if not, filter on category. If it does exist filter on subcategory --> {% if category.sub_category is Null %} <a href="{% url 'academy:brandByCat_list' category.category_name %}"> <div class="row py-3 item-display"> <div class='col-md item-img'> <img src= {{category.category_picture.url}} class="img-fluid category-picture"> </div> <div class="col-md"> <h1 class='py-3'>{{category.category_name}}</h1> <p>{{category.category_info}} </div> </div> </a> {% else %} <a href="{% url 'academy:brandBySubCat_list' category.sub_category %}"> <div class="row py-3 item-display"> <div class='col-md item-img'> <img src= {{category.category_picture.url}} class="img-fluid category-picture"> </div> <div class="col-md"> <h1 class='py-3'>{{category.sub_category}}</h1> <p>{{category.category_info}}</p> </div> </div> </a> {% endif %} {% endfor %} Thanks for the help! -
Django how the link ManytoManyField data with FloatField data?
I have manytomanyfield inside my model.The manytomanyfield field lists the products in the products table. I want to enter the amount for each product I choose. How can I relate manytomanyfield to floatfield field? That's my model: ` class TaskSources(models.Model): id = models.AutoField(primary_key=True) user_task_id = models.ForeignKey(UserTask,on_delete=models.CASCADE) product_id = models.ManyToManyField(Product, verbose_name="Product",default=None) product_amount = models.FloatField(max_length=255,verbose_name="Product Amount") ` The form: ` class TaskSourcesForm(forms.ModelForm): class Meta: model = TaskSources fields = ['product_id', 'product_amount'] ` The views: ` @login_required(login_url="login") def addUserTask(request): user_task_form = UserTaskForm(request.POST or None,initial={'user_id': request.user}) task_sources_form = TaskSourcesForm(request.POST or None) if request.method == 'POST': if user_task_form.is_valid(): user_task = user_task_form.save(commit=False) user_task.author = request.user user_task.save() print(user_task.id) if task_sources_form.is_valid(): task_sources = task_sources_form.save(commit=False) task_sources.user_task_id = UserTask(id = user_task.id) task_sources.save() task_sources_form.save_m2m() messages.success(request,"Task added successfully!") return redirect(".") context = { "user_task_form" : user_task_form, "task_sources_form" : task_sources_form, } return render(request,"user/addtask.html",context) ` Thanks for care. I tried associating the two fields with each other, but I could not succeed. -
View didn't return HTTPResponse object
I was trying to create a blog app by following an online Django tutorial and while I was testing the sign-up page, I ran into a Value Error saying that the view did not return a HTTP response object. i tried everything but i could not find the answer as i am not a Django expert in the users app's views.py file was the code that threw the error from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') messages.success(request, f'Account Created for {username}') return redirect('blog-home') else: form = UserCreationForm() return render(request, 'users/register.html', {'form': form}) and this is the register template {% extends "myblog/base.html" %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Join Today! </legend> {{ form.as_p }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit"> Sign Up! </button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have an account? <a href="#" class="ml-2">Sign In!</a> </small> </div> </div> {% endblock content%} And this is the file structure of the project File Structure -
Django function missing 1 required positional argument despite its indication
i have the following two functions for outputting my views. Unfortunately, the variable test is not output but, the following error message is output: TypeError: selection() missing 1 required positional argument: 'test' index view def index(request): if request.method != 'POST': return render(request, './views/index.html') else: return redirect('selection', test=234) selection view def selection(request, test): print("TEST: ", test) return render(request, './views/selection.html') -
django restframework how to edit POST form
im working on api that resizes images. I want to upload just one file save it and resize and keep it in another folder. more on image HTML form asks me for 2 files, but I need to upload just one -
How can I access end points of Angular Application after deployment?
I have developed one app in Angular and it's running at local server very fine. Now, I have uploaded same app "Dist" folder to my server (linux) having WSGI + Apache server. I also run Django as backend server framework. I am doing this first time. I have made changes in Django and added index.html. The App is displaying only index.html just like local server. However, how can I access routes further? or end points? Any step by step guidance is available with full application? As mentioned, the app is working fine at local server with routes. http://localhost:4200/ or I want same with, http://my domain/end points Right now my domain is rightly pointing to index.html using Django framework. I have also inspected the page. There is no error in loading the page. Now only question is to access further routes- App module, and another modules. -
handling request priority in web sites
as a newbie in web programming i have an web project with a library study area rezervation system. i am doing the project with django and bootstrap5. so here is the question. how can i handle the rezervation request that come in the same time. there will be levels between my users like student, lecturer and guest. i want to give priority to student. also how can handle giving priority to between users who is in same level, is it (in same level prioritize) something i could do or does server decide what will be? if you give me any idea or title for search I would appreciate it. -
Passing a JSON object from Django to Javascript doesn't work properly
I need to pass a json object to a javascript script in Django. I used the method described here: Django: passing JSON from view to template Here is my view: def test_json(request): data = {} data['key'] = 'value' json_data = json.dumps(data) return render(request, 'test_json.html', {'json_data':json_data}) And my template: {{ json_data|json_script:"json_data" }} <script> const mydata = JSON.parse(document.getElementById("json_data").textContent); const keys = Object.keys(mydata); console.log(keys); </script> But the console output is this: [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15" ] It is like it doesn't recognize the keys but recognize every character of the json object as a key, it is like is not recognizing the JSON structure. If I change the script in the template like this: {{ json_data|json_script:"json_data" }} <script> // const mydata = JSON.parse(document.getElementById('json_data').textContent); //const keys = Object.keys(mydata); //console.log(keys) let text = '{ "employees" : [' + '{ "firstName":"John" , "lastName":"Doe" },' + '{ "firstName":"Anna" , "lastName":"Smith" },' + '{ "firstName":"Peter" , "lastName":"Jones" } ]}'; const obj = JSON.parse(text); const keys1 = Object.keys(obj); console.log(keys1) </script> Output: [ "employees" ] I get the key properly. It is like in the process of feeding the JSON from Django to the template the problem. … -
Can I use JavaScript Variables inside a Django Project
I have written some JavaScript Code for my Django Project. ` let current_theme = 0; function darkmode() { if (current_theme == 0) { document.body.classList.add("darkmode") current_theme = 1; } else if (current_theme == 1) { document.body.classList.remove("darkmode") current_theme = 0; } } function switchMode() { if (current_theme == 0) { document.body.classList.add("darkmode") current_theme = 1; const lightModeBox = document.querySelector(".wrapper"); lightModeBox.classList.remove("show"); } else if (current_theme == 1) { document.body.classList.remove("darkmode") current_theme = 0; const lightModeBox = document.querySelector(".wrapper"); lightModeBox.classList.remove("show"); } } ` When I start the project (python manage.py runserver) and I go into the DevTools it says: Error When I click on the first link it doesn't show the declaration of the Variable. Error JavaScript I tried declerate the Variable inside the function, but that doesn't work. How else can I implement this? Thank you :) -
working with django Viewflow by non-superusers not superuser
I'm learning django viewflow (non-Pro) and the all processes that I've been creating works for superuser users only is any way to use django viewflow by normal user or non superuser or another way to disable django permission checking for django viewflow please help me. error list when i refer to process list in app: ...\lib\site-packages\viewflow\flow\views\mixins.py", line 24, in dispatch return permission_required(self.flow_class._meta.view_permission_name, raise_exception=True) -
How to customize drf-yasg / drf-spectacular open api schema for aws gateway integration?
I have a requirement to integrate all the api urls in my django service with AWS gateway. I tried importing the open api spec(swagger json) generated by drf-yasg/drf-spectacular into aws. But this seems create only the resources and methods for the api in the gateway. I notice that, in order to setup the method request, integration request and integration response for all the methods automatically during import, the spec file needs to have aws gateway extensions mentioned for each method. This seems to be a laborious task to write as there are too many resources and methods in my api. So is there a way to customize the schema genertion with aws gateway extensions in it using drf-yasg/drf-spectacular module? or perhaps is there any alternate method to solve this problem? -
Raise an exception using mock when a specific Django model is called
I have a class based view inheriting from FormView with an overridden form_valid() method that I would like to test. As you can see, form_valid() is required to access the CustomUser model which is wrapped with a try and except. What I am trying to do is raise an exception whenever create_user is called, but I am having no success. The CustomUser has been created in the usual way via a CustomUserManager with a create_user method. CustomUser = get_user_model() class SignUpView(FormView): template_name = 'accounts/signup.html' form_class = SignUpForm def form_valid(self, form): try: self.user = CustomUser.objects.filter(email=form.cleaned_data['email']).first() if not self.user: self.user = CustomUser.objects.create_user(email=form.cleaned_data['email'], full_name=form.cleaned_data['full_name'], password=form.cleaned_data['password'], is_verified=False ) else: if self.user.is_verified: self.send_reminder() return super().form_valid(form) self.send_code() except: messages.error(self.request, _('Something went wrong, please try to register again')) return redirect(reverse('accounts:signup')) return super().form_valid(form) What I have tried: def test_database_fail(self): with patch.object(CustomUserManager, 'create_user') as mock_method: mock_method.side_effect = Exception(ValueError) view = SignUpView.as_view() url = reverse('accounts:signup') data = {'email': 'test@test.com', 'full_name': 'Test Tester', 'password': 'Abnm1234'} request = self.factory.post(url, data) request.session = {} request.messages = {} response = view(request) and .. def test_database_fail(self): CustomUser = Mock() CustomUser.objects.create_user.side_effect = CustomUser.ValueError view = SignUpView.as_view() url = reverse('accounts:signup') data = {'email': 'test@test.com', 'full_name': 'Test Tester', 'password': 'Abnm1234'} request = self.factory.post(url, data) request.session = {} request.messages … -
How to search through encrypted field?
I want to make a search through a model. I'm making that with django-filter. But in a field, I'm using django-mirage-field to encrypt and because of that when I make research using django filter it accepts the encrypted version. I don't know if it's possible to decrypt that. What should I do for searching that too? models.py from mirage import fields class Document(Model): file_path = models.CharField(max_length=250) converted_content = fields.EncryptedTextField() filters.py class CaseSearchFilter(django_filters.FilterSet): documents = django_filters.CharFilter(field_name='documents__converted_content__icontains',lookup_expr='icontains', label='Documents') -
Problems with global variable Django
I write a quiz web site. And i need to save answers from users. Some of them have similar username. This is my start function global new_user_answer user_group = request.user.groups.values_list() university = user_group[0][1] num = Answers.objects.all().count() new_user_answer = num + 1 new_line = Answers(id=new_user_answer, id_user=user) new_line.save() return redirect(f'/1') Here I create new line in my DB. Second function save user answers. number_answer = request.POST.getlist('answer') id_questions = request.POST.get('id') a = ', '.join(number_answer) user_group = request.user.groups.values_list() university = user_group[0][1] c = f'q{int(id_questions)}' data = Answers.objects.get(id=new_user_answer) setattr(data, c, a) data.save() if int(id_questions) < 47: return redirect(f'/{int(id_questions) +1 }') else: return render(request, 'index.html') Sometime I have a error 500 name new_user_answer is no define How I can solve this problem? -
Import into tables from Django import_export
I am struggling to populate models in Django by using ForeignKey. Let's say we have as in import_export documentation the following example: class Author(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=100) def __str__(self): return self.name class Category(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): name = models.CharField('Book name', max_length=100) author = models.ForeignKey(Author, blank=True, null=True, ) ... price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) categories = models.ManyToManyField(Category, blank=True) def __str__(self): return self.name How can I implement import_export module that can check if there is an existing author by name (not by id), that is not case sensitive, and that can generate a new author if it does not exist? As an example, let's say the CSV file looks like: name,author,...,price,categories J.R.R. Tolkien,Lord of the Rings,...,40,["cat1","cat2"] Also, if there is a DateTime field, how to generate that in ForeignKey table? -
Calculate next_run at every run for a Schedule Object
I have got a question about django-q, where I could not find any answers in its documentation. Question: Is it possible to calculate the next_run at every run at the end? The reason behind it: The q cluster does not cover local times with dst (daylight saving time). As example: A schedule that should run 6am. german time. For summer time: The schedule should be executed at 4am (UTC). For winter time: The schedule should be executed at 5am (UTC). To fix that I wrote custom logic for the next run. This logic is taking place in the custom function. I tried to retrieve the schedule object in the custom function and set the next_run there. The probleme here is: If I put the next_run logic before the second section "other calculations" it does work, But if I place it after the second section "other calculations" it does not work. Other calculations are not related to the schedule object. def custom_function(**kwargs) # 1. some calculations not related to schedule object # this place does work related_schedule= Schedule.objects.get(id=kwargs["schedule_id]) related_schedule.next_run = ... related_schedule.save() # 2. some other calculations not related to schedule object # this place doesn't That is very random behaviour … -
how to bypass makemigration error on django deployment on fly io
I am trying to deploy my django app on fly.io I followed all the steps from this site: https://testdriven.io/blog/django-fly/ On running flyctl launch, I get the following error: (venv) PS C:\Users\Dell\desktop\re\real_estate> flyctl launch Creating app in C:\Users\Dell\desktop\re\real_estate Scanning source code ? Overwrite "C:\Users\Dell\desktop\re\real_estate\Dockerfile"? No ? Choose an app name (leave blank to generate one): re automatically selected personal organization: dave ? Choose a region for deployment: Chennai (Madras), India (maa) Created app re in organization personal Set secrets on re: SECRET_KEY Creating database migrations Error failed running C:\Users\Dell\desktop\re\venv\Scripts\python.exe manage.py makemigrations: exit status 1 I havent made any changes to the database. I tried running python manage.py makemigrations. It gave following error: ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS').split(' ') AttributeError: 'NoneType' object has no attribute 'split' then I tried: ALLOWED_HOSTS = [""] CSRF_TRUSTED_ORIGINS = [""] which gave following error: File "C:\Users\Dell\desktop\re\venv\lib\site-packages\dj_database_url.py", line 88, in parse if "?" in path and not url.query: TypeError: a bytes-like object is required, not 'str' -
Django authenticate: usage in login vs. register (signup): how do they differ?
I have noticed that the Django authenticate is used in the same way in both the login view and the register view, both return a User object to be used in the login(). In the login view authenticate() uses username and password from the submitted form, then checks on user if the credentials are ok. if request.method == 'POST': username = request.POST['username'] password = request.POST['password1'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) The register view looks very similar to the login view. It gets the credentials from the submitted form and uses the user to login. if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(request, username=username, password=password) login(request, user) Both call user = authenticate(request, username=username, password=password). Apart from saving the form in the register view, what is the difference here? Because the login (I guess) is only checking that the credentials are valid, but the register is creating a new user and, since it is creating, the credentials are new data coming in. Am I getting this correctly? -
probleme with django and postgres interaction
Hello, I have a problem with django and postgres. This is the context : I’m currently trying to create a login system using django for the request and the session système and postgres to store the users. From my systeme i use a form to recover the information of my user, a sql query to see if my user has the right login. But there is a problem, whatever i try there is always a problem to my query. For mor context here is one of my tries : # In the DB : vna_v2_1=# SELECT * FROM vna_users; id | prenom | nom | admin | motDePasse | ----+---------+-----+-------+--------------------------------------------------------------------------------------------------+---------------- 1 | Aksel | C | t | 7fd785e85c8fab96f2d6d683cd3439c0b1b91e21891fb9a1c68ff4a1087e13cadecb661bc0c4d77eab215b423be01da7 | 2 | Mathieu | P | f | test | -> (The first user have a ashed password and the second doesn't) Query : SELECT * FROM vna_users WHERE prenom='Mathieu' AND nom='P' AND vna_users.motDePasse='test'; -> This is one of the query i’d try The error is : LINE 1: ..._users" WHERE prenom='Mathieu' AND nom='P' AND vna_users.... HINT: Perhaps you meant to reference the column "vna_users.motDePasse". -> This is the result i always have whatever i change Other query tha i …