Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upload webscrapped images from folder to database Django
I'm webscrapping data about ski resorts from a site, also getting some pictures. I am saving those pictures in a folder and after that i'm getting them in SQLite database through an imageField. The bad part is that they don't work directory = r'C:\Users\tiberiu.ghimbas\Documents\Resorts img5' image_list = [cv2.imread(file) for file in glob.glob(r'C:/Users/tiberiu.ghimbas/Documents/Resorts img5/*.png')] This list is then looped and insertet item by item. I'm doing all the correct settings for handling images and media files. I know that by going the classic way of uploading images through a form will get you in the database the path to the image from de media/"upload_to = 'filename'" folder but going by my way i'm getting only them image name. How can i solve that ? -
How can I add an attribute to a queryset in Django
I've got a Django 2.2.28 legacy application running under Python 3.7.7. I've got a queryset I'd like to add data to that's not from the database, but generated by Python. So something like this: for item in queryset.iterator(): item.new_property = python_generated_property_value() I want this new_property to be available in a template. Any suggestions/ideas would be greatly appreciated! -
Django all-auth or django multiple user login
if patient login with his login link then he automatic go to patient dashboard same as if doctor login he also go his dashboard. And their data save individually. They cannot access their dashboard also. I want when a client or doctor signup then their data saved separately. How i can do it using django or django allauth. -
how to add bootstrap classes to admin.py?
I don't understand why the form that I am creating in forms.py EditProfileForm to be able to place bootstrap classes in my "edit profile" cannot be seen. The form that I have in the "edit profile" works quite well, but when placing the form.py nothing happens, you don't see the classes. can you help me to know what happens? models.py class CustomUser(AbstractUser): phone1=models.IntegerField(default=0) phone2=models.IntegerField(default=0) fax=models.IntegerField(default=0) website=models.CharField(max_length=100,default=0) socialMedia1=models.CharField(max_length=100,default=0) socialMedia2=models.CharField(max_length=100,default=0) socialMedia3 = models.CharField(max_length=100,default=0) alternativeContact=models.CharField(max_length=100,default=0) country = models.CharField(max_length=100, default=0,choices=COUNTRIES) address=models.CharField(max_length=100, default=0) city=models.CharField(max_length=100,default=0) state=models.CharField(max_length=100,default=0) zip=models.CharField(max_length=10,default=0) tax_percentage=models.IntegerField(default=0) def __str__(self): return self.phone1 form.py class EditProfileForm(UserChangeForm): phone1=forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) phone2=forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) fax=forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) website=forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) socialMedia1=forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) socialMedia2=forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) socialMedia3 = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) alternativeContact=forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) country = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) address=forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) city=forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) state=forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) zip=forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) tax_percentage=forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model=CustomUser fields=('phone1','phone2','fax','website','socialMedia1','socialMedia2','socialMedia3','alternativeContact','country','address','city','state', 'zip','tax_percentage') admin.py class CustomUserAdmin(UserAdmin): add_form = UserCreationForm form=EditProfileForm # form=UserChangeForm model=CustomUser list_display = ['pk','email','username','first_name','last_name'] add_fieldsets = UserAdmin.add_fieldsets+( (None,{'fields':('email','first_name','last_name','image','location','phone1','phone2','fax','website', 'socialMedia1','socialMedia2','socialMedia3','alternativeContact','country','address', 'city','state','zip','tax_percentage')}), ) fieldsets = UserAdmin.fieldsets+( (None,{'fields':('email','first_name','last_name','image','location','phone1','phone2','fax','website', 'socialMedia1','socialMedia2','socialMedia3','alternativeContact','country','address', 'city','state','zip','tax_percentage')}), ) admin.site.register(CustomUser) -
Can I Extend My Template Based on a Condition -Django
I have a template that needs to use separate base templates depending on whether a user is a system admin or a regular administrator. The main difference between the two templates is that one contains more nav bar items and links to other portions of the app. I'd like the system to recognize whether a user is a system admin or regular admin and extend the correct base template off of that test. I know this can be accomplished by creating a second template and doing something like this in the views.py file: if sysAdmin == True: template = loader.get_template('app/template1.html') else: template = loader.get_template('app/template2.html') There are multiple shared views between the two user groups and I would rather not have 4 sets of templates that are almost completely identical. I'd prefer to do something like: {% if sysAdmin == True %} {% extends "app/sysAdminBase.html" %} {% elif sysAdmin == False %} {% extends "app/adminbase.html" %} {% end if %} However, this throws the error Invalid block tag on line 3: 'elif'. Did you forget to register or load this tag? Is this possible or will I need to create duplicate templates? Thank you -
Create Python file in Visual Studio 17.2 and auto-reaload the server
After creating the Django or Flask project in VS 2022 and run the server. The button Add only have option -> Django app. Only stopping the server the option add New Item is enabled. For instance I'd like to create a new Python file while the server in running like in PyCharm. How it can be done in VS without stopping the server? And after that how to manage the Django server restart automaticaly? -
Index a foreign key in Django Models
I want to index a very common query in a project that involves a CharField and ForeignKey. I have a bottleneck with this query and I am trying to optimize it. I have this: class Bill(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) category = models.CharField(max_length=200, null=True, blank=True) ... I added this to try to improve the performance: class Meta: indexes = [ models.Index(fields=['category', 'company']), ] But the result is the same, the query is: models.Bill.objects.filter(company=company, category='recibida') Is there something else that I could improve? Is this indexing well done? -
Why is Django not picking up my admin override?
I'm trying to override the Django admin's index method for my api project, following the guide here. In api/admin.py, I have class ApiAdminSite(admin.AdminSite): def index(self, request, extra_context=None): raise Exception('to see if I am even being called') # I remove this when satisfied .... admin_site = ApiAdminSite() admin_site.register(MaxImpactFundGrant, MaxImpactFundGrantAdmin) admin_site.register(Evaluation, EvaluationAdmin) # and other model registrations In api/apps.py, I have from django.apps import AppConfig from django.contrib.admin.apps import AdminConfig class ApiConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'api' class ApiAdminConfig(AdminConfig): default_site = 'api.admin.ApiAdminSite' In api/../settings.py, aka the folder above my app, aka not the settings file the guide specifies, I have INSTALLED_APPS = [ 'api.apps.ApiConfig', 'modeltranslation', 'api.apps.ApiAdminConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] And when I load the admin index page, it loads ok, but just hasn't registered any of my models: So maybe I've got the wrong settings.py? But I've tried creating one in the api folder and adding just that list to it, and nothing changed. I also tried editing the top level urls.py file to specify the new admin, though I had to hack it to give the new admin a 'site' attribute: from django.urls import path, include from django.contrib import admin from api.admin import admin_site admin_site.site = admin.site urlpatterns … -
Djoser permissions override
i have this endpoint /auth/users/ which shows all the users and their data and only the admin can see all the users data ,the current user can only see his data(email,first_name,last_name...) so I want any user to get the data of all the users I changed the djoser settings to this but still I get only the current user data how can I fix this? DJOSER = { 'PERMISSIONS': { 'user': ['rest_framework.permissions.IsAuthenticated'], 'user_list': ['rest_framework.permissions.IsAuthenticated'], }, 'SERIALIZERS': { 'user_create': 'core.serializers.UserCreateSerializer', 'current_user': 'core.serializers.UserSerializer', 'user': 'core.serializers.CurrentUserSerializer', } } ``` -
Display the id of an object in many to many relation in Django admin
I have a model(VariationPrice) in my Django app which has many to many relation with other model(Variation). Under Django Admin VariationPrice, one sees the variations field with many Variations inside it. Is it possible to display the Variation id (Variation.id) along with the Variation name in many to many field of django admin? class VariationPrice(models.Model): price = models.IntegerField() product = models.ForeignKey(Product, on_delete=models.CASCADE) variations = models.ManyToManyField(Variation, blank=True) -
how to install django-auth-ldap
so basicly i'm trying to install django-auth-ldap to my system, but it always crashes with errors i use python3.10 on Ubuntu 20.04 with Django 4.0.4 (.venv) user@vmlist:~/test/vmlist_frontend$ pip3.10 install django-auth-ldap Collecting django-auth-ldap Using cached django_auth_ldap-4.1.0-py3-none-any.whl (20 kB) Collecting python-ldap>=3.1 Using cached python-ldap-3.4.0.tar.gz (376 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Requirement already satisfied: Django>=2.2 in /home/user/test/.venv/lib/python3.10/site-packages (from django-auth-ldap) (4.0.4) Requirement already satisfied: sqlparse>=0.2.2 in /home/user/test/.venv/lib/python3.10/site-packages (from Django>=2.2->django-auth-ldap) (0.4.2) Requirement already satisfied: asgiref<4,>=3.4.1 in /home/user/test/.venv/lib/python3.10/site-packages (from Django>=2.2->django-auth-ldap) (3.5.2) Collecting pyasn1-modules>=0.1.5 Using cached pyasn1_modules-0.2.8-py2.py3-none-any.whl (155 kB) Requirement already satisfied: pyasn1>=0.3.7 in /home/user/test/.venv/lib/python3.10/site-packages (from python-ldap>=3.1->django-auth-ldap) (0.4.8) Building wheels for collected packages: python-ldap Building wheel for python-ldap (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for python-ldap (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [101 lines of output] /tmp/pip-build-env-kzs5bz2f/overlay/lib/python3.10/site-packages/setuptools/config/setupcfg.py:459: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead. warnings.warn(msg, warning_class) running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-310 copying Lib/ldapurl.py -> build/lib.linux-x86_64-cpython-310 copying Lib/ldif.py -> build/lib.linux-x86_64-cpython-310 creating build/lib.linux-x86_64-cpython-310/ldap copying Lib/ldap/cidict.py -> build/lib.linux-x86_64-cpython-310/ldap copying Lib/ldap/functions.py -> build/lib.linux-x86_64-cpython-310/ldap copying Lib/ldap/logger.py -> build/lib.linux-x86_64-cpython-310/ldap copying Lib/ldap/async.py -> build/lib.linux-x86_64-cpython-310/ldap copying Lib/ldap/resiter.py -> build/lib.linux-x86_64-cpython-310/ldap copying Lib/ldap/modlist.py -> build/lib.linux-x86_64-cpython-310/ldap copying Lib/ldap/ldapobject.py -> build/lib.linux-x86_64-cpython-310/ldap copying Lib/ldap/pkginfo.py … -
Check Overlapping intervals integerfield validation django python
can anyone help me how to solve overlapping validation in django moldel.py start = IntegerRangeField() end = IntegerRangeField() form.py class CheckForm(forms.ModelForm): def clean(self): start=cleaned_data.get("start") end = cleaned_data.get("end") conflicts = Check.objects.filter( start_bbch__lte=end, end_end__gte=start, ) if any(conflicts): raise forms.ValidationError(_("overlapping not allowed" % conflicts.count())) return cleaned_data -
django edit and update multiple object of one form
i have one form for add information to table and in craete view i can copy the form as much i want and insert it to the table like this: my form and can copy them but when i want to edit and update them how can i pass the queryset to form and show them in template i write my view like this and choose formset but my formset never show in template def machineedit(request, id): querymachine = machinefixedmodel.objects.get(pk=id) querywarranty = warranty.objects.get(machine_id=id) # querygallery = galleryModel.objects.filter(machine_id=id) querynet = netpriod.objects.filter(machine_id=id) newadform = modelformset_factory(netpriod, form=netpriodfrom,fields=('activity', 'material'), extra=0) # print(newadform) formmachine = MachinefixedForm(instance=querymachine) formwaranty = warrantyForm(instance = querywarranty) # formgallery = galleryform(instance = querygallery) # formblueprint = galleryform(instance = querygallery) # formnetpriod = netpriodfrom(instance=querynet) formnetpriod = newadform(request.POST or None, querynet) context ={'formmachine': formmachine, # 'formgallery': formgallery, 'formwarranty': formwaranty, # 'formblueprint': formblueprint, 'formnetpriod': formnetpriod,} return render(request, "edit.html", context) is the i choose the right way or not can anyone help me please... -
Showing many to many field as checkbox in template with createview
View: class addrecipe(CreateView): model = Recipe template_name = 'recipebook/addrecipe.html' fields = '__all__' Model: class Recipe(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=200) servings = models.IntegerField(default=1, blank=False) tools = models.ManyToManyField(Tool) def __str__(self): return self.name Template: {% extends 'recipeBook/base.html' %} {% block title %}Add New Recipe{% endblock title %} {% block header %} <header> <a href="{% url 'recipeBook:recipe_list' %}">Recipe list</a> </header> {% endblock header %} {% block content %} <h1>Add New Recipe</h1> <form action="" method ="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Add"> </form> {% endblock content %} Currently the tools field displays as follows: I am trying to find a way to display all the tools in the database as a checklist where the user can simply check off each tool that is relevant to the recipe they are adding, or add a new tool if it's not already in the list. Is there a way to achieve this? -
Django template if inside a for loop with list indexing
I want to fetch the values of a list using indexes of a list. I have a list in views.py views.py def home(request): my_list=[("xy","abc","abcd"),("abcd","abc","xy")] context={ "list"=my_list} return render(request, 'index.html',context) index.html {% for id in list%} {% if id.1 =='abc' %} {{id.0}}="Core user" {{id.0}} {% else %} {{id.0}} {% endif %} {% endfor %} So if the condition satisfies, the new values of the list would be [("xy","Core user","abcd"),("abcd","Core user","xy")] I am getting syntax errors for this. Please let me know what am I doing wrong and how to resolve this? -
Django and django rest framework saving profile information
How is possible to save profile information as I am using django rest api to login a user and the response which I am getting is with the help of requests library .what I want is to save the response and show in profile page .How can I achieve this in django?should I use cookies or session for this. -
If fetch returns object with multiple attributes (ie. object.exists and object.message) how can I use them after fetch is done?
After fetch returns object it logs it perfectly and I can see all attributes in the object. I can even change the html in the page using all the attributes. login_button=document.getElementById('submit-login'); login_form=document.getElementById('login-form'); message=document.getElementById('message'); login_button.addEventListener('click',async (e)=> { e.preventDefault(); form=new FormData(login_form); let response = await fetch('/',{ method:'POST', body: form, headers:{ 'X-CSRFToken':document.cookie, // 'X-Requested-With': 'XMLHttpRequest', }, }); let processed_response=await response.json(); console.log(processed_response); if (processed_response.exists){ console.log('success'); message.classList.remove('failure'); message.classList.add('success'); } else{ message.classList.remove('success'); message.classList.add('failure'); } message.firstElementChild.innerHTML=processed_response.message; setTimeout((processed_response) => { window.location=processed_response.next; },1000); }); However, when I try using the setTimeout function it logs the following: Uncaught TypeError: can't access property "next", processed_response is undefined And well I'm not able to use the attribute from the object in the setTimeout function. Is there something I'm missing. This is my first time dealing with async and fetch/promises so sorry for any low quality code here. Thanks in advance. -
Django Upload pdf then run script to scrape pdf and output results
I am attempting to create a Django web app that allows the user to upload a pdf then have a script scrape it and output and save certain text that the script scraped. I was able to find some code to do the file upload part. I have the script to scrape the pdf. Not sure how to tie them togther to accomplish this task. views.py from django.shortcuts import redirect, render from .models import Document from .forms import DocumentForm def my_view(request): print(f"Great! You're using Python 3.6+. If you fail here, use the right version.") message = 'Upload PDF' # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() # Redirect to the document list after POST return redirect('my-view') else: message = 'The form is not valid. Fix the following error:' else: form = DocumentForm() # An empty, unbound form # Load documents for the list page documents = Document.objects.all() # Render list page with the documents and the form context = {'documents': documents, 'form': form, 'message': message} return render(request, 'list.html', context) forms.py from django import forms class DocumentForm(forms.Form): docfile = forms.FileField(label='Select a file') models.py from django.db import models class Document(models.Model): docfile = … -
how to make a view where user can select text, highlight and save as input for a readonly text field in django?
I am new to web programming and testing out a simple blog. What I am trying to make is a Django view where non editable text field can get input only as highlight and maybe able to accept some comments on each highlighted chunk.(e.g "Google docs, suggest edit and comment" style). Can anyone pls tell me what kind of view(DetialView or any others?) I would need to implement in views.py? Thanks in advance. -
loading a file in my javascript file and using the js file in django
So im trying to use three js in a django project in the javascript file i am loading files to use in my 3d scene when i build it creates a functionning website because it knows where everything should be how ever i am kinda struggling to make it work in a django project please help and i would appreciate it /* [18/May/2022 17:40:32] "GET /textures/environmentMaps/1/ny.jpg HTTP/1.1" 404 2449 Not Found: /textures/environmentMaps/1/py.jpg [18/May/2022 17:40:32] "GET /textures/environmentMaps/1/px.jpg HTTP/1.1" 404 2449 [18/May/2022 17:40:32] "GET /textures/environmentMaps/1/nx.jpg HTTP/1.1" 404 2449 [18/May/2022 17:40:32] "GET /textures/environmentMaps/1/nz.jpg HTTP/1.1" 404 2449 [18/May/2022 17:40:32] "GET /textures/environmentMaps/1/py.jpg HTTP/1.1" 404 2449 Not Found: /main.css [18/May/2022 17:40:47] "GET /main.css HTTP/1.1" 404 2374 [18/May/2022 17:40:47] "GET /static/JS/bundle.2e62d86b71032951.js.map HTTP/1.1" 404 1858 [18/May/2022 17:40:47] "GET /static/style/main.css.map HTTP/1.1" 404 1813 */ one place where my js file is trying to load other files -
how to disable User fields to show my custom form in my template?
I have a problem with a form. It is a form that works like an "edit profile". I just want to style it, I don't like how it looks if I just put {{ form }} in my template, I'm using widget_tweaks to give it a better look. The problem is that when I use widget_tweaks and click the "Save" button, it doesn't work. But if I use the unstyled form {{ form }} instead, it does edit the fields. I'm thinking that when rendering the fields with widget_tweaks I'm not including the default User fields like: password, last login, etc. because I don't need them, I think that is influencing my form not working. Do you have any idea how to disable the default User fields and can I use the widget_tweaks or is it better to use forms.py? models.py COUNTRIES=( ('EUA', ('EUA')), ('Canada', ('Canada')), ('Other', ('Other')), ) class CustomUser(AbstractUser): phone1=models.IntegerField(default=0) phone2=models.IntegerField(default=0) fax=models.IntegerField(default=0) website=models.CharField(max_length=100,default=0) socialMedia1=models.CharField(max_length=100,default=0) socialMedia2=models.CharField(max_length=100,default=0) socialMedia3 = models.CharField(max_length=100,default=0) alternativeContact=models.CharField(max_length=100,default=0) country = models.CharField(max_length=100, default=0,choices=COUNTRIES) address=models.CharField(max_length=100, default=0) city=models.CharField(max_length=100,default=0) state=models.CharField(max_length=100,default=0) zip=models.CharField(max_length=10,default=0) tax_percentage=models.IntegerField(default=0) def __str__(self): return self.phone1 admin.py # Register your models here. class CustomUserAdmin(UserAdmin): add_form = UserCreationForm form=UserChangeForm model=CustomUser list_display = ['pk','email','username','first_name','last_name'] add_fieldsets = UserAdmin.add_fieldsets+( (None,{'fields':('email','first_name','last_name','image','location','phone1','phone2','fax','website', 'socialMedia1','socialMedia2','socialMedia3','alternativeContact','country','address', 'city','state','zip','tax_percentage')}), ) fieldsets = … -
Writing url in View in Django
I want to define a link for a character in the view. I used the following code, but it has an error. Error: Encountered unknown tag 'url' code: html=""" <p> <a href="{% url index2 %}">more information</a> </p> """ I use the Folium library and want to put a link in the popup. So I can not use the normal mode and I have used the above method. -
Django deployment error "usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: "
I am trying to deploy a Django app on a Linux virtual machine created on Google Computing Engine (GCE). My domain name works fine but the wsgi server does not run because of the error in the title. supervisor.log looks like tis. . . . usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: I am having a hard time troubleshooting because it does not tell me where to look into. The error seems to occur when I run gunicorn_start via commands such as sudo supervisorvtl restart tutorial or chmod +x .../venv/bin/gunicorn_start because I can run the contents of the file directly via my terminal. This is how my file tree looks like: /webapp/user |--- req.txt |--- venv |--- tutorial |-- req.txt |--manage.py |--tutorial . . . |--wsgi.py |--settings.py . . . I thought that the cause of this error is in the contents of the gunicorn_start file. So I ran the shell scripts in the file directly in the VM's … -
How to add math operations to a field ? DJANGO
I have a CreateView that generates a form. In this form there is a field that accepts float values. On the backend, i want to add math operations to this field and save the result in the database. How do I do this? -
Path finding between models in Django
I am trying to make a graph like structure in django using models to create paths between model instances. But I am no quite sure about how to do that automatically. The basic structure of my models is something like this: class Location(TimeStampedModel): name = models.Charfield() level = models.SmallPositiveIntegerField() previous_locations = models.ForeignKey('self') next_locations = models.ForeignKey('self') related_locations = models.ForeignKey('self') That previous_locations, next_locations and related_locations were my first approach in order to get some kind of tree structure, but they are pretty useless when there are several locations with the same level. For example, location_1 (with level = 1) can go to location_2 and location_3 (both with level = 2) and then both can go to location_4 (with level = 4). Maybe changing the foreign key to a many to many relation can solve this, but it's still not clear to my how to create the paths. For the paths, I made the following model: class Path(TimeStampedModel): name = models.Charfield() locations = models.ManyToManyField(Locations) Summarizing, the goal is select two locations and automatically create the shortest path or a group of paths (as maybe 2 paths require the same amount of steps). However, I don't know how to doit with the relations I …