Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django_python3_ldap using multiple OU in LDAP_AUTH_SEARCH_BASE
need some help... i'm using django_python3_ldap and it works fine when i change settings.py for each run using different LDAP_AUTH_SEARCH_BASE . userxxx is logged in with LDAP_AUTH_SEARCH_BASEOU=Users,OU=xxx Accounts,OU=ZZZ,DC=domain,DC=local useryyy is logged in with LDAP_AUTH_SEARCH_BASEOU=Users,OU=yyy Accounts,OU=ZZZ,DC=domain,DC=local i have tried with LDAP_AUTH_SEARCH_BASEOU=OU=Users,OU=xxx Accounts,OU=yyy Accounts,OU=ZZZ,DC=domain,DC=local and this gives noSuchObjec ..... 0000208D: NameErr: DSID-03100241, problem 2001 (NO_OBJECT), any hint? -
Optional related form in Django
I've a Customer model and an Address model. Customer model have a not-required ForeignKey to Address. Address model have all fields required. I want to have a form to enter customers with the ability to optionally enter an address, so i make a view with a form for each and send it to the template. Now i can't subbmit the customer because the required address fields prevent me from doing so. I would like to have a link to press to bring up the form with the address -
use npm library in django template
I want to use javascript npm module in django template. In javascript document, it says npm install waveform-playlist --save on cli and to use this line in code. import WaveformPlaylist from "waveform-playlist"; So, for now I write this script in template.html <script> import WaveformPlaylist from "waveform-playlist"; </script> this error comes. Cannot use import statement outside a module (at tracks:96:5) I think some basic idea is wrong? How can I use this type of javascript? -
html form table td value is not saving in database of django
I am trying to save td value which I am getting through Js in database using django. I am specifying name to td but its not saving giving me this error. :(1048, "Column 'total' cannot be null") td is in my footer(tfoot) Why my value is not saving in database on POST : html <tfoot> <tr> <th colspan="5"></th> <th id="total">Total :</th> <td name="total" id="total_value"></td> </tr> </foot> views.py total= request.POST.get('total') or total= request.POST['total'] -
FOREIGN KEY constraint failed when any staff_user saves any object in the admin page
saving any object as admin (the first superuser i created from the cli) in the admin page works just fine. but whenever any other staff_user (whether he is a superuser or not ) tries to save any object i get an error django.db.utils.IntegrityError: FOREIGN KEY constraint failed only the admin user mentioned aboove can do so, this is the traceback Traceback (most recent call last): File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 242, in _commit return self.connection.commit() sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/asgiref/sync.py", line 472, in thread_handler raise exc_info[1] File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 38, in inner response = await get_response(request) File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 231, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/asgiref/sync.py", line 435, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/usr/lib/python3.8/asyncio/tasks.py", line 455, in wait_for return await fut File "/usr/lib/python3.8/concurrent/futures/thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/asgiref/sync.py", line 476, in thread_handler return func(*args, **kwargs) File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 233, in inner … -
Django/Python: post_save signal - expected string or bytes-like object
I have a post_save signal which is failing with 'expected string or bytes-like object'. I am not sure why, it is being caused by the call to create_user below:- This is to create a user within a tenant schema for a newly created tenant: @receiver(post_save, sender=Client) def create_user(sender, instance, created, **kwargs): if created: tenant=instance with schema_context(tenant): name = 'name' email = 'name@email.com' password = 'passwordexample' user = CustomUser.objects.create_user(name, email, password) The underlying user manager which throws the exception is def create_user(self, name, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) name = self.normalize_email(name) email = self.normalize_email(email) user = self.model(name=name, email=email, **extra_fields) user.set_password(password) user.save() return user This seems to fail on user.save() in the above manager Any help or pointers greatly appreciated Thank you -
How can i select needed db for Pytest? I have 2 - one remote, one local. I need pytest to be started on local
The default db is cloud one. And when pytest tries to create a temporary data it got permissions error. So i want to create a second database to be used with pytest. How can i select this database in pytest config? DATABASES = { 'default': { 'NAME': config['database']['name'], 'ENGINE': '...', }, 'tests_db': { "NAME": "tests_db", "ENGINE": 'django.db.backends.sqlite3', } } -
Django - showing amount of objects pointing to a key?
I have a very noob question, in fact, so noob, that despite there being multiple answers on the topic, I simply cant implement it to my project. I have a list of job offers, and my problem is to list how many offers are in each job offer. For example Offer: welder - we have 7 positions models.py from django.db import models from django.contrib.auth.models import User from django.db.models import Count STATUS = ( (0,"Inactive"), (1,"Active") ) class Offer_type(models.Model): type = models.TextField() class Meta: ordering = ['-type'] def __str__(self): return self.type class Offer_general(models.Model): offer_name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) status = models.IntegerField(choices=STATUS, default=0) type = models.ForeignKey(Offer_type, on_delete= models.PROTECT) class Meta: ordering = ['-id'] def __str__(self): return self.offer_name class Offer_localization(models.Model): localization = models.TextField() class Meta: ordering = ['-localization'] def __str__(self): return self.localization class Offer_details(models.Model): slug = models.SlugField(max_length=200, unique=True) localization = models.ForeignKey(Offer_localization, on_delete= models.PROTECT, default="Opole") fk_offer_general_id = models.ForeignKey(Offer_general, on_delete= models.PROTECT) updated_on = models.DateTimeField(auto_now= True) content = models.TextField() requirements = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-id'] def __str__(self): return self.slug views.py from django.shortcuts import render from django.views import generic from django.db.models import Count from .models import Offer_general from .models import Offer_details # Create your views … -
find unique values in django
I am a beginner with Django. My question is, How can i retrieve all unique category name in search_result? My models.py class Category(models.Model): category_name = models.CharField(max_length=20, unique=True) logo = models.ImageField(upload_to='Category') slug = models.SlugField(unique="True") def __str__(self): return self.category_name class Product(models.Model): product_name = models.CharField(max_length=50, blank=False) category = models.ForeignKey(Category, on_delete=models.CASCADE, default="", blank=True, related_name="Products") price = models.FloatField(blank=False, default=0.00, validators=[MinValueValidator(0.0)], help_text='Price Can not be Less than Zero.') def __str__(self): return self.product_name My views.py class SearchView(TemplateView): template_name = "productstemplate/products.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user_search = self.request.GET['product'] search_result = Product.objects.filter(Q(product_name__icontains=user_search) | Q(category__category_name__icontains=user_search)) context['products'] = search_result context['categorys'] = ===>> Here <<=== return context -
How to use the parameter queryset of model formset in ModelForm?
# this is my model class Creator(models.Model): name = models.CharField(max_length=50) class Article(models.Model): title = models.CharField(max_length=688, blank=True) creator = models.ForeignKey(Creator, on_delete=models.CASCADE) class ArticleCoAuthor(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) co_author = models.CharField(max_length=190) # code ArticleFormset = modelformset_factory(Article, form=forms.ArticleForm, extra=1, can_delete=True) article_formset = ArticleFormset( prefix="article", queryset=creator.article_set.prefetch_related("articlecoauthor_set").all() ) # this is my form class ArticleForm(forms.ModelForm): ...... I want to express all the data of the ArticleCoAuthor referenced when representing a row of Articles. How can I convey the "co_author" value, which is the result of "querieset" in "article_formset", and use it in "ArticleForm"? -
Django HTML button on-click invoke backend function
im trying to add to my html a button that appears only on certain events, that works for me but i want to add a onclick script/function that will invoke a backend view.py function that deletes the specific room on click, the room model is : owner(fk), name, slug. and the user model is : username password1 password2. i just need to know how to invoke an onclick event that will call the backend function in my views. rooms.html {% extends 'core/base.html' %} {% block title %} Rooms | {% endblock %} {% block content %} <div class="main"> <h1>Rooms</h1> </div> <div class="rooms-container"> {% for room in rooms %} <div class="room"> <div class="room-info"> <h1 class="room-title">{{ room.name }}</h1> <a href="{% url 'room' room.slug %}" class="room-join">Join Room</a> {% if request.user == room.owner %} <button class="room-delete" id="roomDelete">Delete Room</button> {% endif %} </div> </div> {% endfor %} </div> {% endblock %} {% block scripts %} <!-- todo: add delete room button functionality. --> {% endblock %} ``` views.py from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render from django.contrib import messages from .models import Room, Message @login_required def rooms(request): if request.method == 'POST': room_owner = request.user room_name = request.POST['room-name'] if not Room.objects.filter(slug … -
Fetching Variable from views.py file to html file
I am writing a simple code to fetch the variable from HTML file. Here is my code: views.py file def VariableView(request): context = {'firstName: Muhammad' , 'lastName: Khan'} return render(request, 'Variable.html',context) Variable.html file: <body> <h1>VARIABLE.HTML</h1> <h2>{{firstName | upper}}</h2> </body> I get an error at my console: TypeError at /MyApp/variable/ context must be a dict rather than set. Request Method: GET Request URL: http://127.0.0.1:8000/MyApp/variable/ Django Version: 3.2 Exception Type: TypeError Exception Value: context must be a dict rather than set. Exception Location: C:\Users\DELL\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\django\template\context.py, line 268, in make_context Python Executable: C:\Users\DELL\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\python.exe Python Version: 3.7.9 Python Path: ['C:\\Users\\DELL\\Desktop\\DJango\\mysite', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\\python37.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0', 'C:\\Users\\DELL\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python37\\site-packages', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\\lib\\site-packages'] Server time: Fri, 29 Jul 2022 08:23:36 +0000 -
Django runserver seems to run two instances
I am working on a project where users can post and comment. I made one app called core. In core/views there is a file comments.py There is a class inside it like this: class CommentList(APIView): authentication_classes = [BasicAuthentication, TokenAuthentication] permission_classes = [IsAuthenticated] print("hello") def get(self, request: request.Request, pub_id: str) -> Response: pass Also my core/views/__init__.py has this: from .comments import * Now when I run python3.10 manage.py runserver, it prints 'hello' two times. I expect hello to be printed once. Any possible explanation ? -
How to submit a form in Django ModelForm without changing the password value?
I'm new to Django and want to ask for some advice: The user information should change in the form, but if I do not fill "password" and "confirm_password" fields, an empty string is sent to the database. I tried to make changes to the password validator but did not figure out how to send data to the database, without the value of the "password" and "confirm_password" fields. As far as I understand, the most correct thing is to change the save method, but I don't quite understand how to do it correctly. view.py def change_user_data(request): message = '' if request.method == "POST": form = ChangeUserForm(request.POST, instance=request.user) if form.is_valid(): form.save() message = 'Изменения успешно применены!' else: form = ChangeUserForm(instance=request.user) return render(request, 'users/change_user_data.html', context={'form': form, 'message': message}) form.py class ChangeUserForm(forms.ModelForm): name = forms.CharField(required=False, label="Имя", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'name'})) surname = forms.CharField(required=False, label="Фамилия", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'surname'})) nickname = forms.CharField(required=False, label="Псевдоним", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'nickname'})) email = forms.EmailField(required=False, label="Адрес электронной почты", widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder':'email'})) address = forms.CharField(required=False, label="Адрес", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'address'})) card_id = forms.CharField(required=False, label='Номер банковской карты', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'card_id_number'})) language = forms.ChoiceField(required=False, label='Язык', choices=(('ua', 'Українська мова'), ('ru', 'Русский язык')), initial='ru', widget=forms.RadioSelect()) sex = forms.ChoiceField(required=False, label='Пол', choices=(('male', 'Мужской пол'), ('female', 'Женский пол')), … -
How to ignore more than 50% of transactions logging in new relic for Django applications
I am working on integrating new relic with a Django application. Now, i do not wish to monitor the entire application, to be more specific I do not need more than 50% of the application to send data to new relic. If the transactions to be ignored were less I could have used agent.ignore_transaction(flag=True). Since the number of transactions to be ignored is huge, I am looking for some other efficient and easy method. Can I please get some help on achieving this, and if there is any solution available please quote an example. Thank you Regards -
Unable to update a JsonField in Postgres using raw queries in Django
I'm trying to run this code after a migration. cursor.execute(f'UPDATE abc_model SET "abc_temp" = \'{{"0" : "{abc}" }}\' WHERE abc_model."id" = {id}') I'm getting this error when using a dump of the following version: -- Dumped from database version 9.5.25 -- Dumped by pg_dump version 9.5.25 django.db.utils.DataError: invalid input syntax for type json LINE 1: ...abc_model SET "abc_temp" = '{"0" : "M... ^ DETAIL: Character with value 0x0a must be escaped. CONTEXT: JSON data, line 1: ...cum current detected the deviation from baseline. It works fine when using a dump of the following version: -- Dumped from database version 12.10 (Ubuntu 12.10-1.pgdg18.04+1) -- Dumped by pg_dump version 14.2 (Ubuntu 14.2-1.pgdg18.04+1) -
insert string after to the 4th length of the string - python
Hello Experts I'm a newbie to python, what I'm trying to achieve is to add '/' after to 4th length of the string Example: my string is having a 6-length '202204' so I'm trying to add '/' after on the 4th string to make it like this 2022/04. Currently, this is the code that I'm trying to achieve to add / to return the 4lenght as year and the remaining 2 as month. def is_datetext_valid(self, date_text): date_format = '%Y/%m' if date_text is None: return False, 0, date_format, date_text date_text = date_text.replace("月", "") date_text = date_text.replace("年", "" if len(date_text) == 5 else "/") date_text = date_text.replace("頃", "") # date_text = date_text.replace("","" if len(date_text) == 6 else '/') date_text_len = len(date_text) try: if date_text_len is 4: date_format = '%Y' -
Create foreign key objects inside serializer
I've two model: class Author(models.Model): name = models.CharField(max_length=255) class Books(models.Model) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books_author') name = models.CharField(max_length=255) Now, I need to create an author and it's related books in a single request inside create serializer. The incoming data would look something like this: { "author": "John Doe" "books":[ { "name": "Life of Pie" }, { "name": "Lord of the rings" } ] } How can I do it without using a for loop inside the create serializer? -
How to save button value in Django database?
I done a part of save a value in button to the database when i click that button.but i want an another option : 1)Select the particlular option you want 2)then click an next button which redirect to next page and also save the value which a already selected -
Dynamic QR cod generation in django template python
I am stack to generate dynamic cod for this class in Django template(print_id_Card.html),can any one to help me in this problem. this is my model for witch I am going to create QR cod. class Customer2(models.Model): Customer_Name=models.CharField(max_length=30) Customer_Address=models.CharField(max_length=100) Customer_Phone=models.IntegerField() Customer_Email=models.EmailField(max_length=50) Picture=models.ImageField(upload_to='Images',blank=True, null=True) QR=models.ImageField(upload_to='Images',blank=True, null=True) class Meta: db_table="Customer_Table" This is my Urls.py path('Customer_print_Id/<int:id>',views.print_customer_id) And this is My views.py def print_customer_id(request,id): obj=Customer2.objects.filter(id=id) return render(request, 'Print_Id_Card.html',{'obj':obj,'media_url':settings.MEDIA_URL}) And this is my template, in this template I want to generate QR cod for that specific Customer. <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> {% load static %} <link href="{% static 'CSS/bootstrap.min.css'%}" rel="stylesheet"> <link href="{% static 'Images/'%}" rel="stylesheet"> </head> <body> <div class="container"> <div class="card" style="width:360px; margin-left: 400px; margin-top:50px;"> {% for ob in obj %} <div class="card-body" style="font-weight: bold; text-align: center; border-radius: 5px;"> <P>Customer Idivisual Card</P> <img class="card-img-top" src="{{media_url}}{{ob.Picture}}" alt="Card image" style="width:120px" ,height="100px"><br> <label for="id">Customer ID: {{ob.id}}</label><br> <label for="Name">Name: {{ob.Customer_Name}}</label><br> <label for="Address">Address: {{ob.Customer_Address}}</label><br> <label for="Phone">Phone: +93{{ob.Customer_Phone}}</label><br> <label for="Email">Email: {{ob.Customer_Email}}</label><br> <div></div><img class="card-img-top" src={{X}} alt="Card image" style="width:120px" ,height="10px"><br> </div> {%endfor%} </div> </div> <br> </div> </body> </html> -
ModuleNotFoundError: No module named 'api.apps'
I'm following a Tech with Tim tutorial https://www.youtube.com/watch?v=JD-age0BPVo&list=PLzMcBGfZo4-kCLWnGmK0jUBmGLaJxvi4j&index=1&t=373s, and when I try run makemigrations I keep getting the error ModuleNotFoundError: No module named ‘api.app’ Upon executing the command in the terminal, I received this error. ryanmg@Ryans-MacBook-Pro music_controller % python3 manage.py makemigrations Traceback (most recent call last): File "/Users/ryanmg/Documents/Coding/React-Django-Project/music_controller/manage.py", line 22, in <module> main() File "/Users/ryanmg/Documents/Coding/React-Django-Project/music_controller/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/config.py", line 213, in create mod = import_module(mod_path) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'api.apps' This is my settings.py file. I have added the reference "api.apps.ApiConfig" INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig', 'rest_framework', ] This is my apps.py file from django.apps import AppConfig class ApiConfig(AppConfig): # default_auto_field = 'django.db.models.BigAutoField' name = 'api' My directory listings are as follows image of directory listings -
Why isn't the data from the input file transferred? Django
I want to check the data I received from the request, but the data in the input(file multiple = "True")tag is not transferred. print(request.FILES.get('input_tag_type_file_name')) >> None I dont want to form field. Because i cann't expect how many inputs i will recieve -
django how to save current user from views.py
I have a table called items office_id , sem ,sy ,remarks, recorded_by And table called customuser userid, password, email How can i save the current user's userid here at table items > recorded_by for now this is my views.py class Add(LoginRequiredMixin, CreateView): form_class = CreateForm model = ClearanceItem template_name = 'clearance/add.html' def form_valid(self, form): form.instance.recorded_by= self.request.user return super().form_valid(form) -
query to django model to compare daily sale over previous day (compare two row of database model)
I have a django model that is "DailyReport" of the companies sale I want to find out company sale change over the previous day. the model that i define is like that: class DailyReport(models.Model): company = models.CharField(max_length=50) sale = models.IntegerField() date = models.DateField() How can i figure out this issue to add new column for every report that represent change rate over the previous day -
Django model creation insists I use auth_user when I created a custom user type
The code that is causing an error: obj = CustomUser.objects.all()[0] o = Order(portfolio={'stocks': 'appl'}, user=obj, money=1) o.save() I'm trying to create a new order object which uses a CustomUser instance CustomUser is defined as follows: class CustomUser(AbstractUser): id = CharField(max_length=100, default=NO_ACCOUNT) Order is defined as follows: class Order(models.Model): portfolio = models.JSONField(default=dict) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) money = models.IntegerField(default=0) I would expect that I can create this object but the error I'm getting is: insert or update on table "deploy_order" violates foreign key constraint "deploy_order_user_id_b435189b_fk_auth_user_id" DETAIL: Key (user_id)=(2) is not present in table "auth_user". I'm not sure why auth_user gets looked up when I clearly am using my custom user type. My migrations are up to date.