Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get user id in the serializer for the token authenticated user in DRF
How can I get the user from token in serializer? I am getting the id in views but I need in serializer for applying a filter in queryset of nested queryset. views.py class UserListAPIView(generics.ListAPIView): permission_classes = (permissions.IsAuthenticated, jwtPermissions.IsSSOAdminOrReadOnly,) queryset = userModels.User.objects.all() serializer_class = serializers.UserSerializers def get_queryset(self): return self.queryset.filter(id=self.request.user.id) serializers.py class UserSerializers(serializers.ModelSerializer): class Meta: model = userModel.User fields = ('id','email','name','contact_no','address','is_active','solutions') def to_representation(self, instance): rep = super().to_representation(instance) rep['component'] = ComponentUserSerializers(instance.component.all(), many=True).data return rep class ComponentUserSerializers(serializers.ModelSerializer): user_devices = serializers.SerializerMethodField() def get_user_devices(self, obj): #self.context['request'].user.id <-- getting null user_devices_queryset = sensorModel.UserSensorDevice.objects.filter(sensor_type=obj.id, user = self.context['request'].user.id) user_devices_serializer = sensorSerializers.UserSensorDeviceSerializer(user_devices_queryset, many=True) return user_devices_serializer.data class Meta: model = coreModel.Component fields = ('id','comp_code','part_no', 'user_devices') I need to apply a filter in ComponentUserSerializer in get_user_devices API. And I am not getting user_id of the token authenticated user. -
Django - Update one fields value automatically after a value change
I am new to django and I have a simple question. I have two model: Model RegisterLogin and Model OtpEmailVerify. I wanna make 'is_verified' field of Model OtpEmailVerify 'True' as long as 'otp_no' provided matches with the 'otp' field of model LoginRegister. models.py class RegisterLogin(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now_add=True) email = models.EmailField(unique=True) first_name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) phone_regex = RegexValidator(regex=r'\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999-999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=15, blank=False, unique=True) sign_up_for_newspaper = models.BooleanField(default=False) allow_remote_shopping_assistance = models.BooleanField(default=False) otp = models.CharField(null=False, unique=False, max_length=5) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'phone_number'] def __str__(self): return self.email def save(self, *args, **kwargs): otp_choice = '1234567890' for i in range(5): self.otp += str(random.choice(otp_choice)) super(RegisterLogin, self).save() class OtpEmailVerify(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) otp_no = models.IntegerField(default=0, help_text='Please enter the Otp that has been sent for ' 'verification ') user = models.OneToOneField(RegisterLogin, null=False, on_delete=models.CASCADE) is_verified = models.BooleanField(default=False, help_text='if it is true, that means can now validate otp for verification') def __str__(self): return self.otp_no def save(self, *args, **kwargs): if self.otp_no == self.user.otp: return not self.is_verified else: return ValidationError('Wrong Otp Provided.') views.py class OtpVerifyView(generics.CreateAPIView): queryset = OtpEmailVerify.objects.all() serializer_class = … -
Unable to install Misaka
I tried installing wheels and again ran pip install misaka but I'm ending up with the same error. Misaka installation error! -
How to access the dictionary keys and values in django templates
I have created a dictionary of message senders which is updating dynamically. If I print the dictionary keys in the python console window, I am getting the expected output but when I try to access the values in the Django template, I am getting nothing here is my python code; views.py def home(request): senders = {} chatting =Message.objects.filter(seen=False) for msg in chatting: user = User.objects.get(id=msg.sender.id) if user != request.user and user not in senders.values(): senders.update({user.id : user}) return render(request, 'home.html', senders) template Home.html <div> {% for key, val in senders %} <div> <a href="#">{{val}}</a> </div> {% endfor %} </div> -
Auto generate classes in python
I want to create a new subclass of a base class after creating an object in my django admin project. Auto creation of class that I want is something like django migration when createmigration is execute. How can I do it? -
How to pass serializer.data into create function in views django
views.py def productslist(request): products = Products.objects.all() context = {'products':products} return render(request,'productslist.html',context) def productsform(request): return render(request,'productscreate.html') @api_view(['GET','POST']) def products_list(request): if request.method == 'GET': product = Products.objects.all() serializer = Productserialize(product,many=True) return Response(serializer.data) elif request.method == 'POST': serializer = Productserialize(data=request.data) if serializer.is_valid(): def create(serializer): return Products.objects.create(serializer) return Response(serializer.data) return Response(serializer.errors) @api_view(['GET','PUT']) def products_detail(request, pk): products = Products.objects.get(pk=pk) if request.method == 'GET': serializer = Productserialize(products) return Response(serializer.data) elif request.method == 'PUT': serializer = Productserialize(products, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) In views.py I have done create function but it is not working not saving data I want to save serializer data using create function I want to pass serializer.data into create function in post method api Please help me to solve this Thanks in advance serializer.py from rest_framework import serializers from .models import Products class Productserialize(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, allow_blank=True, max_length=100) description = serializers.CharField(required=False, allow_blank=True, max_length=100) image = serializers.FileField() def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return Products.objects.create(**validated_data) -
Django keep open tab
Is there any way to redirect home and keep the open tab. views.py from django.views.decorators.http import require_http_methods @require_http_methods(["POST"]) def reply(request,messageID): print(messageID) parent = Messages.objects.get(id=messageID) reply = Messages.objects.create(text=request.POST['text'], receiver=parent.sender, sender=request.user, parent=parent) print(parent) print(reply) print(request.POST) return redirect('home') html: {% block content %} <div class="col-md-3" style="float:left"> <h1>Hi {{ user.username }}!</h1> <img class="avatar" src="{{user.get_profile_pic_url}}" > <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#editProfile">+</button> <ul class="nav nav-tabs flex-column" id="myTab" role="tablist"> <li class="nav-item" role="presentation"> <a class="nav-link active" id="home-tab" data-bs-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Dashboard</a> </li> <li class="nav-item dropdown" role="presentation"> <a class="nav-link dropdown-toggle" id="messages-tab" data-bs-toggle="dropdown" aria-expanded="false">Messages</a> <ul class="dropdown-menu"> <li><a class="dropdown-item" id="messages-send-tab" data-bs-toggle="tab" href="#messagesSend" role="tab" aria-controls="messagesSend" aria-selected="false">Send</a></li> <li><a class="dropdown-item" id="messages-inbox-tab" data-bs-toggle="tab" href="#messagesInbox" role="tab" aria-controls="messagesInbox" aria-selected="false">Inbox</a></li> </ul> </li> </ul> </div> <div class="col-md-9" style="float:right"> <div class="tab-content" id="myTabContent"> <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab"> {% include 'dashboard.html' %} </div> <div class="tab-pane fade" id="messagesSend" role="tabpanel" aria-labelledby="messages-send-tab"> {% include 'sendMessageForm.html' %} </div> <div class="tab-pane fade" id="messagesInbox" role="tabpanel" aria-labelledby="messages-inbox-tab"> {% include 'inbox.html' %} </div> </div> </div> {% endblock %} -
How to send Django model object's details as answer according to the user's choice of InlineKeyboardButton?
I'm new to creating telegram bots with Django. I selected python-telegram-bot library for creating bots with Django. I've created a Django model, named as category: class category(models.Model): name = models.CharField(max_length=250) category_id = models.IntegerField() def __str__(self): return self.name and product: class product(models.Model): product_category = models.ForeignKey(category, on_delete=models.SET_NULL, blank=True, null=True) name = models.CharField(max_length=250) cost = models.FloatField() img = models.ImageField() def __str__(self): return self.name Successfully created InlineKeyboardButtons and placed id of each product model object to each button, with these functions: def product(update: Update, context: CallbackContext): query = update.callback_query.data product_button_list = [] for each in product.objects.select_related().filter(product_category_id = query): product_button_list.append(InlineKeyboardButton(each.name, callback_data=each.id)) reply_markup = InlineKeyboardMarkup(build_menu(product_button_list,n_cols=2)) update.callback_query.message.edit_text("Mahsulotni tanlang!", reply_markup=reply_markup) def build_menu(buttons,n_cols,header_buttons=None,footer_buttons=None): menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)] if header_buttons: menu.insert(0, header_buttons) if footer_buttons: menu.append(footer_buttons) return menu When the user selects a button named as the name of the product model object, I am receiving the correct id of the product model object, tested with printing the query: def product_info(update: Update, context: CallbackContext): query = update.callback_query.data print(query) obj = albus_product.objects.filter(pk=query) print(obj) Question: How to reply Django product model object's fields including its image to the user according to the user's chosen product? Like: You have chosen a product: Image of the product Name … -
Django, assigning a composite value to one field depending upon values entered in other fields in same model?
I am new to django. What I am currently trying to do is set a value which is a primary key and non-editable automatically generated depending upon the values entered in the same model to some other fields. Here is an example: class Student(models.Model): student_id = models.CharField(max_length=100, primary_key=true) name = models.CharField(max_length=100) class = models.CharField(max_length=200) roll_no = models.CharField(max_length=500) So, what I am trying to achieve is if someone enters following information : name = Haris class = 8th roll_no = 104011 The automatically generated primary key that would be non-editable for field "student_id" would be: student_id = Haris_8th_104011 Does anyone have an idea how to achieve this? Hope my example made the query clear though. -
ERROR: Command errored out with exit status -11
I ran this command in a virtual environment with Python3.6.7: pip3 install -r requirements.txt --use-deprecated=legacy-resolver Then I got this error: ERROR: Command errored out with exit status -11: command: /home//venv/bin/python /home//venv/lib/python3.6/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-dm6prya6/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'poetry-core>=1.0.0' cwd: None Complete output (0 lines): ERROR: Command errored out with exit status -11: /home//venv/bin/python /home//venv/lib/python3.6/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-dm6prya6/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'poetry-core>=1.0.0' Check the logs for full command output. -
Django pass back some data on post
if not request.user.is_doctor and not request.user.is_staff: bookAppointment = BookAppointmentForm() bookAppointment.fields['doctors'].queryset = Profile.objects.filter(Q(is_active=True)&Q(is_doctor=True)) context['bookAppointment'] = bookAppointment I would like to add data to the page if a dropdown was selected with the above no redirects since I am using the below to pass a table back. d = get_date(request.GET.get('day', None)) print(d) # Instantiate our calendar class with today's year and date cal = Calendar(d.year, d.month) html_cal = cal.formatmonth(withyear=True) # Figure how to pass this context['calendar'] = mark_safe(html_cal) html: <form method = "POST" action='/displayCalendar' enctype="multipart/form-data"> {% csrf_token %} {{ bookAppointment.as_p }} <button type="submit" name='bookAppointment'>Check availability</button> </form> {{calendar}} forms.py class BookAppointmentForm(forms.ModelForm): class Meta: model = Calendar fields = ('doctors',) -
Unauthorized User Error in Django Unit test
Hello! I am writing a unit test case for a website, The website has a basic function of address update, the address update requires an authentic user login, so I am using the temporary token for that purpose in query-param (as a part of website functionality) from django.test import TestCase from accounts.models import Address, User, Business, Employment from accounts.controllers import AddressController class Test_Cases_AddressController(TestCase): user= User.objects.create_user( birth_year=1996, birth_month= 8, birth_day = 15, marital_status= "married", \ reset_password_token = "xxxxy", confirmation_token = "xxxx", password_reset_at= "2022-01-12 13:12:13", \ confirmed_at= "2022-01-12 13:12:13", email= "testuser@example.com", username = "testuser123") def test_update_address(self): address1 = Address.objects.create(street_1="abc abc abc", city="lahore", state="punjab", zip="54000", type="abcdef") API_LOGIN_URL = '/addresses/1/?_t=xxxx/' response= self.client.put(API_LOGIN_URL, {"street_1": "xyz xyz xyz"}, content_type='application/json' ) self.assertEquals(response.status_code, 201) def test_get_address(self): API_LOGIN_URL = '/addresses/1/?_t=xxxx/' response= self.client.get(API_LOGIN_URL) self.assertEquals(response.status_code, 200) but I am still getting the same unauthorized error PS C:\Users\Lenovo\web> docker-compose run --rm api sh -c "python manage.py test accounts" Creating web_api_run ... done Creating test database for alias 'default'... System check identified some issues: WARNINGS: accounts.User.privacy: (postgres.E003) JSONField default should be a callable instead of an instance so that it's not shared between all field instances. HINT: Use a callable instead, e.g., use `dict` instead of `{}`. main.NonProfit.website: (fields.W340) null has no effect … -
django create object using nested serializer and model
Hi i am try to create 3 model objects in single post request from flutter to django restframework but i don't know how to use serializer to create object so I'm implemented many lines of code to done this but it's working fine. It's correct or not View.py from rest_framework.views import APIView from .models import Booking, FromAddress, Product, ToAddress from .serializers import BookingSerializer, FromAddressSerializer from rest_framework.response import Response from rest_framework import status # Create your views here. class BookingView(APIView): def get(self,req): bookings = Booking.objects.all() serializer = BookingSerializer(bookings,many=True) return Response(serializer.data) def post(self,req): user = self.request.user fromAddressData = req.data['from_address'] toAddressData = req.data['to_address'] productData = req.data['product'] from_address = FromAddress.objects.create(name=fromAddressData['name'],phone=fromAddressData['phone'],address=fromAddressData['address'],) to_address = ToAddress.objects.create(name=toAddressData['name'],phone=toAddressData['phone'],address=toAddressData['address'],pincode=toAddressData['pincode'],) product = Product.objects.create(title = productData['title'],weight = productData['weight'],nature_of_content=productData['nature_of_content'],breakable=productData['breakable'],) from_address.save() fadrs = FromAddress.objects.get(id= from_address.id) print(FromAddressSerializer(fadrs)) to_address.save() product.save() booking = Booking.objects.create(user=req.user,from_address=fadrs,to_address=to_address,product= product, price=req.data['price'], payment_id=req.data['payment_id']) booking.save() return Response('Success') Model.py from django.db import models from django.contrib.auth.models import User import uuid # Create your models here. class FromAddress(models.Model): name = models.CharField(max_length=50) phone = models.CharField(max_length=10) address = models.TextField(max_length=200) def __str__(self): return self.name class ToAddress(models.Model): name = models.CharField(max_length=50) phone = models.CharField(max_length=10) address = models.TextField(max_length=200) pincode = models.CharField(max_length=6) def __str__(self): return self.name class Product(models.Model): title = models.CharField(max_length=50) weight = models.DecimalField(max_digits=5,decimal_places=2) nature_of_content = models.CharField(blank=True,null=True,max_length=100) breakable = models.BooleanField(default=False) def __str__(self): return f'{self.title} … -
displaying None instead of data in the form of table
Here, select machine name and operation number, after select and save, It is displaying none instead of data like machine name and operation number in the form of table. Please help me out to solve this. I am new in Django. urls.py: urlpatterns = [ path('upload/',views.upload,name='upload'), path('save',views.save_machine,name='save_machine') ] views.py: def upload(request): machines = Machine.objects.all() return render(request,'usermaster/upload.html',{'machines':machines}) def save_machine(request): if request.method == "POST": machine_name = request.POST.get('machine_name', '') operation_no = request.POST.get('operation_no') choiced_machine = Machine.objects.get(machine_name=machine_name, operation_no=operation_no) machines = Machine.objects.all() return render(request,'usermaster/upload.html',{'machines':machines,'choiced_machine':choiced_machine}) models.py: class Machine(models.Model): machine_name = models.CharField(max_length=200) operation_no = models.IntegerField(null=True) def __str__(self): return self.machine_name upload.html: <form action="{% url 'save_machine' %}" method="post"> {% csrf_token %} <select> <option>Select Machine Name</option> {% for machine in machines %} <option name="machine_name">{{ machine.machine_name }}</option> {% endfor %} </select> <br> <br> <select> <option>Select Operation Number</option> {% for machine in machines %} <option name="operation_no">{{ machine.operation_no }}</option> {% endfor %} </select> <br> <br> <br> <input type="submit" value="Save"> </form> <tr> <td>{{choiced_machine.machine_name}}</td> <td>{{choiced_machine.operation_no}}</td> </tr> -
Adding criteria to Django DRF responsive map InBBoxFilter with viewsets.py, not views.py?
We've developed a responsive map using this tutorial where Django Rest Framework serves responses that populates the map. My viewsets.py: class MarkerViewSet(viewsets.ReadOnlyModelViewSet): """Marker view set.""" bbox_filter_field = "geom" filter_backends = (filters.InBBoxFilter,) queryset = Tablename.objects.all() serializer_class = MarkerSerializer pagination_class = GeoPaginator I'd like to add optional criteria to this filter if they are found in a GET value. The rest of my project uses views.py, which filters things differently. My simplified views.py which does this for something else: def EgFilterView(request): qs = Tablename.objects.all() date_min_query = request.GET.get('dmin') min_date = 1970 qs = qs.filter(date__gte=dt.datetime(int(date_min_query), 1, 1, tzinfo=pytz.UTC)) context = { 'queryset': qs, 'dmin': min_date, } return render(request, "main_page.html", context) But it looks like viewsets.py doesn't handle .get() values in this way, but instead uses .list() and .create(), which I don't understand. How can I include additional filters into my viewsets.py to further filter things with GET values? Would it be better to attempt to convert this viewsets.py / other complicated API stuff I don't understand into views.py? -
How can I restrict users to delete other's posts in django using class based views?
my views.py file: from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.contrib.auth.mixins import ( LoginRequiredMixin, UserPassesTestMixin, ) from .models import Post # Create your views here. class PostListView(ListView): model = Post template_name = "blog/index.html" context_object_name = "posts" ordering = ["-date_posted"] class PostDetailView(DetailView): model = Post class PostCreateView(CreateView, LoginRequiredMixin, UserPassesTestMixin): model = Post fields = ['title', 'genere', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class PostUpdateView(UpdateView, LoginRequiredMixin, UserPassesTestMixin): model = Post success_url = "blog-home" def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False class PostDeleteView(DeleteView, LoginRequiredMixin, UserPassesTestMixin): model = Post success_url = "/" def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False def about(request): return render(request, 'blog/about.html') My models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) genere = models.CharField(max_length=50, default='') def __str__(self): return f'{self.title} by {self.author}' def get_absolute_url(self): return reverse('blog-home') my urls.py url: from django.urls import path from .views import PostListView, … -
JWT authentication for Django rest framework --> error ={ "detail": "Authentication credentials were not provided." }
I'm using JWT for authentication and I can't make this error go away... HTTP 401 Unauthorized Allow: GET, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Bearer realm="api" { "detail": "Authentication credentials were not provided." } Below are all my code files... I think the error is in the simple_jwt section in the settings file but can't figure out what. I looked up a few stackoverflow answers already but nothing seem to work out in my case. settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', # 'rest_framework.authentication.TokenAuthentication', ), } from datetime import timedelta from django.conf import settings SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30), # 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': settings.SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } serializers.py from rest_framework import serializers from django.contrib.auth.models import User from rest_framework_simplejwt.tokens import RefreshToken, Token from .models import Book class UserSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField(read_only=True) _id = serializers.SerializerMethodField(read_only=True) isAdmin = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', '_id', 'email', 'username', 'name', 'isAdmin'] def get__id(self, obj): return obj.id def get_isAdmin(self, obj): return obj.is_staff def get_name(self, obj): … -
Django: Check at model level if anything in ManyToMany field before saving
There's a lot of questions worded similarly, but every single one I've seen is somebody trying to get some kind of data through a ManyToMany relationship before saving it. I'm not trying to use the relationship at all before saving, I just want to see if the user put anything there or not. My model has a ForeignKey field pointing to a parent model, and two ManyToMany fields pointing to other models, but I only want users to be able to use one M2M field or the other, not both. This model is being edited through the admin as an inline on its parent. models.py class ProductSpecial(models.Model): # name, slug, image, etc class ProductSpecialAmount(models.Model): special = models.ForeignKey(ProductSpecial, related_name='amounts', on_delete=models.CASCADE) amount = models.IntegerField() brands = models.ManyToManyField(ProductBrand, related_name='specials', blank=True) lines = models.ManyToManyField(ProductLine, related_name='specials', blank=True) admin.py class ProductSpecialAmountInline(admin.StackedInline): model = ProductSpecialAmount # fieldsets, etc @admin.register(ProductSpecial) class ProductSpecialAdmin(admin.ModelAdmin): inlines = [ProductSpecialAmountInline] # fieldsets, etc I only want users to be able to choose from brands or lines, but not both, and I would like to validate this before save and throw a validation error if necessary. My initial attempt was to just do... class ProductSpecialAmount(models.Model): # ... def clean(self): if self.brands and self.lines: raise … -
Given models relations nested 3 layers what query will return an object I can pass to Django Rest Framework model serializers
Given models related three levels deep how can I construct a query where I can pass the response to a Django Rest Framework model serializer? The code below with one layer of relationship works. Modles class SubArea(models.Model): label = models.CharField(max_length=20) fiber_switch = models.ForeignKey( 'FiberSwitch', related_name='sub_areas') class BackboneLine(models.Model): sub_area = models.ForeignKey( SubArea, related_name='backbone_lines') source = models.ForeignKey( Enclosure, related_name='backbone_lines_out') destination = models.OneToOneField( Enclosure, related_name='backbone_line_in') @property def label(self): return f'{self.source.box_number} - {self.destination.box_number}' Serializers class BackboneLineSerializer(ModelSerializer): class Meta: model = BackboneLine fields = ['label'] class SubAreaSerializer(ModelSerializer): backbone_lines = BackboneLineSerializer(many=True) class Meta: model = SubArea fields = ['label', 'backbone_lines'] Code sub_area = SubArea.objects.get(pk1) sub_area_serialzer = SubAreaSerializer(sub_area) But if I add the model BackboneLineSegments along with a serializer for it, and change the BackoneLineSerializer to handle it I get errors. Added Model class BackboneLineSegment(models.Model): location = models.LineStringField() buried = models.BooleanField(default=False) backbone_line = models.ForeignKey( BackboneLine, related_name='segments' ) New Serializer class BackboneLineSegmentSerializer(GeoFeatureModelSerializer): class Meta: model = BackboneLineSegment geo_field = 'location' fields = ['location', 'buried'] Updated BackboneLineSerializer class BackboneLineSerializer(ModelSerializer): segments = BackboneLineSegmentSerializer(many=True) class Meta: model = BackboneLine fields = ['label', 'segments'] Code sub_area = SubArea.objects.get(pk1) sub_area_serialzer = SubAreaSerializer(sub_area) This throws the following error. Got AttributeError when attempting to get a value for field segments on serializer BackboneLineSerializer. The serializer … -
How to fix Session matching query does not exist?
I made a raw django website to prevent multiple sessions by a user. It worked fine locally but it started throwing errors when I uploaded it to pythonanywhere. This happened after I logged into the site. If you want to log into the site use: E-mail: career Pwd: Qazpl,@123 Here is the error, I get: Environment: Request Method: GET Request URL: https://careerabacusgallery.pythonanywhere.com/ Django Version: 4.0.1 Python Version: 3.9.5 Installed Applications: ['onlinetest.apps.OnlinetestConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'onlinetest.middleware.OneSessionPerUserMiddleware'] Traceback (most recent call last): File "/home/careerabacusgallery/.virtualenvs/test/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/careerabacusgallery/statelevel/onlinetest/middleware.py", line 19, in __call__ Session.objects.get(session_key=stored_session_key).delete() File "/home/careerabacusgallery/.virtualenvs/test/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/careerabacusgallery/.virtualenvs/test/lib/python3.9/site-packages/django/db/models/query.py", line 439, in get raise self.model.DoesNotExist( Exception Type: DoesNotExist at / Exception Value: Session matching query does not exist. My settings.py: """ Django settings for statelevel project. Generated by 'django-admin startproject' using Django 4.0.1. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable … -
How to show data when select and save
I am new in Django. In this project, select machine name and operation number, after select, we need to click on save button, after button click, data should display in the form of table, when button click only. Please tell me where I got wrong. Please. urls.py: urlpatterns = [ path('upload/',views.upload,name='upload'), path('save',views.save_machine,name='save_machine'), ] views.py: def upload(request): machines = Machine.objects.all() return render(request,'usermaster/upload.html',{'machines':machines}) def save_machine(request): if request.method == "POST": machine_name = request.POST.get('machine_name', '') operation_no = request.POST.get('operation_no') choiced_machine = Machine.objects.get(machine_name=machine_name, operation_no=operation_no) machines = Machine.objects.all() return render(request,'usermaster/upload.html',{'machines':machines,'choiced_machine':choiced_machine}) template upload.html <form action="{% url 'save_machine' %}" method="post"> {% csrf_token %} <select> <option>Select Machine Name</option> {% for machine in machines %} <option name="machine_name">{{ machine.machine_name }}</option> {% endfor %} </select> <br> <br> <select> <option>Select Operation Number</option> {% for machine in machines %} <option name="operation_no">{{ machine.operation_no }}</option> {% endfor %} </select> <br> <br> <br> <input type="submit" value="Save"> </form> <tr> <td>{{choiced_machine.machine_name}}</td> <td>{{choiced_machine.operation_no}}</td> </tr> models.py: class Machine(models.Model): machine_name = models.CharField(max_length=200) operation_no = models.IntegerField() def __str__(self): return self.machine_name when I clicked on save button, I got this error: DoesNotExist at /save Machine matching query does not exist. Request Method: POST Request URL: http://localhost:8000/save Django Version: 4.0 Exception Type: DoesNotExist Exception Value: Machine matching query does not exist. Exception Location: C:\Users\Manoj\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py, line 439, … -
How do you add validation to django rest framework api
I have two models, which look like this: class Item(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) sku = models.CharField(max_length=60) description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) location = models.CharField(max_length=60) serial_number = models.CharField(max_length=60) def __str__(self): return self.name class Warehouse(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) def __str__(self): return self.name and they have two serializers which look like this: class ItemSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Item fields = ('id', 'name', 'sku', 'description', 'price', 'location', 'serial_number') #we need a validator that checks if location is in the list of warehouses #we need a validator that checks if sku is in the list of products class WarehouseSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Warehouse fields = ('id', 'name') I need a way to ensure that the location field for newly created items matches an existing name field from a warehouse. I also need the deletion of a warehouse to trigger the deletion of all items in that warehouse, or, failing that; if the warehouse has items, it cannot be deleted. I'm brand new to python and django, so any help would be massively appreciated! for reference, my views class looks like class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all().order_by('name') serializer_class = ItemSerializer class WarehouseViewSet(viewsets.ModelViewSet): queryset = Warehouse.objects.all().order_by('name') serializer_class = … -
Execute a Django view and redirect to another view like a request.POST
When I access my web page, let's say example.com, that url is associated with my index view. def index(request, pid): context = {} context['nbar'] = 'index' if request.method == 'POST': User = get_user_model() users = User.objects.all() context['users'] = users context['project_values'] = Project.objects.get(id=pid) return render(request, 'index.html', context) Inside my template (index.html) I have a button that simply changes the state of a certain project Active <-> Inactive If the user clicks the button, I want the view activate_project or deactivate_project to run in background and when the execution is finished, just reload index.html as a post.REQUEST . What I've tried: Activate - Deactivate views: def activate_project(request, pk): if request.method == 'POST': project_to_activate = ITT.objects.get(pk=pk) if project_to_activate.status == "Inactive": project_to_activate.status = "Active" project_to_activate.save() return redirect('/index/'+str(project_to_activate.id)+'/') def deactivate_project(request, pk): if request.method == 'POST': project_to_deactivate = ITT.objects.get(pk=pk) if project_to_deactivate.status == "Active": project_to_deactivate.status = "Inactive" project_to_deactivate.save() return redirect('/index/'+str(project_to_deactivate.id)+'/') The problem comes here: return redirect('/index/'+str(project_to_deactivate.id)+'/') If I use the redirect, it is treated as a GET instead of a POST. <WSGIRequest: GET '/index/5/'> In short, I need index to know that I am coming from deactivate_project or activate_project, how can I make the view index smart enough to know that? -
Django: How do I use a custom template for a specific sitemap only if I have multiple separate sitemaps?
I want to use a custom template only for a VideoSitemap when I have multiple sitemaps divided as follows: How can I use a custom template only for a specific sitemap? I want to use a custom template for VideoSitemap with a sitemap tag for Video. class VideoSitemap(Sitemap): changefreq = "weekly" def items(self): return Video.objects.published() def location(self, obj): return f"/video/{obj.pk}" def lastmod(self, obj): return obj.updated_at class PlaylistSitemap(Sitemap): ... class TagSitemap(Sitemap): ... # urls.py sitemaps = { "video": VideoSitemap, "playlist": PlaylistSitemap, "tag": TagSitemap } urlpatterns = [ path( "sitemap.xml", sitemaps_views.index, {"sitemaps": sitemaps}, name="django.contrib.sitemaps.views.index", ), path( "sitemap-<section>.xml", sitemaps_views.sitemap, {"sitemaps": sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), ] -
Pass List of UUID to django endpoint url as param
I have this code #VIEWS def report_pdf(request, queryset): if request.method == "GET": trans = Transaction.objects.filter(id__in=queryset) return something #URLS path("pdf/<uuid:queryset>", views.report_pdf, name="get_pdf") Now from my frontend react iam sending a get request to this endpoint with a list of UUID values. I cant find a way to access that list in my view coming from frontend. Would appreciate any suggestions!