Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamically Change Ordering of `fields` of Django Serializer using DynamicFieldsModelSerializer
I have been using DynamicFieldsModelSerializer like so: class DynamicFieldsModelSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) if fields is None: request = self.context.get('request') if request is None: return fields = request.query_params.get('fields') if fields is None: return fields = fields.split(',') # Drop any fields that are not specified in the 'fields' argument allowed = set(fields) existing = set(self.fields.keys()) for field_name in existing - allowed: self.fields.pop(field_name) And the Serializer in question inherits the above class. Like so: class OrderReportSerializer(DynamicFieldsModelSerializer): card = CardSerializer(fields=('id', 'name')) board = BoardIDSerializer(source='card.board') customer = CustomerIdNameSerializer(source='card.customer') supplier = SupplierIdNameSerializer(source='card.supplier') quantity = serializers.CharField(source='card.quantity') . . . class Meta: model = Order fields = ( # fields whose source is Card 'local_ordered_date', 'card', 'country', 'customer', 'supplier', . . . ) And the view that uses aforementioned Serializer is following: class SomeView(): def table_view(self, queryset, **kwargs): user = kwargs["user"] """ Override if different logic is required to display report data in table view. """ report_model = Report.objects.get(user=user, report_type=self.__str__()) fields = report_model.table_fields queryset = queryset.select_related( 'card__board', 'card__customer', 'card__supplier', ... ... ) if 'balance' in fields or 'invoice_total' in fields: ... ... return OrderReportSerializer( queryset, … -
Django Rest Framework Dynamic Filter against the url
views.py class ProductFilterView(APIView): permission_classes = [AllowAny] serializer_class = SpecificationListSerializer filter_fields = ('title', 'price') def get(self, request, *args, **kwargs): qs = list_products() filter_params = {} for filter in self.filter_fields: query_params = self.request.query_params.get(filter) if query_params: if ',' in query_params: filter_params[filter] = query_params.split(',') else: filter_params[filter] = query_params serializer = self.serializer_class(qs.filter(**filter_params), many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) i have filter_fields = ('title', 'price'), and i want to make it dynamic. i want to get all fields from serializer serializers.py class SpecificationListSerializer(serializers.ModelSerializer): """Serializer For SpecificationCategory""" category = CategorySerializer(many=True) #product = ProductSerializer(many=True) title = serializers.CharField() class Meta: model = Specifications fields = '__all__' def get_category(self, obj): fieldebi = obj.fields.all() return fieldebi there is something wrong, i want to give all fields taken in serializer and to be shown in views.py as filter_fields. is there any way to do it? -
How to add comment to APIView class method assigned as reference inside the class?
Here is how the method has been written in the class: class ChangePasswordView(views.APIView): def put(self, request): '''Description is here''' ... post = put I want to add a custom comment to the post method. How can I do that? -
Django Rest Framework API Testing with Token authentication and IsAdmin permission Returning 401, AssertionError
good people, I am writing test cases for my django rest framework API for the first time. I have used token authentication and is admin permission. I have written some api endpoint tests. The tests run fine without authentication. I have also done this in POSTMAN and with providing token authorization at headers it runs fine there. But whenever I am running the unit test cases with token authentication and is admin permission it is returning me 401, assertion error. I am stuck with this for the last two days. Can anyone please help me to figure out where I am doing wrong? I am providing my code below: My Model: class Vendor(models.Model): user = models.ForeignKey(MyUser, on_delete=models.CASCADE, related_name='myuser') vendor_name = models.CharField(max_length=100) vendor_type = models.CharField(max_length=100, choices=Vendor_Type) display_name = models.CharField(max_length=100) vendor_mail = models.CharField(max_length=255) vendor_phone = models.CharField(max_length=15) vendor_address = models.CharField(max_length=255) def __str__(self): return self.display_name My serializer: class VendorSerializer(serializers.ModelSerializer): address_details = VendorAddressDetailSerializer(read_only=True, source='detaisaddress') sales_person = VendorContactSerializer(read_only=True, source='contactperson') social_account = VendorSocialSerializer(read_only=True, source='vendorsocial') class Meta: model = Vendor fields = ['id','vendor_name', 'vendor_type', 'display_name', 'vendor_mail', 'vendor_phone','vendor_address', 'user', 'address_details', 'sales_person', 'social_account'] My view: class VendorViewSet(viewsets.ModelViewSet): queryset = Vendor.objects.all() serializer_class = VendorSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAdminUser] URL Patterns: router = DefaultRouter() router.register('vendors', VendorViewSet, basename='vendors') urlpatterns = [ … -
Create SPA applications with Django and Vanilla.js
How can I make SPA applications in Django and vanilla.js. Is there a way to only send a template as string, and render it on the front-end using javascript? Any help is highly appreciated. Thank you -
How to generate a pdf in angular and save it in django server's filesystem
I'm working on a feature that requires to send pdf as attachements to email. I use Django's MailMultiAlternative class to send the mails. I generate my PDF file in my front-end side, using Angular. I know i can use Django's templates to generate a pdf, but i already have my Angular component finished and interpolated, plus i'm using scss in Angular, and i don't want to make the styles of the document in django templates, if possible. Is there any way to automatically generate, upload on the server, and send the PDF without requiring the user to download it. What i would like -
How can I change price on changing selecting different from dropdown? (Django)
Html <select class="tranactionID" style="width: 250px;"> {% for val in productID.list %} <option price={{val.Price}} class="price_value" >{{val.AUID}} - {{val.Description}} - {{val.Price}}</option> {% endfor %} </select> <div class="pricing"> <p class="price"><span class="mr-2 price-dc">Rs. </span><span class="price-sale" id='id_price'>Rs. </span></p> </div> Script <script> $(document).on("change", '.price_value', function (event) { event.preventDefault(); console.log($('#id_price').val($(this).children(":selected").attr("price"))); }); </script> Problem In the dropdown I have different values from the server and {{val.price}} represents the price of each item. Now what I want is that if I change the option value from the dropdown the price should be updated in the " for price" respectively. -
Send newline char in urllib.quote in Django
I'm trying to send two sentences (newline between them) using urllib.quote to Django template but unable to get the newline on template. I've tried .encode("utf-8") and %0A but none of them working. Here's my code: # s = "Some string over here. %0A Some string there." s = "Some string over here. \n Some string there." WEBROOT = "{}://{}/mytemplate/?message={}".format( protocol, Site.objects.get_current(), urllib.quote( s.encode('utf8') ), ) return HttpResponseRedirect(WEBROOT) In Template: <div class="subtitle"> {% if message %} <span>{{ message }}</span> {% else %} .... {% endif %} </div> What I want: Some string over here. Some string there. What I'm getting: Some string over here. \n Some string there. or, Some string over here. %0A Some string there. -
DRF: request.user returns nothing for token based authentication
I am basically new to DRF & trying to make one API endpoint to update user via mobile app,here is my code for that, class MobileAppUserUpdateView(APIView): def post(self, request, format=None): user = request.user print('USER',user) #<- prints nothing print('TOKEN',request.auth) #<- prints the token return ResponseBuilder.success([constants.RECORD_UPDATED]) there I want to access the user who has made that request using the auth token but getting nothing there.Here is my settings for DRF, NON_FIELD_ERRORS_KEY = 'message' REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', # 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'NON_FIELD_ERRORS_KEY': NON_FIELD_ERRORS_KEY, } I have also added the "rest_framework.authtoken" in the INSTALLED_APPS list as per the documentation.Any help would be appreciated... -
'>' not supported between instances of 'QuerySet' and 'int' in Django
this is my code: now = datetime.datetime.now() before_requests = MyModel.objects.filter(expired_at__lte=now) and i have this error: DateTimeField MyModel.expired_at received a naive datetime (2021-06-22 11:34:44.810749) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" '>' not supported between instances of 'QuerySet' and 'int' can every one help me? -
Assign/Mapping Multiple Country to user Django
I have a list of Countries as Master Model. Now I want to map/assign one or more Countries to a user in Profile. Model.py from django.db import models from django.conf import settings from Roads.models import CountryMaster class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) country = models.ForeignKey(CountryMaster, on_delete=models.DO_NOTHING, null=True) views.py @login_required def edit(request): if request.method == 'POST': user_form = UserEditForm(instance=request.user, data=request.POST) profile_form = ProfileEditForm(instance=request.user.profile, data=request.POST, files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() else: user_form = UserEditForm(instance=request.user) profile_form = ProfileEditForm(instance=request.user.profile) return render(request, 'account/edit.html', { 'user_form': user_form, 'profile_form': profile_form }) Forms.py class ProfileEditForm(forms.ModelForm): class Meta: model = Profile fields = ('country', ) widgets = {'country': forms.SelectMultiple} I was able to do till here. I want to assign multiple Countries to a User Profile. -
Django DateTimeField showing different time in shell and browser
I just made a Coupon model in Django and displaying the valid_from and valid_till in the template. The value show in django shell ORM is the actual time created, and count 20days from it till it expires. However the one in template keep showing the CURRENT time and counts 20days from the CURRENT time. It's my first time trying something outside of tutorial and I don't know how to pinpoint a "fix", especially when django orm shell is showing the right time as I intended. models.py from django.db import models from django.contrib.auth.models import User from PIL import Image from django.utils import timezone from datetime import timedelta import uuid class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img= Image.open(self.image.path) if img.height> 300 or img.width> 300: output_size= (300, 300) img.thumbnail(output_size) img.save(self.image.path) def twentydays_coupon(): return timezone.now()+ timedelta(days=20) class Coupon(models.Model): user= models.OneToOneField(User, on_delete= models.CASCADE) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) valid_from= models.DateTimeField(default=timezone.now) valid_till= models.DateTimeField(default=twentydays_coupon) def __str__(self): return f'{self.user.username} Coupon' views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm from .models import Coupon def register(request): if request.method … -
django 2d payment getway using django-paypal in uk
I'm using django-paypal to implement my payments in uk, i know the basic usage of the package but, i'm wondering if it has 2d support for UK? (new to payments sorry if missed up things..) -
How can I add pictures in Openstreetmap folium marker popup using django database?
I am using openstreetmap for showing data. I need to add image in marker popup and image will come from django database. SO how can I do that? #this is my code for i in qs: folium.Marker([i.latitude, i.longtitude], tooltip='click here for more', popup= "", icon=folium.Icon(color='green', icon='user')).add_to(map1) and it gives me this error. TypeError at /location/map/ can only concatenate str (not "ImageFieldFile") to str -
How to get the updated value in django UpdateView after updating the profile information?
I am successfully able to update the user info, but I am not able to redirect the user to the new url The url for profile is below: from django.urls import path, include from users import views as user_views from .views import SignUpView, ProfileUpdateView urlpatterns = [ path('profile/<str:username>', user_views.profile, name='profile'), path('profile/<str:username>/update', ProfileUpdateView.as_view(), name='profile-update'), path('register/', SignUpView.as_view(), name='register'), path('captcha/', include('captcha.urls')), ] So when I update my username from xyz to abc, it redirects me to profile/xyz and not profile/abc my views.py: class ProfileUpdateView(UpdateView): model = User template_name = "users/profile_update.html" success_message = "Your profile was updated successfully" slug_url_kwarg = 'username' slug_field = 'username' context_object_name = 'profile' fields = ['username', 'email'] second_form_class = ProfileUpdateForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["form2"] = ProfileUpdateForm(self.request.POST, self.request.FILES, instance = self.request.user.profile) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form2 = self.second_form_class(request.POST, request.FILES,instance=self.request.user.profile) if form2.is_valid(): profile = form2.save(commit=False) profile.user = request.user profile.save() form = self.get_form() return self.form_valid(form) else: return self.form_invalid(form) def get_success_url(self): self.object = self.get_object() form = self.get_form() username=form.cleaned_data['username'] user = User.objects.get(username=self.request.username) print(user) return reverse_lazy("profile", kwargs={'username': self.user}) -
Django multiple of the same dependent dropdownboxs in one form
I have a problem with the following; I have a dependent dropdown menu in a Django model form. Now I want to use it several times in the same form but I can't get it to work if I load more than one then I can only enter/use one. And I have a 2nd problem if this works how do I get the different values in a list/array so that I can store them in the db? The ultimate goal is to select how many beams are desired and on that basis to be able to enter the desired hours, ion species, energy and flux per beam. My code is as follows: models.py from django.db import models from smart_selects.db_fields import ChainedForeignKey class IonSpecies(models.Model): # ionspecie = models.CharField(max_length=10) Name = models.CharField(max_length=10) def __str__(self): # return self.ionspecie return self.Name class Energys(models.Model): Ion_Species = models.ForeignKey(IonSpecies, on_delete=models.CASCADE) Name = models.CharField(max_length=50) def __str__(self): # return self.energy return self.Name # Create your models here. class CreateBeamRequestModel(models.Model): #status choices SELECT = 'Select' REQUEST = 'Request' TENTATIVE = 'Tentavive' ACCEPTED = 'Accepted' CONFIRMED = 'Confirmed' CANCELLED = 'Cancelled' COMPLETED = 'Completed' QUEUED = 'Queued' STATUS_CHOICES = [ (SELECT, ('Select an option')), (REQUEST, ('Request')), (TENTATIVE, ('Tentative')), (ACCEPTED, ('Accepted')), (CONFIRMED, … -
In Django admin, how can I hide another related model field when adding it to the "Tədris" model?
I tried to do it with signals but I couldn't. Models and their images on the admin panel. Please help me https://i.stack.imgur.com/A3zS0.png https://i.stack.imgur.com/edtrK.png https://i.stack.imgur.com/yNio1.png https://i.stack.imgur.com/plhUW.png -
Django error : struct.error: unpack requires a buffer of 4 bytes
I hope you are fine . I will thank if anyone help me to solve error below that is for django while activating a language for making a multi language website . Thanks . Best wishes . struct.error: unpack requires a buffer of 4 bytes -
How to add unique_together for id and key inside Jsonfied in Django?
This how my model looks like. class TestModel(models.Model): data = models.JSONField( verbose_name=_("user data"), validators=[user_data_validator], ) class Meta: unique_together = ["id", "data__userId"] This is the schema for data field class DataSchema(BaseModel): userId = UUID How to make unique_together for id and userId from the JsonField? -
Django and Javascript: Take Info From API And Save To Database
I'm very new to Javascript with Django and I'm looking for some basic info on how to take info from an API that has already been returned, and post it to the database. I have used views.py to take information and save it to the database, but I haven't done this with info from an API that is achieved in Javascript. My project is a weather app that gets info from OpenWeather for a city that the user types into a box, and that part works - the API information is returned. I currently have a model for each Location, I just don't know how to save it in the database. Is this done through fetch, using POST? I am also slightly confused about how the urls would be setup. Any information, maybe some sample github code, could help :) For example, if I want to get the location and then add it to my 'favorites' would something like this make sense? I know I would still need to make the view, and url. const location_content = document.querySelector('#content').value; function add_to_fav() { fetch('/favorites', { method: 'POST', body: JSON.stringify({ location_content: location_content }) }) .then(response => response.json()) .then(result => { console.log(result); }); localStorage.clear(); … -
What's the difference between "id" and "pk" parameter with get_object_or_404
I am learning Django. When I was learning how to use get_object_or_404, I noticed that some codes specify id as the argument of get_object_or_404, while others specify pk. It seems that whether I specify id or pk, the result is the same. foo1 = get_object_or_404(FooModel, pk=1) foo2 = get_object_or_404(FooModel, id=1) """ FooModels table has some records that includes id is 1. When I access foo/1, foo1 and foo2 have the same values. """ How do you use these parameters differently? Or if there is something fundamentally wrong with my thinking, please let me know. Thanks. models.py from django.db import models from django.utils import timezone class FooModel(models.Model): name = models.CharField('name', max_length=20) body = models.CharField('body', max_length=100) created_at = models.DateTimeField('created_at', default=timezone.now) urls.py from . import views urlpatterns = [ path("foo/<int:id>", views.foo), ] views.py from django.shortcuts import get_object_or_404 from .models import FooModel def foo(request, id) foo1 = get_object_or_404(FooModel, pk=id) foo2 = get_object_or_404(FooModel, id=id) """ FooModels table has some records that includes id is 1. When I access foo/1, foo1 and foo2 have the same values. """ $ python -m django --version 2.2.20 $ python --version Python 3.7.9 -
Django POST request from a HTML dynamic form
I have develop a dynamic form with Bootstrap and Javascript, now I'd like to post that information in sql3 database (default django database), so I made a POST REQUEST in HTML file, views.py and the respective models.py But when I try to push the submit bottom from the form, nothings happens, I think the issue is how the form was made, but I can't figure out how to solve it. Infraestructura.html {% extends "Portafolio/layout.html" %} {% load static %} {% block scripts %} <script src = "{% static 'Portafolio/scriptinfra.js' %}" type="text/javascript"></script> {% endblock %} {% block content %} <form action= "{% url 'infraestructura' %}" method="POST" class="form mt-5" id="infra"> {% csrf_token %} <h1>Factibilidad Técnica y Operativa</h1> <h2>Análisis de Infraestructura</h2> <main class="container"> <section class="row"> <div class="col-lg-4 mb-2"> <input name='Infraestructura' class="form-control" type="text" placeholder="Infraestructura"> </div> <div class="col-lg-4 mb-2"> <input name='Tiempo' class="form-control" type="text" placeholder="Tiempo"> </div> <div class="col-lg-4 mb-2"> <input name='Costo' class="form-control" type="text" placeholder="Costo Mensual"> </div> </section> </main> <nav class="btn-group"> <button id='add' class='btn btn-success' type='button'> <i class="fa fa-plus-square"></i> Añadir </button> <button id='rem' class='btn btn-danger' type='button'> <i class="fa fa-minus-square"></i> Eliminar </button> </nav> <!-- Submit buttom--> <div class="d-grid gap-2 mt-3"> <input type="submit" class="btn btn-lg btn-primary"> </div> </form> {% endblock %} views.py def infraestructura(request): if request.method =='POST': Infraestructura = … -
Adding Background Image Using CSS
In my django project I try to add background image to html template. But it does not work my code is like this background-image: url("/img/bg.jpg"); error GET http://127.0.0.1:8000/img/bg.jpg 404 (Not Found) Please help me to fix this I try it different ways... -
django.core.exceptions.ImproperlyConfigured: Cannot import 'category'. Check that 'api.category.apps.CategoryConfig.name' is correct
I am using 3.2 django, and rest framework . main project name is ECOM and api is app .Inside api there are multiple apps like category,migrations,order,payment,product,user. Now I want to inform ecom.settings about installed api. HOW I should do it ? SETTING.PY OF ECOM : INSTALLED_APPS = [ #other basic install 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'api', 'api.category', ] but getting error. My category apps.py file looks like class CategoryConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'category' GIT hub link is https://github.com/Jhaamlal/DJANGO_REACT -
How can i bind two serializers into separate one serializer django rest framework?
info: One is User and the Second one is User Data like phone number,city etc Now i can add these two serializer into third serializer and show all data in third one Problem: now i want to create new Serializer Where i can combine both serializer attributes. but i don't understand how can i achieve to bind two serializer into different one and show all data? serializers.py class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = ['email', 'phone'] class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = ['city'] Want to achieve class CombineSerializer(serializers.ModelSerializer): class Meta: fields = ['email', 'phone', 'city']