Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with Django Error during template rendering, maximum recursion depth exceeded
enter image description here I have gone through everything you say in answers to similar problems but I can't find the solution. -
problem with django multitable inheritance and django-parler
i have these models: class Product(TranslatableModel): productId = models.UUIDField(default=uuid4, primary_key=True, editable=False) translations = TranslatedFields( title = models.CharField(max_length=100), description = models.TextField(max_length = 2000) ) picture = models.ImageField() price = models.FloatField() art_type = models.ForeignKey(ArtType, on_delete=models.SET_NULL, null = True,blank = True) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) purchase_num = models.PositiveBigIntegerField() objects = InheritanceManager() class Course(Product): languages = models.ManyToManyField(Language) isChaptersOpen = models.BooleanField(default=True) but whenever i try to add a new course i get this error message in the django admin panel: ImproperlyConfigured at /en/admin/products/product/ InheritanceQuerySet class does not inherit from TranslatableQuerySet why this is happening -
Django Migration to add Group and permissions not adding permissions
I have a custom migration that is intended to automatically create a new group and add permissions. The group is being created but the permissions are not being added. Any ideas about how to fix this? from django.db import migrations, models from django.contrib.auth.models import Group, Permission from django.contrib.auth.management import create_permissions def add_group_permissions(apps, schema_editor): for app_config in apps.get_app_configs(): create_permissions(app_config, apps=apps, verbosity=0) group, created = Group.objects.get_or_create(name='Employee') if created: permissions_qs = Permission.objects.filter( codename__in=[ 'can_add_how_to_entry', 'can_change_how_to_entry', 'can_view_how_to_entry', ] ) for permission in permissions_qs: group.permissions.add(permission) group.save() class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.RunPython(add_group_permissions), ] -
How to modify an extra field in response model to differentiate if an item belongs to a user depending on the ORM objects
I'm new to backend development and want to have an extra field in my response depending on the user id. The project is a mini ecommerce app where only the shop owner can edit its content. When the frontend requests GetAllShops, how can I attach a boolean field like is_owner for every shop entity returned from sql alchemy ORM by comparing the id of the shop with the id of the client? Thanks in advance. I'm using Pydantic and FastAPI. -
Auto deployment of Django project
I have a django project and create a repository for it on gitlab. I want to auto deploy it on an ubuntu VPS but I don't know how. -
Django not loading some templates on my server
Currently working on a project but on localhost it works well but on server I get 404 error in some page and I am currently using server for testing it seems server doesn’t contain my html page. -
How Do I Access This A Value In A Python Data Dictionary?
I have a python data dictionary that I am using to do some date comparisions. However when I loop through it I can't figure out how to access the DailyPlannerRequest value. I have tried doing a request.DailyPlannerRequest but the error that comes back is 'datetime.date' object has no attribute 'DailyPlannerRequest'. I've read a bit about trying to convert this dictionary value but can't find anything helpful. I am trying to do a loop and query a filter value and compare it to this data dictionary value. I'm trying to do something like.... if request.day == day and event.daily_planner_request_name == request.DailyPlannerRequest : I've done this lots of times before but the complication here is that one is a queryset and the other is a dictionary value that I'm trying to get to compare. I've played a bit with the approach documented here Accessing dict keys like an attribute? But can't seem to figure this out. Thanks in advance for any ideas. -
how to add extra elements via JavaScript in django modelformset_factory when user selects the product?
I am trying to create a page where users can select the product and insert a number of units in each component. I managed to create a view, formset, and small JS function that allows a user to add the next product and component dynamically but I am struggling to add a feature that would allow displaying related components and products automatically whenever the user will select the product from the dropdown list. Is there any JS plugin that would handle something like this or any ideas on how to develop such a feature? I did something like this in my DetailView by passing author, created, related_product, and related_component in the initial method but here I would definitely have to use JS. For now I have something like this: However, the user must select related_product and related_component manually. What I want is something like this: So whenever the user selects the product it will automatically auto-populate proper values in related_product and related_component fields. It is important to keep adding another product button because the user should be able to add as many products as possible. I'd appreciate any advice. models.py class Product(models.Model): title = models.CharField(max_length=255, default='') class CostCalculator(models.Model): title = … -
ModuleNotFoundError: No module named 'encyclopediadjango'
I am currently taking a cs50w course specifically on the django part. I am trying to launch my app that I created and followed the exact steps that were in the course video, however it gives an "ModuleNotFoundError: No module named 'encyclopediadjango'" error. I double checked that my django files are installed correctly and I am using the right version of python. What can I do to fix the error? yerden@MacBook-Pro-Yerulan wiki % python3 manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen … -
django orm prefatch related missing resualts
I am trying to use prefatch related but oddly I dont get the results instances: here is the invoke code: attraction: Attraction = Attraction.objects.prefetch_related("reviews").get(pk=product_id) print(attraction.reviews) print(AttractionReview.objects.filter(attraction_id=product_id)) here is the output: attractionsAPI.AttractionReview.None <QuerySet[<AttractionReview: AttractionReview object (37)>, <AttractionReview:AttractionReview object (36)>, <AttractionReview: AttractionReview object (39)>, <AttractionReview: AttractionReview object (34)>]> my AttractionReview modal: class AttractionReview(models.Model): traveler_name = models.CharField(max_length=255, null=True, blank=True) submitted_on = models.DateField(null=False, blank=True) text = models.TextField(null=True, blank=True) title = models.TextField(null=True, blank=True) attraction = models.ForeignKey( Attraction, on_delete=models.CASCADE, related_name="reviews", ) class Meta: unique_together = ["attraction", "text"] -
Django AuthenticationForm is not working this give error name 'UsernameField' is not defined
class LoginForm(AuthenticationForm): username = UsernameField(label='username', widget=forms.TextInput(attrs={'autofocus':True,'class':'form-control'})) password = forms.CharField(label =_("Password"), strip=False, widget=forms.PasswordInput(attrs={'autocomplete':'current-password', 'class':'form-control'})) -
Django Async Model Save()
I'm converting my normal views to async views due to request queries blocking all my threads. So far I've solved most of my problems except one. How to async save a model ? async def dashboardAddChart(request, rowId): row = (await sync_to_async(list)(DashboardRow.objects.filter(pk=rowId).select_related('dashboard__site', 'dashboard__theme')))[0] chart = DashboardChart(dashboard=row.dashboard, dashboardRow=row) if row.dashboard.theme is not None: dashboardThemes.applyThemeToChart(chart) chart.save() chartData = await getChartData(chart.pk) I've tried numerous things with chart.save() including: await sync_to_async(chart.save) t = asyncio.ensure_future(sync_to_async(chart.save)) await asyncio.gather(t) But I'm not getting it right. Any help will be appreciated! -
select special items from foregin key in django
I have two models class Product(models.Model): name = models.CharField(max_length=50) averageRating = models.IntegerField(null=True, blank=True) ratingCount = models.IntegerField(null=True, blank=True) cover = models.ImageField(upload_to='images/', default=None, blank=True, null=True) ... and class VariantProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) mainPrice = models.IntegerField() discountPrice = models.IntegerField(null=True, blank=True) this means different variant of products have different prices. now I need the variant of a product that have minimum price in SQL i think this code works for my purpose but I don't know how can I get this result in Django -
Vue/Nuxt and Django Stack, How to make a local request to my Django API on server?
I'm working on an app using Vue and Nuxt, and I want to send a request from my Vue app, to my Django app ( Which is running in the same machine ) but Nuxt just send the request on the client side to localhost but I want to do that from my Nuxt app to my Django app, how can I do that? when I send an axios request to fetch some data from my django api, it sends it from the client, not from the server "to" my django app which also is on the same server, I want that request to be completely local on the server and my api to NOT be accessible from anywhere else -
How to convert Django TextField string into JSON?
I have the following model: class Car(models.Model): data = models.TextField(default="[]") Also, I have the following serializer: class CarSerializer(serializers.ModelSerializer): data = serializers.ListField(child=serializers.CharField()) The REST API gets data and saves it as text field. In my to_dict method of Car, I want to convert self.data into JSON and return the dict: def to_dict(self): result = dict() result['data']= json.loads(self.data) return result But it fails with the error: json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1) As I understand, the reason is that self.data is: "['a', 'b', 'c']" And not: '["a", "b", "c"]' I'm familiar with JsonField, but since I'm using SQLite without JSON1 externation, I can't use it. How can I convert self.data to JSON? -
Django Rest API: Serializer won't show Foreign Key Field values
I'm trying to list the values of FacilityAddressSerializer within the FacilitySearchSerializer. This is what i tried. I get all the values of the FacilitySearchSerializer but the values of the FacilityAddressSerializer are showing as Null: serializers.py class FacilityAddressSerializer(serializers.ModelSerializer): class Meta: model = FacilityAddress fields = ( "id", "PrimaryAddress", "SecondaryAddress", "City", "RegionOrState", "PostalCode", "Geolocation", "AddressInfo" ) class FacilitySearchSerializer(serializers.ModelSerializer): AddressInfo = FacilityAddressSerializer(source="fa") class Meta: model = Facility fields = ( "id", "Name", "AddressInfo", "ListingVerified", "mainimage", "AdministratorCell", "Capacity", "PriceRangeMin", "PriceRangeMax", ) read_only_fields = ("id", "Name", "ListingVerified", "mainimage", "AdministratorCell", "Capacity", "FeaturedVideo", "PriceRangeMin", "PriceRangeMax") models.py class Facility(models.Model): Name = models.CharField(max_length=150, null=True, blank=False) mainimage = models.ImageField(null=True, blank=True) Capacity = models.IntegerField(null=True, blank=True) TelephoneNumber = models.CharField(max_length=30, null=True, blank=True) AdministratorCell = PhoneNumberField(null=True, blank=True) PriceRangeMin = models.IntegerField(null=True, blank=True) PriceRangeMax = models.IntegerField(null=True, blank=True) class FacilityAddress(models.Model): PrimaryAddress = models.CharField(max_length=150, null=True, blank=True) SecondaryAddress = models.CharField(max_length=150, null=True, blank=True) City = models.CharField(max_length=150, null=True, blank=True) RegionOrState = models.CharField(max_length=50, null=True, blank=True) PostalCode = models.CharField(max_length=30, null=True, blank=True) Geolocation = models.CharField(max_length=30, null=True, blank=True) AddressInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE, related_name='fa') -
Django forms: not adding attributes
Im aware that there is many post like this, but can you spot the typo or error in my code? Im adding custom classes to my forms but when I inspect the element on the web page there are none. The same goes for placeholder. code {% csrf_token %} <div class="col-6"> {{form.name}} </div> <div class="col-6"> {{form.surname}} </div> from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import SearchStats from django import forms import re def isStandardized(value): if not re.compile(r'^[a-zA-Z ]+$').match(value): raise ValidationError('Enter only english characters') return True class AuthorForm(ModelForm): name = forms.CharField(validators=[isStandardized]) surname = forms.CharField(validators=[isStandardized]) class Meta: model = SearchStats fields = ['name', 'surname', 'author_id', 'amount'] widgets = { 'name': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Name of an author'}), 'surname': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Surname of an author'}), 'author_id': forms.TextInput(attrs={'type':'hidden'}), 'amount': forms.TextInput(attrs={'type':'hidden'}) } -
Django Cannot Authenticate in the Login Page(Cant get in "user is not None")
I did all the things according to the django.documentation, users are saved in database but still cannot log in homepage. Always bringing back to me that 'Bilgilerinizi Kontrol Ediniz' error message. Could someone please about what can be the reason? Here is my "urls.py main": urlpatterns = [ path('signup', views.signup, name='signup'), path('login', views.login_user, name='login'), path('', views.homepage, name='home') ] Here "views.py": def login_user(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user = authenticate(request, email=email, password=password) if user is not None: login(request, user) return redirect('/') else: messages.info(request, 'Bilgilerinizi Kontrol Ediniz') return redirect('login') else: return render(request, 'login.html') And here it is my "login.html" page: <form action="" method="post"> {% csrf_token %} <div class="login-form"> <div> {% for message in messages %} <strong style="font-size: 0.8em;color:red">{{message}}</strong> {% endfor %} </div> <div class="field"> <div class="control"> <input class="input email-input" name="email" type="text" placeholder="E-mail Adresiniz"> <div class="input-icon"> <i data-feather="user"></i> </div> </div> </div> <div class="field"> <div class="control"> <input class="input password-input" name="password" type="password" placeholder="●●●●●●●"> <div class="input-icon"> <i data-feather="lock"></i> </div> </div> </div> </div> <div class="field is-flex" style="margin-top: 12px"> <div class="switch-block" style="display: flex;align-items: center;"> <label class="f-switch"> <input type="checkbox" class="is-switch"> <i></i> </label> <div class="meta"> <p style="font-size:.8rem">Beni Hatırla</p> </div> </div> <a href="forget-password" style="margin-left: auto;font-size:.8rem;align-self: center">Şifremi Unuttum</a> </div> <div class="field"> <div class="control"> <button type="submit" class="button … -
Create REST api to be consumed by mobile app, which tell u if a number is spam,or allow u to find a person’s name by searching for their phone number
Prefer using Django, Flask or Rails. For persistence you need to use a relational database along with an ORM for your framework. Terminology and assumptions: ● Each registered user of the app can have zero or more personal “contacts”. ● The “global database” is basically the combination of all the registered users and their personal contacts (who may or may not be registered users). ● The UI will be built by someone else - you are simply making the REST API endpoints to be consumed by the front end. ● You will be writing the code as if it’s for production use and should thus have the required performance and security. However, only you should use only a web server (the development server is fine) and a database, and just incorporate all concepts using these two servers. Do not use other servers. Data to be stored for each user: ● Name, Phone Number, Email Address. Registration and Profile: ● A user has to register with at least name and phone number, along with a password, before using. He can optionally add an email address. ● Only one user can register on the app with a particular phone number. ● A … -
Making different option for Select in Wagtail admin
I have on list of Types with two options and 2 list of options (one for each Type) Type= [(0, 'A'),(1, 'B')] Option_A=[(0,'optA0'),(1,'optA1'),(2,'optA2') Option_B=[(0,'optB0'),(1,'optB1'),(2,'optB2') and I have 2 fields in subclass page: type= models.TextField( ... choices=Type, ... ) depended_choice = models.TextField( ... choices=Option_A, #need to have Option_A if Type is A, and Option_B if Type is B ... ) and I also have this: content_panels = Page.content_panels + [ FieldPanel("type",widget=Select), FieldPanel("depended_choice",widget=Select),] I have to have different lists in Wagtail admin area for Select menu for depended_choice depending on selected Type -
not showing error in terminal and not working function code for delete help me to solve
def delete_video(request, id): if request.method=='POST': Pi=Info_techModel.objects.get(pk=id) pi.delete() return HttpResponseRedirect('/')` <a href="delete_video/{{i.id}}"><i class="fas fa-trash" style="color:red;"></i></a>urlpatterns=[ path('', views.It_view, name='index'), path('update_video/int:id', views.update_video, name='update'), path('delete_video/int:id',views.delete_video, name='delete') ]` -
Bootstrap/css issue - Elements not using static files in django
I am trying to develop a Django application with a downloaded template. The HTML template starts breaking after exporting to Django in the static folder. I have ensured that the static links are defined between {% static ' '%} everywhere still, the page doesn't seem to look like the template before. My HTML page now: The template which actually should be: I tried to debug and these are console errors I see: I am not good with bootstrap and CSS. I do not understand where's the error. Can anyone help me out with where should I fix it? Sharing the scripts declared in the base HTML file below: {% load static %} {% static "images" as baseUrl %} <!DOCTYPE html> <html lang="en"> <!-- Basic --> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- Mobile Metas --> <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <!-- Site Metas --> <title>Create CV Resume - Responsive HTML5 Template</title> <meta name="keywords" content=""> <meta name="description" content=""> <meta name="author" content=""> <!-- Site Icons --> <link rel="shortcut icon" href="#" type="image/x-icon" /> <link rel="apple-touch-icon" href="#" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <!-- Pogo Slider CSS --> <link rel="stylesheet" href="{% static 'css/pogo-slider.min.css' %}"> <!-- Site CSS --> … -
How to change each element of django template for loop with javascript
{% for transaction in transactions %} <ul> <li>{{transaction.number}}</li> <li id = "price">{{transaction.price}} USD </li> <li>{{transaction.created}}</li> </ul> <hr> {% endfor %} I made currency converter option with api. In this case user has 3 transactions. How can i change each transaction's currency with javascript after using dropdown menu? When i change currency by document.getElementById("price").innerHTML = ${totalExchangeRate2} ${selectValue}; (it is onchange with dropdown menu) only first price changes. How to make this django loop avaible in javascript or something like this? -
Conflict among def : has_permission and has_OBJECT_permission Python-Django
I write a Djando program. I need to implement a backend for a mobile application with ads. Ads can be created (POST), modified (PATCH) (only the creator of the ad can) and viewed (GET). I have limited only 10 Ads with status = 'OPEN'. unAuthenticated user can do only (GET) API request. I'm sending a 'PATCH' API request to change a declaration. But the debugger only passes has_permission and does not access to has_object_permission. It only accesses has_object_permission if there is no has_permission. How can I make both methods work at the same time? file - permissions.py class IsOwnerOrReadOnly(permissions.BasePermission): def has_permission(self, request, view): if request.method == 'GET': return True if request.method == 'POST' \ and Advertisement.objects.filter \ (creator=request.user, status = 'OPEN').count() < 10: return [IsAuthenticated()] return [] def has_object_permission(self, request, view, obj): if request.method == 'PATCH': return request.user.is_authenticated and obj.creator == request.user return [] file - views.py class AdvertisementViewSet(ModelViewSet): """ViewSet for Advertisement.""" queryset = Advertisement.objects.all() serializer_class = AdvertisementSerializer permission_classes = [IsOwnerOrReadOnly] #throttle_classes = [AnonRateThrottle] API- request # attempt to change ad PATCH {{baseUrl}}/advertisements/2/ Content-Type: application/json Authorization: Token 8affcdadbdd6b9f8ebefa5a552aa127ebff60178 { "status": "CLOSED" } -
Why am I getting a 415 {detail: 'Unsupported media type "applicaton/json" in request.'} error
I am making a post request to my Django rest framework backend but I keep getting a 415 error when I make the fetch request from React. The request works perfectly when I make it from Django Rest Framework but I get 415 error when I make the POST request from React views.py @api_view(["POST"]) def PaymentCreateView(request): if request.method == "POST": serializer = PaymentSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) React const Support = async () => { const response = await fetch('http://127.0.0.1:8000/support/payment-create/',{ method: "POST", credentials: "include", headers: { "Accept": "application/json", "Content-Type": "applicaton/json", }, body:JSON.stringify({ "user": user, "email": email, "phone_number": phone_number, "number_of_apples": number_of_apples, "amount": amount, "message": message, }) }) let data = await response.json() console.log(data) } useEffect(() => { userpage() }, []) const handleSubmit = (e) => { Support() e.preventDefault() } error [error][1] [1]: https://i.stack.imgur.com/PUWI4.png