Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django - model class with non-persistent attribute that should be refreshed on each call
My User class looks like : class User(AbstractBaseUser, SafeDeleteModel, PermissionsMixin): UNKNOWN = 'Unknown' id = models.AutoField(primary_key=True) email = models.EmailField(unique=True) default_organization = models.ForeignKey(to='Organization', on_delete=models.SET_NULL, null=True, related_name='default_organization', blank=True) organizations = models.ManyToManyField(to='Organization', through='UserOrganizationMembership', related_name='users', blank=True) So a user can be a part of multiple organisations. However, each time he logs in, he must log in through ONE organisation. Now I have two kinds of orgs present - internal, client I have some telemetry setup for my application and the idea is that i want to not send any telemetry for internal orgs. I want to create an attribute in the /users api that returns this flag (flag depends on both the user and the account he logs in through). My view class looks like this: class UsersViewSet(UpdateModelMixin, ListModelMixin, GenericViewSet): queryset = User.objects.all() serializer_class = UserDetailSerializer def get_serializer_context(self): context = super().get_serializer_context() #self.request.user.is_telemetry_enabled =should_send_event(self.request.user, self.request.tenant.is_internal) context.update({"request": self.request}) return context def get_permissions(self): permission_classes = [IsStaff] if self.action in ('list',) else [CanEditUser] return [permission() for permission in permission_classes] What I've looked at : adding a field in model class and setting it in the get_serializer_context. Doesn't work because adding a field in model makes it a class variable, not per instance. second, it still didn't show up … -
How to change default USER Authorisation to custom model in DRF
I have model.py file which has one model named as Tutor class Tutor(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.CharField(max_length=255) password = models.CharField(max_length=255) I want to implement token authentication using this Tutor model, for login and signup. As of now I have setup token authentication and its working good, but its default authorisation is for USER, which get generated using python manage.py createsuperuser, and I want to use Tutor for Authroization. How to go building this, any resources for my usecase would mean a lot :) -
I wants to show image on homepage after login in django
In views.py file in the function what i have to write in code. Model name where the filename is stored is student and field name is filename def home(request): id = request.user.id result = User.objects.get(pk=id) context = {'result' : result} return render(request, 'customer/shome.html', context) -
Django Async View - Model __str__
I'm trying to convert my existing Django 4.1 app to async due to performance reasons. It's more of a struggle than I initially anticipated. Below is some test code: async def diagrams(request): tests = await sync_to_async(list)(Test.objects.filter(name='Test 1')) print(tests) return render(request, 'analyticsApp/test.html') class Test2(models.Model): name = models.CharField(max_length=50, default='', blank=True) def __str__(self): return self.name class Test(models.Model): name = models.CharField(max_length=50, default='', blank=True) testForeignKey = models.ForeignKey(Test2, editable=True, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name + '_' + self.testForeignKey.name So I kind of figured out how to "filter" objects using async_to_async. However, a problem that I'm struggling to solve is using __str__ in a Model. All of my models use __str__ to give accurate string depcitions of the model. It seems like this cannot be done ? I tried to convert def __str__ to async def __str__ but django is not awaiting this when it is being called so it causes problems. Any idea how to handle this ? -
Why I'm getting "Not Found: /api/products/undefined" instead of /api/products/1?
I want to get data of a single product from "api/products/id" (I'm using Django Rest Framework) and put them into redux store, so when I refresh product's page the data will be actually displayed. The problem is, when I go to "localhost:3000/products/1" (I'm using also React) instead of getting product with id = 1, I get undefined product and no data at all. The deeper point I've found where id is undefined is in views.py Why this problem occurs? It has some connection with migration? I deleted database *.pyc + *.py files except init and then once again run makemigrations and migrate but nothing changed. And how can I solve it? Browser's consol: VS Code terminal views.py @api_view(['GET']) def getProduct(request, pk): print("\n\n\nPlural key: ", pk) # The pk is undefined product = Product.objects.get(id=pk) # So the product also is undefined serializer = ProductSerializer(product, many=False) return Response(serializer.data) serializer.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' models.py from django.contrib.auth.models import User class Product(models.Model): # ID is generating automatically user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) image = models.ImageField(null=True, blank=True, default='/placeholder.png') brand = models.CharField(max_length=200, null=True, blank=True) category = models.CharField(max_length=200, null=True, blank=True) description = models.TextField(null=True, blank=True) rating = … -
Get first Item in a django orm query for each unique value of a column
I have a table of Snapshots. It has the following attributes: device_ip created_at name There are multiple records in the table. Various records can have the same device_ip but will have unique names. I want to fetch the latest record for each device_ip ordered by created_at. I am using MySQL database. Here is what I tried: Snapshot.objects.filter(device_ip__in=device_ip_list) .order_by("-created_at") .values( "device_ip", "name", "created_at" ).first() But It provides the last record of the table. Suggestions?