Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to display mapbox location in django template?
i created a django mapbox app my models.py class is : class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.SET_NULL ,blank=True,null=True) location2 = LocationField(map_attrs={"center": [51.42151,35.69439], "marker_color": "blue"},null=True, blank=True) and this is my views.py : def profile_page(request,id,slug): user_id=request.user.id profile = get_object_or_404(Profile,id=id,slug=slug) post = Post.objects.filter(profile=profile) mapbox_access_token = 'pk.eyJ1IjoibWlzdGVyZmgiLCJhIjoiY2tteHNmcjllMHJ4OTJwJ3-SkFRpWJtDDDwfrpg' context={ 'profile': profile, 'mapbox_access_token': mapbox_access_token } return render(request,'profile_page.html',context) and this is templates: <div class="col-12 col-xl-12 pr-0 pr-md-4 "> {{ profile.location2 }} <div class="border" id="map" width="100%" style='height:400px'></div> </div> <script> mapboxgl.accessToken = {{ mapbox_access_token }}; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v10', center: [35.69439, 51.42151], zoom: 9, // bearing: 180 }); </script> mapbox location {{ profile.location }} shows like this (46.30637816268069, 38.065254395567706) in template but graphical mapbox doent show in template -
ModelChoiceField on django-filter
I created a django-filter class to use on my dashboard, but the ModelChoiceField dropdown is showing all 'colocador' objects and not just those that is related to the current user Colocador is a user profile that is related to another user profile on class Colocador(models.Model): user = models.OneToOneField( MyUser, on_delete=models.CASCADE, primary_key=True) work_for = models.ForeignKey(Dono, models.CASCADE, blank=True, null=True) I have a model like this class Venda(models.Model): name = models.CharField(max_length=50, verbose_name='Nome') colocador = models.ForeignKey( Colocador, on_delete=models.CASCADE, verbose_name="Colocador") And in my filters.py class VendaFilter(django_filters.FilterSet): foo colocador = django_filters.ModelChoiceFilter( queryset=Colocador.objects.filter(work_for=3)) class Meta: model = Venda fields = ['search', 'status', 'colocador'] I hardcoded the work_for to 3 but obviously I don't want a hardcoded value, I already passing the actual user and tried this but doesn't work class VendaFilter(django_filters.FilterSet): search = django_filters.CharFilter( method='search_filter', label='Procurar') # colocador = django_filters.ModelChoiceFilter( # queryset=Colocador.objects.filter(work_for=3)) class Meta: model = Venda fields = ['search', 'status', 'colocador'] def search_filter(self, queryset, name, value): return Venda.objects.filter( Q(name__icontains=value) | Q(phone_number__icontains=value) | Q( cpf__icontains=value) | Q(rg__icontains=value), colocador__in=self.colocadores) def __init__(self, user, *args, **kwargs): super(VendaFilter, self).__init__(*args, **kwargs) self.colocadores = Colocador.objects.filter(work_for=user) self.filters['colocador'] = django_filters.ModelChoiceFilter( queryset=Colocador.objects.filter(work_for=user)) The dropdown is showing just the objects that are related to user, but when I submit the filter raise this error raise FieldError("Cannot resolve … -
Import Issue With django.views
everyone. I'm working with a small team to create a python project with Django and Vue implemented. We're having troubles with our import statements and having PyCharm recognize the file path. from django.views import views as vue_views This particular line of code is what's causing the problem. Pycharm keeps telling us "Cannot find reference 'views' in 'init.py' ". When we run the django server, the console will tell us "ImportError: cannot import name 'views' from 'django.views' (C:\Users\myusername\AppData\Roaming\Python\Python39\site-packages\django\views_init_.py)". The project will work fine on one of my coworkers machines but gives us these errors when any of us pull it from git. This leads us to believe it has something to do with our interpreter or something like that. Any help would be appreciated. Thanks in advance! -
How to list MultiChoiceField results one by one in Django?
I have multi choice model. I want to display it in the template one by one and not all at once. Like i want to list them in my template one by one in a good position. how do i separate multichoicefield display results ? views.py def car_detail(request, id): single_car = get_object_or_404(Car, pk=id) data = { 'single_car': single_car, } return render(request, 'cars/car_detail.html', data) models.py features_choices = ( ('Sürücü Hava Yastığı', 'Sürücü Hava Yastığı'), ('Eba (ani Fren Desteği )', 'Eba (ani Fren Desteği )'), ('Hırsızlığı Önleyici Alarm Sistemi', 'Hırsızlığı Önleyici Alarm Sistemi'), ('Sürücü Yan Hava Yastığı', 'Sürücü Yan Hava Yastığı'), ('Ön Yolcu Hava Yastığı', 'Ön Yolcu Hava Yastığı'), ('Arka Ses Ötesi Park Radar Sistemi', 'Arka Ses Ötesi Park Radar Sistemi'), ('İmmobilizer', 'İmmobilizer'), ('Dstc (dinamik Denge Ve Çekiş Kontrol Sistemi)', 'Dstc (dinamik Denge Ve Çekiş Kontrol Sistemi)'), ('Şerit Değiştirme Asistanı', 'Şerit Değiştirme Asistanı'), ('Kör Nokta Sensörü', 'Kör Nokta Sensörü'), ('Ön Yolcu Yan Hava Yastığı', 'Ön Yolcu Yan Hava Yastığı'), ('Ön Emniyet Kemerini Bağla Sinyali', 'Ön Emniyet Kemerini Bağla Sinyali'), ('Deri Kaplama El Freni', 'Deri Kaplama El Freni'), ('Yol Bilgisayarı', 'Yol Bilgisayarı'), ('Navigasyon Sistemi', 'Navigasyon Sistemi'), ('Uzun Far Asistanı', 'Uzun Far Asistanı'), ('Merkezi Kilit', 'Merkezi Kilit'), ('Yağmur Sensörü', 'Yağmur Sensörü'), ('Usb Bağlantısı', 'Usb … -
how to center a bootstrap div image vertically and horizontally
before you downvote and close the topic, hear me out please. I DID CHECK OUT every single stackoverflow question on this exact topic. I did try every single approach and yet nothing's working. It may take you a few seconds to help me solve this, but I am struggling for over 3 hours on this exact thing. Here's the problem. My web app runs on django and I'm currently working on the front-end. It looks like this at the moment. I'm trying to get the 3 pictures centered both horizontally and vertically into some reasonable size into the middle of the page. I want it to be responsive. This is a home page for a logged category of HOST, when logged as TENANT, he has only 2 pictures there, which I want to have centered as well relative to the window size. Here is my html with a bit of django logic: {% extends 'milk_app/base.html' %} {% load static %} <!DOCTYPE html> {% block title_block %} Homepage {% endblock %} {% block body_block %} <!-- Home page for Hosts --> {% if user.userprofile.account == "Host" %} <div class="container"> <div class="row"> <!-- Scroll other properties --> <div class="center-block col-4"> <a href="{% … -
Django model-form-view connection
I am trying to scrap datas from a website. Here is my models.py ` from django.db import models from .utils import get_link_data from .forms import AddLinkForm class Link(models.Model): name = models.CharField(max_length=500, blank=True) price = models.CharField(max_length=20, blank=True) image = models.CharField(max_length=1000, blank=True) def __str__(self): return str(self.name) def save(self, *args, **kwargs): name, price, image = get_link_data(AddLinkForm.url) self.name = name self.price = price self.image = image super().save(*args, **kwargs) And here is my forms.py from django import forms class AddLinkForm(forms.Form): url = forms.URLField() And my views.py: from django.shortcuts import render from .models import Link from django.views.generic import DetailView from .forms import AddLinkForm def home_view(request): form = AddLinkForm(request.POST or None) if request.method == 'POST': if form.is_valid(): form.save() form = AddLinkForm() qs = Link.objects.all() items_no = qs.count() context = { 'qs': qs, 'items_no': items_no, 'form': form, } return render(request, 'links/main.html', context) class ProductDetailView(DetailView): model = Link template_name = 'links/details.html' ` I have to change form.save() I guess, but how will I save the form after I change it and get the url from view? I dont want 'url' in my db so I didnt add it to my model. -
how to substitue models.permalink depracted code in Django?
I am reading the book Beginning Django E-Commerece that describes how to build a webshop using Django. In one of the code example that I am following the author is setting up a product model that looks as below. Here he used a decorator models.permalink followed by get_absolute_url. From the documentation, I learned models.permalink is depracted. How should I adapt the below code for my current Django 3.1.3 version? Also can somebody explain to me what models.permalink actually does? In particular what does @models.permalink def get_absolute_url(self): return ("catalog_product", (), {'product_slug' : self.slug}) intend to do? from django.db import models from django.db.models.fields.related import create_many_to_many_intermediary_model class Product(models.Model): name = models.CharField(max_length = 50, unique=True) description = models.TextField() allergic_note = models.CharField(max_length = 255) quantity = models.IntegerField(null = True, blank = True) #Used for campaign products to show how many items there is left price = models.DecimalField(max_digits=9, decimal_places=0, default=0.00) is_active = models.BooleanField(default = True) is_deliverable = models.BooleanField(default = True) image_path = models.CharField(max_length = 255) meta_keywords = models.CharField(max_length=255, help_text="comma delimited keywords text for SEO") meta_description = models.CharField(max_length=255, help_text="SEO description content") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=255, unique = True, help_text="Unique text for url created from name") is_featured = models.BooleanField(default = False) is_bestseller = … -
502 bad gate way django
I am trying to deploy my django site to gcloud, everything uploads just fine but when I follow the link I get a 502 bag gate way error. I was following the gcloud tutorial for app engine with no luck. This is my app.yaml runtime: python 39 resources: memory_gb: 4 handlers: url: /static/ static_dir: /static/ url: /.* script: auto I'm new to django and gcloud so any help would be greatly appricated -
ManyToManyField, filtering by matching all related values
I have in my model to classes: User: name Pair: users=ManyToManyField(User) I want to make working and in the next step optimal query which allows me to get all pairs of two users. This code of course not works, but shows my problem. The order of user_1 and user_2 is not important. def get_pair_by_users(user_name_1, user_name_2): return Pairs.objects.filter(users__name=user_name_1 & users__name=user_name_2) -
add key and value in json dict
how add key and value from user in file? def register(): while True: username=input("enter your username: ") if not username.strip(): print("\") continue if username in user_data: print("this user exist") else: break while True: password=input("enter your password: ") if not password.strip(): print("\") continue renter_pass=input("enter again") if password !=renter_pass: print("pass and \pass should be equal!") else: break while True: age=input("enter your age: ") if not age.strip(): print("\") continue if not age.(): print("input must be number ") continue else: break the age not dump with key and my dict "y": ["1470", "12"]} dosnt have age key -
Trying to make query with filtering foreign key
I have a huge list of sports teams that has their respective league as a foreign key, (NBA, NCAA, MLB, NFL). In my Django form, I am trying to filter out only the teams with the MLB key but when I do the query with Objects.filter(league='MLB') I get an error that tells me it wants the id number. But when I do Objects.filter(league=3), I don't get an error but the queryset is empty. Objects.all() returns all the teams from all the leagues. If I run a for loop I can print out all the team's leagues, I just can't seem to search by them. I'm not sure what I am doing wrong. I appreciate your help. Models class TeamName(models.Model): name = models.CharField(max_length=100, null=False, blank=False) abbreviation = models.CharField(max_length=10, null=False, blank=False) league = models.ForeignKey( 'League', null=False, blank=False, on_delete=models.CASCADE) def __str__(self): return self.name class League(models.Model): leagues = ( ('MLB', ('MLB')), ('NBA', ('NBA')), ('NCAAB', ('NCAAB')), ('NFL', ('NFL')), ) name = models.CharField( max_length=10, choices=leagues, null=False, blank=False) def __str__(self): return self.name Forms def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) seasons = Season.objects.filter(name='MLB2021') names = [(season.id, season.name) for season in seasons] self.fields['season'].choices = names team_names = TeamName.objects.filter(league='MLB') teams = [(team.id, team.name)for team in team_names] self.fields['name'].choices = teams -
Django: Filtering two objects from the same "column"
Im quite new to django and hmtl and have managed to create a chart where the user can filter which first_name they want . I want to extend this so the user now can enter two first names in seperate forms and have both be displayed in the same chart. I´m using the django_filters package. models.py class Name(models.Model): first_name = models.CharField() value = models.IntegerField() views.py def Page(request): object = Name.objects.all() filter1 = myFilter(requests.Get, queryset = object) filter2 = myFilter(requests.Get, queryset = object) person_1 = filter1.qs person_2 = filter2.qs context = { person_1: person1, person_2: person2, filter1: filter1, filter2: filter2 } return render(request, "chart.html", context) chart.html <form method = "get" style ="margin-left: 50px"> {{ filter1.form }} {{ filter2.form }} <button type = "submit"> Search</button> </form> *ACESSS OBJECTs ETC* *CHART.JS STUFF* I dont get any errors and both forms works well, but not simultaneously. My guess is that I can't filter this way? -
Why is React not working in django project?
I have a django project, and I'm trying to add react to one page. I have a page called reacttest.html, and a reacttest.js file. I have installed React with npm. Here are the two files content: reacttest.js : import React from "react"; React.render( <h1>Bonjour, monde !</h1>, document.getElementById('root') ); reacttest.html : {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>React test</title> </head> <body> <div id="root"></div> <script type="text/jsx" src={% static 'app/js/reacttest.js' %}></script> </body> </html> Thanks! -
how can i make registration by email using Django registration
I'm workig on a small project using Django, i have installed django-registration to create the registration feature, but as i can see the registration is by the username and not by the email, Link of the package : https://django-registration-redux.readthedocs.io/ how can I fix that, This is my forms.py from django_registration.forms import RegistrationForm from .models import CustomUser class CustomUserForm(RegistrationForm): class Meta(RegistrationForm.Meta): model = CustomUser -
How Do I Count A Favorite Category - Django Query
I created a website for sharing anything about books in pdf. But i want to know what is the favorite category by how much 1 category used by many books. Books - Category has been arranged with ManyToManyField so this is the models.py class Category(models.Model): name = models.CharField(max_length=255, default='') def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=255) link = models.SlugField(max_length=255, unique=True, default='') # ng usah book = models.FileField(upload_to='book/pdf/') # ng usah cover = models.ImageField(upload_to='book/cover/') author = models.CharField(max_length=255) availability = models.IntegerField(default=0) description = CKEditor5Field(null=True, blank=True, config_name='special') uploader = models.ForeignKey(User, on_delete=models.CASCADE, related_name='uploader') pending = models.BooleanField(default=True) # ng usah upload_date = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, related_name='likes', blank=True) category = models.ManyToManyField(Category, blank=True) def ttl_like(self): return self.likes.count() def __str__(self): return self.title def delete(self, *args, **kwargs): self.book.delete() self.cover.delete() super().delete(*args, **kwargs) def get_absolute_url(self): links = self.link links = str(links) return reverse('read:detail', args=[links]) i want to count the favorite on the views.py, but i want to know how much the categories used on 1 book and ordering by the most used category choices .order_by('-fav_category'). here this the views.py in GCBV class AllBookList(ListView): model = Book template_name = 'read/list.html' paginate_by = 6 ordering = ['-pk'] def get_queryset(self): qq = self.request.GET.get('q') ss = self.request.GET.get('s') if qq is not None: … -
Difference between querysets and objects in Django
What is the difference between a query set and objects.all() in Django? After reading the documentation I am still a bit in doubt as to particularly when each of those should be used. Thank you! -
Django CustomAuthForm and default LoginForm not raising validation error
I extended the Django AuthenticationForm and created two backends to allow users to sign in with either (or both) email and username. This works perfectly if I try to sign in to the Django admin using any of the credentials. Although I can sign in on the frontend using any of these credentials, validation errors fail to show anytime the wrong credentials are used. forms.py class CustomAuthenticationForm(AuthenticationForm): username = forms.CharField(widget=TextInput( attrs={'placeholder': 'Enter your email address'})) password = forms.CharField(widget=PasswordInput(attrs={'placeholder': 'Password'})) remember_me = forms.BooleanField(required=False, label="Keep me signed in", initial=False) views.py class CustomLoginView(LoginView): form_class = CustomAuthenticationForm redirect_field_name = REDIRECT_FIELD_NAME template_name = 'login.html' def get(self, request, *args, **kwargs): if request.user.is_authenticated: if request.user.is_personal: return HttpResponseRedirect(reverse(...)) elif request.user.is_business: return HttpResponseRedirect(reverse(...)) else: return HttpResponseRedirect(reverse(...)) return super(LoginView, self).get(request, *args, **kwargs) def form_valid(self, form): remember_me = form.cleaned_data['remember_me'] if not remember_me: self.request.session.set_expiry(0) self.request.session.modified = True auth_login(self.request, form.get_user()) return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): if self.request.user.is_personal: return reverse(...) elif self.request.user.is_business: return reverse(...) else: return reverse(...) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) current_site = get_current_site(self.request) context.update({ self.redirect_field_name: self.get_redirect_url(), 'site': current_site, 'site_name': current_site.name, 'title': _('Log in to your account'), **(self.extra_context or {}) }) return context backends.py from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model User = get_user_model() class CaseInsensitiveModelBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): … -
Link the current user to a field in ModelForm django
Overview I'm working on a commerce site using django. The logged in user has the ability to create a listing. I'm using django model to create a model and ModelForm for forms. models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Listing(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=500) starting_bid = models.IntegerField() image_url = models.URLField(blank=True) category = models.CharField(max_length=15, blank=True) listed_by = models.ForeignKey(User, on_delete=models.CASCADE) The last field in Listing(models.Model) is used to store the user who listed the listing which should be based on the current logged in user. forms.py from django import forms from .models import Listing class ListingForm(forms.ModelForm): class Meta: model = Listing fields = ["title", "description", "starting_bid", "image_url", "category"] forms.py without the listed_by field is working as intended. views.py def create(request): """Renders a Form to Create a Listing""" if request.method == "POST": # Create a form instance and populate it with data from the request: form = ListingForm(request.POST) if form.is_valid(): # Save a new Listing object from the form's data. listing = form.save() # Redirects the users to the main page return HttpResponseRedirect(reverse("index")) # If the form is not valid, render the template with errors return render(request, 'auctions/create_listing.html', {"form": form}) # Create a form instance … -
Django media image full path for PIL
i am trying to get the full path of an uploaded django image (to the media folder) to use it with PIL but it returns FileNotFoundError code: from PIL import Images img_dir = Image.objects.all().first() img = img_dir.image1.url im = Image.open(img) how can i solve this error? -
Pagination with function based view with dictionary
I'm trying to paginate the pages with the help of Paginator. Have written this so far but I don't understand what would I pass in the context. Simply doing this doesn't work, I think my knowledge with Paginator is limited. customerproducts = customerproductsjsondata.json() customerproducts_list = customerproducts['data'] paginated_products = Paginator(customerproducts_list, 20) -
Return all model results, but filter out the ManyToManyFields
I'm trying to filter out the results from a model so all fields return, but I can filter just one ManyToManyField in the model. I'd only like it to filter out on the page, and not in the Admin. I've found some great information about ManyToMany filtering but, for some reason, nothing that helps in this particular case. So I guess I'm either doing it very wrong, or I'm missing an important search term. I've tried filtering in models, in views, and in the template. Here's a minimal example to help explain: # models.py class Foo(models.Model): name = models.CharField(unique=True, max_length=255) bars = models.ManyToManyField(Bar) class Bar(models.Model): thing = models.CharField(max_length=12) is_public = models.BooleanField(default=False) # views.py class FooDetail(DetailView): def get_queryset(self): # Would I filter in here? return super(FooDetail, self).get_queryset() I would like the Foo model to return all foos, but for each foo only includes bars that are true for is_public Where do I filter out the Bar results for the Foo model? I found this question which is basically what I'm asking, but the answer is specific to that question and shows it filtered in the Serializer. So I don't understand how/where to apply that answer here where I'm not doing any … -
Access denied to mysql database when lauched from Django's dbshell
I have just installed mysql in my mac system, and I have configured my Django settings.py for the mysql data base DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '/usr/local/mysql-8.0.23-macos10.15-x86_64/data/takeawaywebshop', #changed in production 'USER': data['mysql']['username'], 'PASSWORD': data['mysql']['password'], 'HOST': '', 'PORT': '', } } When I launched the below command calling dbshell from manage.py, I received an error stating that the data base access what denied python manage.py dbshell mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1044 (42000): Access denied for user 'jianwu'@'localhost' to database '/usr/local/mysql-8.0.23-macos10.15-x86_64/data/takeawaywebshop' CommandError: "mysql --user=jianwu --password=xxxxxx /usr/local/mysql-8.0.23-macos10.15-x86_64/data/takeawaywebshop" returned non-zero exit status 1. Any ideas of what I have missed? -
What configurations to be made to enable a web application handle thousands of requests per second - Django/Gunicorn/Postgres
I want to deploy a web application with Django backend and Postgresql DB running on Nginx and Gunicorn. What are the configurations to be made to enable this application to handle around 1000 requests per second without any delay. Generally, each request takes less than a second to process. So, I also want these requests/calls to hit on API within a second to process in less than 2 seconds without consuming more CPU. This is a doubt which arose while learning. So, I don't have any code snippets or configurations to share. Thanks much in advance. -
saving default fields in a ManyToMany relationship
User class User(AbstractBaseUser): email = models.EmailField(max_length=60, unique=True) username = models.CharField(max_length=60, unique=True) job = models.ManyToManyField(Job, blank=True, related_name="users", default = JobDefault) where JobDefault() returns a string. def JobDefault(): return "Artist" class Job(models.Model): job = models.CharField(max_length=60, null=True, default = JobDefault()) def __str__(self): return self.job So there's a m2m field involving User and Job but I want to set a default "Artist"(which is what JobDefault() returns) as the job if a user does not specify a job. Django seems to have a bug which prevents the setting of initial values of the model every time an instance is created. I tried implementing this by overriding the save method of User: def save(self, *args, **kwargs): if not self.job.all(): self.job.add(JobDefault()) super(User, self).save(*args, **kwargs) but returns an error when I try saving a User object: raise ValueError('"%r" needs to have a value for field "%s" before ' ValueError: "<User: hello@gmail.com>" needs to have a value for field "id" before this many-to-many relationship can be used I also tried using Postsave: @receiver(post_save, sender=User, dispatch_uid='SetDefaultName') def SetDefaultName(self, **kwargs): User = kwargs['instance'] if not User.job.all(): User.job.add(JobDefault) User.save() but returns this error when I try to run any manage.py command: @receiver(post_save, sender=User, dispatch_uid='SetDefaultName') NameError: name 'User' is not defined Is there … -
Django subdomains using django_hosts
I'm getting a NoReverseMatch at / 'ccc' is not a registered namespace when using django_hosts. I've followed tutorials from How to Use django-hosts Library, How to Create Infinite Domains Using Django Hosts, and I'm getting the NoReverseMatch error