Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django trying to add images with forms
I have two models with two different forms. One has a ForeignKey for another model, making a 1-N relationship. The problem is when i try to add images , is not working. The form where i change the (name/TabletForm2) is working so , only when i try to add (image/TabletFormImagem) is not working. The problem is that My model's def get_image(instance, filename): return os.path.join('intervencao/fotografias', str(instance.intervencao), filename) class Intervencao(models.Model): name= models.CharField(verbose_name="Name", max_length=200, blank=True, null=True) class Imagem(models.Model): intervencao = models.ForeignKey(Intervencao, related_name='intervencaoObjectsImagem', on_delete=models.CASCADE) imagem = models.ImageField(upload_to=get_image, blank=True, null=True, verbose_name="Fotografia") def __str__(self, ): return str(self.intervencao) My View def project_detail_chefe(request, pk): form = TabletForm2(request.POST) form2 = TabletFormImagem(request.POST, request.FILES) if request.method == "POST": if form.is_valid(): form.save() return redirect('index') else: form = TabletForm2(request.POST) if form2.is_valid(): //when i print something here to see if the form2 is valid , never enter here. form2.save() return redirect('home') else: form2 = TabletFormImagem() context = { 'form':form, 'form2':form2, } return render(request, 'tablet/info_chefes.html', context) tablet/info_chefes.html <div class="col-md-12"> <div class='form-group'> <label for="{{ form.subject.id_for_label }}" id="titulo">Name:</label> <em>{{ form.name}}</em> </div> </div> <div class="col-md-12"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form2.as_p }} <button type="submit">Upload</button> </form> </div> Forms class TabletForm2(forms.ModelForm): class Meta: model=Intervencao fields = ['data_intervencao_fim','ferramenta'] class TabletFormImagem(forms.ModelForm): class Meta: model=Imagem fields = ['imagem'] -
Include the same Django Admin class to multiple apps
For example, I have 3 apps: app1, app2 and all_apps. First 2 apps are nested in apps and have a lot of models. Now I want to include some admin classes to app1 and app2, and also to all_apps/admin.py (for example some configuration). What I need to do make that admin classes visible in both appX and all_apps? I tried to import it to both, but it appeared only in admin of app where it is located. Is it possible to include the same admin class twice (if it is for 2 different apps)? I know that it requires proxy-class if I need to include it twice to the same app, but what if they are different? -
Could not find path on running the django-private-chat, am I doing something wrong?
Details: django-private-chat version: 0.3.0 Django version: 3.1.2 Python version: 3.8.3 Operating System: Windows 10 I have installed all the requirements in my virtual environment, Django-private-chat is giving this error on running the server: Using the URLconf defined in tests.urls, Django tried these URL patterns, in this order: ^dialogs/(?P<username>[\w.@+-]+)$ [name='dialogs_detail'] ^dialogs/$ [name='dialogs'] The empty path didn't match any of these. Could someone point out what I am doing wrong? -
Failed to start gunicorn daemon, gunicorn.service: Failed to load environment
When i run sudo journalctl -u gunicorn I get: Oct 14 12:49:22 django-ubuntu-helpme systemd[1]: gunicorn.service: Failed to load environment > Oct 14 12:49:22 django-ubuntu-helpme systemd[1]: gunicorn.service: Failed to run 'start' task:> Oct 14 12:49:22 django-ubuntu-helpme systemd[1]: gunicorn.service: Failed with result 'resourc> Oct 14 12:49:22 django-ubuntu-helpme systemd[1]: Failed to start gunicorn daemon. I suppose something doesn’t add up with my directories. I have /etc/systemd/system/gunicorn.service which is: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=myname Group=myname EnvironmentFile=/home/myname/myapp/env WorkingDirectory=/home/myname/myapp ExecStart=/home/myname/myapp/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myapp.wsgi:application [Install] WantedBy=multi-user.target The directories I’m working in are as follows. myapp/ has my requirements.txt file, env/, and another app/ dir. Within myapp/app, I have manage.py, an env file that containt my SECRET_KEY which I've exported, and another app/ dir. Within myapp/app/app, I have settings.py and wsgi.py. What am I doing wrong? -
Django. An autocomplete field of a form doesn't work
I faced a problem during developing a search filter for my web-app. I need one field of a filter to be an autocomplete field, but unfortunately it doesn't work as expected. When I type smth in this field it displays nothing although it has to display some options. I use Bootstrap for this field, the class is 'basicAutoComplete', and as you can see in the picture below (please do not pay attention to bad positioning of the fields) there is no information displayed. But if I remove 'basicAutoComplete', all my buildings appears in dropdown list as you can see in the second picture. Can someone tell me how to fix it? class 'basicAutoComplete' no class Here is my code: views.py def device_rooms_search(request): device_rooms = DeviceRooms.objects.all() deviceRoomsFilter = DeviceRoomsFilter(request.GET, queryset=device_rooms) device_rooms = deviceRoomsFilter.qs builds = Buildings.objects.all() context = {'device_rooms_list': device_rooms, 'deviceRoomsFilter': deviceRoomsFilter} return render(request, "database/device_rooms/device_rooms_search.html", context) filters.py class DeviceRoomsFilter(df.FilterSet): name = df.CharFilter(field_name='room_number', lookup_expr='icontains') descr = df.CharFilter(field_name='description', lookup_expr='icontains') class Meta: model = DeviceRooms fields = ['name', 'facility_id', 'building_id', 'device_room_type', 'descr'] models.py class DeviceRooms(models.Model): id = models.CharField(max_length=7, primary_key=True) room_number = models.CharField(max_length=30, unique=True) device_room_type = models.ForeignKey(DeviceRoomTypes, on_delete=models.CASCADE) building_id = models.ForeignKey(Buildings, on_delete=models.CASCADE) facility_id = models.ForeignKey(Facilities, on_delete=models.CASCADE) description = models.CharField(max_length=200, null=True) search.html <form method="get" action=""> {% … -
(Django)Should I use same function for similar kind of function or create different for each
They are somewhat similar like all are comment related function. def someFucntion(request,query): if query == 'func1': # to something... elif query == 'func2': # to something... else: # to something else... -
How to highlight word in Django template from query keyword?
I want to highlight keywords in Django template which are the same keywords getting from the query. The below image illustrates how it highlights the keyword. In this example, the query contains two keywords "plastic" and "automotive" I want Django template to get those query keywords and highlight the same keyword contained in each Description. I guess it may uses {{ request.GET.query }} but I can not figure out any more. Please teach me how to make it. -
How can I count my followers in django template?
Well I have count the my following (people who i follow) but i dont understand how can i count my follower (people who follow me). model.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follower = models.ManyToManyField(User, related_name ='is_following',blank=True,) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) objects = ProfileManager() def __str__(self): return f'{self.user.username}' views.py(profiledetailview) def get_context_data(self, *args, **kwargs): context = super(UserProfileDetailView, self).get_context_data(*args, **kwargs) user = context['user'] '''#Trying with this but it is not working i guess this is wrong way to this but i am not sure!!''' allprofile = UserProfile.objects.all() followers = 0 for u in allprofile.follower: if u == user.userprofile: followers+=1 context['followers']=followers return context (My roughly idea: I was thinking somehow i gain all the profiles and than loop through them to check the particular user profile if there is profile within their follower than add one some follower variable.) You can ignore this if you know other way i have tried my idea but that couldn't work. you guys know them please tell me. -
(Django)How open diffrent templete .html for diffrent category like Mobile, Cars?
I have a category model. I want to open mobile form for mobile category and Cars form for car models -
Ruby has_many :through Association to python django
How to write this in django.There are two class models:users and advertiser_users. has_many :users, through: :advertiser_users -
How to access existing MySQL data table using Django
I am new in Django. I have some data table in MySQL, how can I access and query data from existing table. Thanks. -
Writing a user registration form that doesn't extend UserCreationForm, having trouble with clean() function not executing at all
So as the title says, I have to make my own form to register a user as a learning task. The form works as intended however i want to validate the data that is entered(right now only that pwd1 and pwd2 match). I wrote a clean function but it does nothing and reports no errors. form.py: from django import forms import phonenumbers from phonenumber_field.formfields import PhoneNumberField class RegisterForm(forms.Form): email = forms.EmailField( label='email address', max_length=255) f_name = forms.CharField(max_length=30) country = forms.CharField(max_length=30) mobile = PhoneNumberField(region="IN") address = forms.CharField(max_length=300) pwd1 = forms.CharField(max_length=32, widget=forms.PasswordInput) pwd2 = forms.CharField(max_length=32, widget=forms.PasswordInput) def clean(self): cleaned_data = super().clean() pwd1 = cleaned_data.get("pwd1") pwd2 = cleaned_data.get("pwd2") if pwd1!= pwd2: raise forms.ValidationError("Passwords don't match", code='password_mismatch',) views.py def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] f_name = form.cleaned_data['f_name'] address = form.cleaned_data['address'] country = form.cleaned_data['country'] mobile = form.cleaned_data['mobile'] password = form.cleaned_data['pwd1'] pwd2 = form.cleaned_data['pwd2'] user = User.objects.create( email=email, f_name=f_name, address= address, country= country, mobile= mobile, ) user.set_password(password) user.save() return redirect('/accounts/login/') else: return redirect('failure') else: form = RegisterForm return render(request, 'register.html', {'form':form}) return redirect('/register/') register.html <!DOCTYPE = 'html'> <html> {% load static %} <link rel="stylesheet" href="{% static 'accounts/file.css' %}"> <head> <div class="header"> <a href="/" class="logo">task1</a> <div class="header-right"> <a href="/">Home</a> … -
How to pass an object to celery in django request?
Here i initialize an object which can't be serialized in django view. I want to share this object among different requests and celery. Among requests i share the object with middleware. But I get problem when passing this object to celery. I have tried singleton. In middleware, I instantiate the singleton and assign value (a dict of {uuid:object} ) to member of it from request. But when i get the singleton in celery task, I got empty dict. How can i get the dict in celery? -
Django admin view design error/acting funny
Anyone faced this before? I have never. I installed Django 3.1 along with Python 3.9 and started facing this(see the image). Even when I scroll up, the top half stays there, its fixed, only the bottom half scrolls. I am using ckeditor for the body field in my app. Could that package be the reason? -
Dynamically removing a form from Django formset with Ajax
I would like to remove form dynamically when I press remove link. I have tried this solution but the problem with this solution is that it only removes form from html, it does not remove form from formset. So, I tried to alter from this solution and from this blog. Here is my progress: <form class="form-horizontal" method="POST" action=""> {% csrf_token %} <h3>Ingredients</h3> {{ formset.management_form }} <div class="form-list"> {% for form in formset.forms %} <div class='table'> <a class="remove-form" href="#">remove</a> <table class='no_error'> {{ form.as_table }} </table> </div> {% endfor %} </div> <input type="button" value="Add More" id="add_more"> <div class="row spacer"> <div class="col-4 offset-2"> <button type="submit" class="btn btn-block btn-primary">Create</button> </div> </div> </form> <script> function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.name) el.name = el.name.replace(id_regex, replacement); } function cloneMore(selector, type) { var newElement = $(selector).clone(true); var total = $('#id_' + type + '-TOTAL_FORMS').val(); newElement.find(':input').each(function() { var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-'); var id = 'id_' + name; $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked'); }); newElement.find('label').each(function() { var newFor = $(this).attr('for').replace('-' + (total-1) + '-','-' … -
ImportError: cannot import name 'ProductDetails' from 'pages.views'
I have written test case for views for details page. Here is below code I have written, When I am runing pytest in terminal i t raising these error. My project structure is as below vikreya mysite .cache .idea .pytest_cache logs media mysute init.py manage.py settings.py urls.py wsgi.py pages .cache migrations static templates tests test_views.py init.py admin.py apps.py cron.py Forms.py functions.py models.py urls.py views.py ``` from django.test import RequestFactory from django.urls import reverse from django.contrib.auth.models import User from pages.models import vk_customer from mixer.backend.django import mixer import pytest from pages.views import ProductDetails @pytest.mark.django_db class TestViews: def test_product_detail_authenticated(self): mixer.blend('pages.vk_master_table') path = reverse('detail', kwargs={'pk': 1516}) request = RequestFactory().get(path) request.user = mixer.blend(vk_customer) response = ProductDetails(request, pk=1516) print(response) assert response.status_code == 200 ``` This the error i am getting..... ____________________________________________________________ ERROR collecting pages/tests/test_views.py ____________________________________________________________ ImportError while importing test module 'H:\vikreya\mysite\pages\tests\test_views.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: c:\users\user\appdata\local\programs\python\python38\lib\importlib\__init__.py:127: in import_module return _bootstrap._gcd_import(name[level:], package, level) pages\tests\test_views.py:8: in <module> from pages.views import ProductDetails E ImportError: cannot import name 'ProductDetails' from 'pages.views' (H:\vikreya\mysite\pages\views.py) Please help me out to solve this error, Thank you, ~Salima -
Django Expire Session on Tab Close
I am making a project in Django to practice authentication. I am using sessions and have enabled SESSION_EXPIRE_AT_BROWSER_CLOSE But still the session remains if I close the browser tab. It works when I quit the browser, but I wanted it expire after tab is closed. I am unable to find a solution. Thanks in advance -
Requests python [closed]
How could I paginate this results from API with the requests library I would like to know how to do it because I will implement this on django project. Thanks import requests path = 'https://api.themoviedb.org/3/movie/popular?' api = 'my-api' url = '{}api_key={}&language=en-US&page=1'.format(path, api) response = requests.get(url) obj = response.json() results = obj.get('results', []) if results: for pelicula in results: titulo = pelicula['title'] print(titulo) imagen = pelicula['poster_path'] print(imagen) votos= pelicula['vote_average'] print(votos) -
asgiref AsyncToSync explanation
# https://github.com/django/asgiref/blob/master/asgiref/sync.py class AsyncToSync: """ Utility class which turns an awaitable that only works on the thread with the event loop into a synchronous callable that works in a subthread. If the call stack contains an async loop, the code runs there. Otherwise, the code runs in a new loop in a new thread. ############### DON'T UNDERSTAND #################### Either way, this thread then pauses and waits to run any thread_sensitive code called from further down the call stack using SyncToAsync, before finally exiting once the async task returns. """ Can anyone help to explain the bolded text? thanks in advance! -
Django: Problem serializing and posting nested JSON data, "id already exists."
I'm facing a weird error while serializing a nested dictionary in Django. Here's what I've done I've created a view using DRF that processes and builds a nested dictionary after which this dictionary will be used by the serializer to post the data. views.py .... actual_data = generate_data() test_data = { 'album_name': 'The Grey Album', 'album_id': 1234, # I've defined this as my primary key in my models.py 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, {'order': 2, 'title': 'What More Can I Say', 'duration': 264}, {'order': 3, 'title': 'Encore', 'duration': 159}, ] } # test_data == actual_data -> (True) # type(test_data) == type(actual_data) ->(True) serializer = AlbumSerializer(data=actual_data) # This statement gives error serializer = AlbumSerializer(data=test_data) # This statement works and return serialized data serializer.is_valid() serializer = AlbumSerializer(data=actual_data) # This statement gives error if I pass actual_data to the serializer, then the serializer failes and throws and error saying { "album_id": [ "album with this album id already exists." ] } serializer = AlbumSerializer(data=test_data) # This statement works and returns serialized data I checked my models.py, serializer.py; everything looks fine because the test_data works just fine. Any leads as to why this is happening would … -
pass non-english letters in urls django 3.1
I have a website showing some news. Some of the article's names are not in English language and they are Persian. If I click on the title of a news, it should show the details of that news.When I test it on local host, it works fine. But on the real host I get internal server (500) error. Does anyone know how should I pass Persian names in the url? I use Django version 3.1. This is the model of News app: class News(models.Model): name = models.CharField(max_length = 500, default="-") This is the url: path('details/<word>/', views.news_details, name="news_details"), It is the template: {% for i in news %} <a href="{% url 'news_details' word=i.name %}"><img class="img-full" style="width: 390px; height:300px;" src="{{i.picurl}}" alt=""></a> {% endfor %} and it is views.py: def news_details(request,word): news = News.objects.get(name = word) return render(request, 'front/news_details.html',{'news':news}) -
Django annotation case when
I have the following model: class Room(models.Model): # model fields class Table(models.Model): room = models.ForeignKey( Room, [...], related_name='tables' ) preparation_time = models.BooleanField(default=False) class Seat(models.Model): table = models.ForeignKey( Table, [...], related_name='seats' ) timestamp = models.DateTimeField(auto_now_add=True) is_vip = models.BooleanField(default=False) The code itself checks that per room there is a maximum of one table with preparation_time=None. Which is always the .last() one in the queryset. I would like to get the latest timestamp based on the following rules: 1.) If all tables of a room are prepared, return the latest preparation_time (the preparation_time of the latest table in the room) 2.) If there is a table without preparation_time, return the latest timestamp of a seat with a vip on it. I am getting the latest seat for case 2 like this: Room.objects.annotate( latest_activity=Max( 'tables__seats__timestamp', filter=models.Q(tables__seats__is_vip=True)) ) Then I tried to implement the first rule like this: .annotate( last_activity=Case( When(~Exists(Q(tables__preparation_time__isnull=True)), then=Max('tables__seats__timestamp', filter=Q(tables__seats__is_vip=True)) ), default=Table.objects.filter(room=OuterRef('id')).last().preparation_time, output_field=DateTimeField() ) For some reason this fails as I can not use the Q query in the exists. What would be the best way to achieve my goal? -
field id expected a number but got <function id of ---- > django
I was trying to add products detail view function by using the objects.get(pk = id) method. Since while I link it to the template I get above error with one plus point that I get I'd number on the end of url. Hope I get the solution for this soon -
Django - Not able to connect with Ldap Active Directory
I am a total newbie and this is my first Django web-app. This will be used in an intranet of the org I am working for. I need to connect my web-app with Active Directory for SSO authentication. For starters I followed the following tutorial. And since I don't have the access to the org's AD right now, I am using a free LDAP test server I found online. I followed the exact steps as mentioned in the tutorial, but I don't know what changes I should be expecting. From what I have seen, after a successful connection with LDAP server, the Users model on django-admin should be populated. But in my case I am seeing no changes in the Users model. Here is my settings.py file(refer the end of this code)(as this is the only file I have added the connection code in): import os import ldap from django_auth_ldap.config import LDAPSearch from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'kt_j(tvya@9r+ef8%+5$4y#h$jl%u-^!!pxeo0h5t=j)w23361' # SECURITY WARNING: don't run … -
Django: Remove duplicate data
I am using Django and React for my app. I am really new in Django rest frame work. I have made three models, they are order, customer and products. Order models have many to one relationship with customers and products. I fetched the data successfully to React frontend. But the problem is when I make new entries, for example: when user order new product. It give each time same user's name is frontend like this. I checked some documentation and stackover-flow questions but did not find the right answers. I know i need do something in my views.py's Order query but don't know how. This is my models class Customer(models.Model): name = models.CharField(max_length=200, null= True) email = models.CharField(max_length=20, null=True) phone = models.CharField(max_length=20, null=True) date_created= models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Tag(models.Model): name= models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): CATEGORY=( ('Indoor', 'Indoor'), ('Outdoor', 'Outdoor'), ) name= models.CharField(max_length=200, null=True) price= models.FloatField(null=True) category=models.CharField(max_length=200,null=True, choices=CATEGORY) description= models.CharField(max_length=200,null=True, blank= True) date_created=models.DateTimeField(auto_now_add=True, null=True) tags= models.ManyToManyField(Tag) def __str__(self): return self.name class Order(models.Model): STATUS =( ('Pending', 'Pending'), ('Out of delivery', 'Out of delivery'), ('Delivered', 'Delivered'), ) status= models.CharField(max_length=200, null=True,choices= STATUS) date_created=models.DateTimeField(auto_now_add=True, null=True) customer = models.ForeignKey(Customer, null= True, on_delete= models.SET_NULL, related_name='orders') product = models.ForeignKey(Product, null= True, on_delete= …