Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 121835: character maps to <undefined>
I am building a Location based Webapp and I am stuck on an Error. UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 121835: character maps to This error is keep showing when i migrate the DataBase. migrations.py DATA_FILENAME = 'data.json' def load_data(apps,schema_editor): shop = apps.get_model('mains','Shop') jsonfile = Path(__file__).parents[2] / DATA_FILENAME with open(str(jsonfile)) as datafile: objects = json.load(datafile) for obj in objects['elements']: try: objType == obj['type'] if objType == 'node': tags = obj['tags'] name = tags.get('name','no-name') longitide = obj.get('lon',0) latitude = obj.get('lat',0) location = fromstr(f'POINT({longitide} {latitude})', srid=4326) Shop(name=name,location = location).save() except KeyError: pass What have i tried I tried many answer like put encoding='cp437, it didn't worked for me. I also tried encoding="utf8", it didn't work too. When i add , encoding = 'cp850' with filename then it shows json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) I don't what am i doing wrong. Any help would be appreciated. Thank You in Advance. -
Is there a way to determine the order in which a FilterSet (from django-filter) perform queries?
Im using django-filter for a project. I've had to declare methods for filters in order to merge the queries being made. However besides doing those merges I also need to apply other filters. My problem is that there seems to be no way to determine the order in which the filters perform the queries. Here's my code class Tramite(models.Model): .... class FechasEtapas(models.Model): tramite = models.ForeignKey(Tramite, on_delete=models.CASCADE, related_name='etapas') etapa = models.IntegerField(choices=ETAPA_CHOICES, default=1) The views: class TramiteFilter(filters.FilterSet): origen__contains = BaseCSVFilter(method='filter_origen') origen__not_contains = BaseCSVFilter(method='filter_not_origen') lead__fecha_creacion = DateFromToRangeFilter() fecha_etapa_1__after = CharFilter(method='filter_etapa_fecha_greater') fecha_etapa_2__after = CharFilter(method='filter_etapa_fecha_greater') fecha_etapa_3__after = CharFilter(method='filter_etapa_fecha_greater') .... def __init__(self, *args, **kwargs): self.len_tramite = Tramite.objects.all().count() super().__init__(*args, **kwargs) class Meta: model = Tramite fields = { 'lead__score': ['lte', 'gte'], .... } def filter_origen(self, qs, name, value): return qs.filter(reduce(operator.or_, (Q(origen__contains=x) for x in value))) def filter_not_origen(self, qs, name, value): return qs.exclude(reduce(operator.or_, (Q(origen__contains=x) for x in value))) def filter_etapa_fecha_greater(self, qs, name, value): if len(qs) != self.len_tramite: return (qs | Tramite.objects.filter(etapas__etapa=name[12], etapas__fecha_etapa__gte=value).distinct()).distinct() return qs.filter(etapas__etapa=name[12], etapas__fecha_etapa__gte=value) I need that the filters fecha_etapa_x__after are run first so the other queries are made over the already merged queries, however right know my code is doing the opposite. Is there a way to achieve this? Thanks in advance. -
Return value from another model Django
I try to get data from a ChoiceField and bind to textbox. I have model BookingUnit one to many with PaymentTerm and PaymentTerm one to many with UnitPrice. I want when bookingUnit, select the paymentTerm and it will return with unitPriceAmount from model UnitPrice. How to solve this? Best Regards, Capah Maga Here Model,Form, view and template that i use. Model.py class UnitBooking(models.Model): projectID = models.ForeignKey(Project,on_delete=models.CASCADE) bookingID = models.AutoField(primary_key=True) bookingNo = models.CharField(max_length=20) unitID = models.ForeignKey(Unit,on_delete=models.CASCADE) nupNo= models.CharField(max_length=20) paymentTermID = models.ForeignKey(PaymentTerm,on_delete=models.CASCADE) unitBasePriceAmount = models.DecimalField(max_digits=20,decimal_places=2) unitPriceAmount = models.DecimalField(max_digits=20,decimal_places=2) remarks = models.CharField(max_length=16) isActive = models.BooleanField(default=True) insertTime = models.DateTimeField(default=datetime.now,blank=True) insertUser = models.CharField(max_length=50) lastUpdated = models.DateTimeField(default=datetime.now,blank=True) lastUpdater = models.CharField(max_length=50) def __str__(self): return self.bookingNo class PaymentTerm(models.Model): projectID = models.ForeignKey(Project,on_delete=models.CASCADE) paymentTermID = models.AutoField(primary_key=True) paymentTermNo = models.CharField(max_length=20) paymentTermName = models.CharField(max_length=150) isActive = models.BooleanField(default=True) insertTime = models.DateTimeField(default=datetime.now,blank=True) insertUser = models.CharField(max_length=100) lastUpdated = models.DateTimeField(default=datetime.now,blank=True) lastUpdater = models.CharField(max_length=150) def __str__(self): return self.paymentTermID class UnitPrice(models.Model): projectID = models.ForeignKey(Project,on_delete=models.CASCADE) unitPriceID = models.AutoField(primary_key=True) unitID = models.ForeignKey(Unit,on_delete=models.CASCADE) paymentTermID = models.ForeignKey(PaymentTerm,on_delete=models.CASCADE) basepriceAmount = models.DecimalField(max_digits=20,decimal_places=2) taxAmount = models.DecimalField(max_digits=20,decimal_places=2) totalAmount = models.DecimalField(max_digits=20,decimal_places=2) isActive = models.BooleanField(default=True) insertTime = models.DateTimeField(default=datetime.now,blank=True) insertUser = models.CharField(max_length=150) lastUpdated = models.DateTimeField(default=datetime.now,blank=True) lastUpdater = models.CharField(max_length=150) def __str__(self): return self.unitPriceID ===================================================================== Form.py class UnitBookingForm(forms.ModelForm): projectID = forms.ModelMultipleChoiceField(queryset=Project.objects.all(),widget=forms.Select(attrs={'class' : 'form-control'}),label="Project ID") bookingID = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control'}),label="Booking ID") bookingNo … -
TypeError at /post 'User' object is not iterable
I am currently building a post page for my web application Tutor find. The post page is can be only accessed when a user logins. I need the post page to show all the posts done by the current user. Please help Here is my models.py code class Skill(models.Model): teacher_name = models.CharField(max_length=50) skill_type = models.CharField( max_length=30, choices=SKILL_CHOICES, ) name = models.CharField(max_length=65) duration = models.IntegerField() cost = models.IntegerField() location = models.CharField(max_length=65) def __str__(self): return str(self.skill_type + " " + self.name) My view for posting skills in the home page : @login_required def postskill(request): if request.method == 'POST': print(request.user.id) print(request.user.username) form = PostRecord(request.POST) if form.is_valid(): data = form.cleaned_data s = Skill( # author = request.user.id, teacher_name = request.user.username, skill_type = data.get('skill_type'), name = data.get('name'), duration = data.get('duration'), cost = data.get('cost'), location = data.get('location'), ) s.save() allskills = Skill.objects.all().order_by('name') return render(request, 'home.html', {'skills': allskills}) else: form = PostRecord() return render(request, 'postskill.html', {'form': form}) View for post page: def post(request): logged_in_user_posts = Skill.objects.filter(request.user) return render(request, 'post.html', {'posts': logged_in_user_posts}) urls: urlpatterns = [ path('', views.index, name='index'), path('home', views.index, name='home'), path('signup', views.signup, name='signup'), path('postskill', views.postskill, name='postskill'), path('profile', views.profile, name='profile'), path('post', views.post, name='post'), ] template for postskill {% extends "base_generic.html" %} {% block content %} <h2>Post Skill</h2><br> … -
Mongodb query to check if a particular field is not null ( aggregation)
I have queries like { "title": "sjncx", "desciption": "cknxk jckd", "price": "29.99", "stock": "3", ... } I need to filter data if the title is not empty.( title exists and not null). And also is empty like ~ title: "" ~ ( so title exists but empty) I tried for is not empty: {'title': {'$ne': 'null'}} for is empty: I tried {'title': {'$type': 10}} That doesn't work. What would be the reason? -
Attribute error : 'str' object has no attribute 'post'
I am new to Django and trying to integrate razorpay with my website but getting error AttributeError: 'str' object has no attribute 'post' views.py def order(request, id): product = Product.objects.get(prod_ID=id) if request.method == 'POST': customer_id = request.user product = Product.objects.get(prod_ID=id) product_id = product try: quantity = request.POST['quantity'] quantity = int(quantity) order_price = quantity * product.prod_Price print(order_price) except MultiValueDictKeyError: pass try: size = request.POST['size'] value.update(size=size) except MultiValueDictKeyError: pass try: Colour = request.POST['Color'] value.update(Colour=Colour) except MultiValueDictKeyError: pass attribute_value = json.dumps(value) order_store = Order(user_id=customer_id, prod_id=product_id, quantity=quantity, attribute_value=attribute_value, order_price=order_price) if order_store: order_store.save() o_id = Order.objects.get(order_id=order_store.order_id) payment_store = Payment(order_id=o_id) payment_store.save() client = razorpay.Client('rzp_test_Cut6mUJgrjfQU', 'LSNlrKrH0NoUq8Y9rEUbg27') print(client) data = { 'amount': order_price * 100, 'currency': "INR", 'receipt': 'Order for ' + str(o_id.order_id), 'notes': { 'name': o_id.user_id.first_name + o_id.user_id.last_name, 'Payment_for': o_id.prod_id.prod_Name } } print(data) order_detail = client.order.create(data=data) print(order_detail) return render(request, 'user/payment.html', {'order_store': order_store}) context = {'products': products } return render(request, 'user/order.html', context) Here I am trying to integrate payment with my website but after creating order and payment status I am trying to do payment but I don't know what I am doing wrong. -
Websocket connection failed. Chatsocket closed
Using django channels im trying to connect to a websocket but it can't find it. I tried to see if its because of routing.py or consumer.py and i can't find the answer. I get the warning that no route was found for path 'tribechat/1/'. git error message: Traceback (most recent call last): File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\security\websocket.py", line 37, in __call__ return await self.application(scope, send, receive) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\sessions.py", line 254, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\auth.py", line 181, in __call__ return await super().__call__(scope, receive, send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\routing.py", line 168, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'tribe_chat/1/'. Console error message: WebSocket connection to 'ws://127.0.0.1:8000/tribe_chat/1/' failed: routing.py: from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.urls import path, re_path from tribe_chat.consumers import TribeChatConsumer application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ re_path(r'ws/tribe_chat/(?P<room_id>\w+)/$', TribeChatConsumer.as_asgi()), ]) ) ), }) consumers.py: from channels.generic.websocket import … -
django REST framework remove nested json
I would like to get the data from multiple model, now I work as these: class IGStatSerializer(serializers.ModelSerializer): class Meta: model = IGStat fields = [ "account", "rank", "followers", "created", ] class IGSerializer(serializers.ModelSerializer): stats = serializers.SerializerMethodField() class Meta: model = IGAccount fields = [ "id", "username", "avatar", "brand", "stats",] def get_stats(self, instance): today = datetime.today() - timedelta(days=1) stat = instance.stats.all().filter(created__year=today.year, created__month=today.month, created__day=today.day) return IGStatSerializer(stat, allow_null=True, many=True).data And the json result will be like this: { "id": 3613, "username": "beautyfromnaturehk", "avatar": "https://scontent-iad3-1.cdninstagram.com/v/t51.2885-19/s320x320/42763479_187833352109784_1648992215864705024_n.jpg?tp=1&_nc_ht=scontent-iad3-1.cdninstagram.com&_nc_ohc=Q4hJvaXL-vYAX--Ol1x&oh=e05aef733557c9951642c3c8b518d2f9&oe=607A54CC", "brand": 4172, "stats": [ { "account": 3613, "rank": 22822, "followers": 21485, "created": "2021-03-16T00:00:00Z" } ] }, And in actual case, there will combine more than one models together and having many nested json. So I would like to remove the nested and rename the field name, like the above case should be like this: { "id": 3613, "username": "beautyfromnaturehk", "avatar": "https://scontent-iad3-1.cdninstagram.com/v/t51.2885-19/s320x320/42763479_187833352109784_1648992215864705024_n.jpg?tp=1&_nc_ht=scontent-iad3-1.cdninstagram.com&_nc_ohc=Q4hJvaXL-vYAX--Ol1x&oh=e05aef733557c9951642c3c8b518d2f9&oe=607A54CC", "brand": 4172, "stats_account": 3613, "stats_rank": 22822, "stats_followers": 21485, "stats_created": "2021-03-16T00:00:00Z" }, The stats nested was remove and rename the content of it. -
Why does django think these values are different?
In my template, I am creating a select control from the list in qualifications. I have added the comment line to try to figure out why I could not designate a given row as selected. {% for qual in qualifications %} <!-- form.qualid.value ({{ form.qualid.value }}) {% if form.qualid.value == qual.empqualid %}equals{% else %}does not equal{% endif %} qual.empqualid ({{ qual.empqualid }}) --> <option value="{{ qual.empqualid }}"{% if qual.empqualid == form.qualid.value %} selected{% endif %}>{{ qual.EmpQualName }}</option> {% endfor %} A sample of my results: <!-- form.qualid.value (166) does not equal qual.empqualid (558) --> <option value="558">Gardening</option> <!-- form.qualid.value (166) does not equal qual.empqualid (166) --> <option value="166">General Manual Labour</option> <!-- form.qualid.value (166) does not equal qual.empqualid (571) --> <option value="571">General Manual Labour (Chinese)</option> The middle row should be a match, as the qual.empqualid is the same as the form.qualid.value (at least it looks like it to me). The variable form.qualid is an IntegerField and qual is a dictionary that has a key 'empqualid' that also holds integers. I think that forms emit strings with value()? Is that a possible issue? If so how do I check or change types? As you can see, django thinks that 166 and 166 are … -
relation "mains_shop" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "mains_shop"
I am Building a Webapp and I am stuck on an Error. What i am trying to do I am making a GeoDjango app using Gdal , OSGeo , Postgresql , Postgis. When i try to open the Shop panel in Django Admin then it is keep showing me relation "mains_shop" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "mains_shop" And when i delete it and migrate again then it shows ValueError: String input unrecognized as WKT EWKT, and HEXEWKB. But deleting migrations is solving ValueError . models.py class Shop(models.Model): name = models.CharField(max_length=100) location = models.PointField() address = models.CharField(max_length=100) city = models.CharField(max_length=50) admin.py @admin.register(Shop) class ShopAdmin(OSMGeoAdmin): list_display = ('name', 'location') settings.py INSTALLED_APPS = [ 'django.contrib.gis', ] DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': '-------', 'USER': '-------', 'PASSWORD': '-------', 'HOST': 'localhost', 'PORT': '', } } What have i tried First time when error appears then i think that GDal would not installed then I reinstalled it and it successfully installed. I have reinstalled PostGis . I have also seen many answers but nothing worked for me. I don't know what am i doing wrong. Any help would be appreciated. Thank You in Advance. -
django dropdown menu selection not registering as a post request
i'd like to select an order_id from a drop down menu, which will end up querying my MySQL data for the start point latitude/longitude and end point latitude/longitude for the selected taxi ride. i've looked at tutorials online but when i check the network tab of my inspect element, my dropdown selection doesn't register as a POST request (thus none of my data is actually being queried). what am i doing wrong? (also, because I'm using Django 1.6.11, i've inserted the code for JSONResponse instead of importing it from django.http) base.html <body> <div class="order"> <h1>View and calculate distance per order</h1> <select name="dropdown_menu" id="dropdown_menu"> <option class="dropdown" type="dropdown" selected>-- Select Order ID -- </option> {% for order in orders %} <!-- for x in {context}--> <option value="{{ order.order_id }}"> {{ order.order_id }} </option> {% endfor %} </select> <p>The selected order id is {{dropdown_menu}}</p> <!-- render distance calculation --> <!-- render distance on folium --> </div> {% block javascript %} <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <script> $("#dropdown_menu").change(function () { // calling select id const subjectId = $(this).val(); // get the selected subject ID from the HTML dropdown list $.ajax({ // initialize an AJAX request type: "POST", url: '', data: { 'order_id_selected': order_id_selected, // add the order … -
pytest mark parameterize a class attribute rather than a method argument
This is a simple example of a larger problem. I would like to test out class methods which are based on class attributes with multiple tests like parameterize(). This example uses the same attribute 'view.form.cleaned_data["regexstring"]' for testing to see if it was modified both before and after the method was run. Is there a way to parameterize the attribute tests? Or is it necessary to restructure my code to be less readable to get the testing I want (using method arguments)? # in tests/bookview.py import pytest from ..views import BookView class BookViewTest: def SetUp(self): view = BookView() @pytest.mark.parametrize("view.form.cleaned_data["regexstring"],view.form.cleaned_data["regexstring"]", [("/\w/i", "\w"), ("/\d/i", "/\d/i"), ("/\w+/i", "\w+")]) def test_reformat_javascript_regex_to_postgres_regex(self): view.reformat_javascript_regex_to_postgres_regex() # elsewhere inside views.py class BookView: ... def reformat_javascript_regex_to_postgres_regex(self): if self.form.cleaned_data["regexstring"].endswith('/i'): self.form.cleaned_data["regexstring"] = \ self.form.cleaned_data["regexstring"][:-2] self.form.cleaned_data["regexstring"] = \ self.form.cleaned_data["regexstring"] \ .replace('^','\m') \ .replace('/', '') \ .replace('$', '\M') -
Insert current model object in forms in django
Good day SO. I want to add a logic inside my forms. This logic will check if email address is already in use. Scenario: Applicant is extended to Account with a OneToOneField. Another is I added an email field in my applicant. cant remove it rn. Currently this is my clean_email of Applicant Form: def clean_email(self): # Get the email email = self.cleaned_data.get('email') # Check to see if any users already exist with this email as a username. try: account = Account.objects.get(email=email) except Account.DoesNotExist: # Unable to find a user, this is fine return email # A user was found with this as a username, raise an error. raise forms.ValidationError('This email address is already in use.') So far so good when registering my Applicant. However, if I update my applicant, (the same email address) it will check with account. Since in Account, email already exist, it raises validation error. I was thinking of adding an if account condition with the current object but I don't know how to insert my object Applicant to check. -
Redirect the user to a specific submission after submitting a form
I've written a basic forum model that allows users to create a post that others can respond to. After the user submits a form for a response to a forum post, the site displays a blank CommentForm, but instead, I want the user to be redirected to the unique forum post they responded to. Here's what I have so far: # views.py from django.shortcuts import render, get_object_or_404 from .models import Forum from .forms import CommentForm, ForumForm from django.contrib.auth.decorators import login_required # this is the view for the response form @login_required def newcomment(request): form = CommentForm if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): post = form.save(commit = True) post.save() form = CommentForm else: form = CommentForm return render(request, 'myapp/newcomment.html', {'form' : form}) # this is the view for a specific forum def forumdetail(request, id): forum = get_object_or_404(Forum, pk = id) responses=[] responses.append(forum.comment_set.all()) context={'forum' : forum, 'responses' : responses} return render(request, 'myapp/forumdetail.html', context) This is the webpage for the response form <!-- myapp/newcomment.html --> {% extends 'base.html' %} {% block content %} <h2 style="font-family: Impact; letter-spacing: 3px;">New Comment</h2> <table class = 'table'> <form method = "POST" class = "post-form"> {% csrf_token %} {{form.as_table}} </table> <button type = 'submit' class = … -
This field must be unique error in postman in OnetoOneField in Django Rest Framework
I am trying to update Customer Profile also updating main Customuser first_name and last_name field at the same time using nested serialization. But I am getting customer field must be unique error. I have posted the pics here. My models: class CustomUser(AbstractUser): # username = None first_name = models.CharField(max_length=255, verbose_name="First name") last_name = models.CharField(max_length=255, verbose_name="Last name") email = models.EmailField(unique=True) is_seller = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] objects = CustomUserManager() def __str__(self): return self.email class Customer(models.Model): customer = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) full_name = models.CharField(max_length=100, blank=True) phone_num = models.CharField(max_length=50, blank=True) #dob = models.CharField(max_length=255,blank=True,null=True) region = models.CharField(max_length=255, blank=True,null=True) city = models.CharField(max_length=255, blank=True, null=True) area = models.CharField(max_length=255,blank=True,null=True) address = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return self.customer.email My serializers: class CustomerProfileSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__' # depth = 1 class CustomerUpdateSerializer(serializers.ModelSerializer): customer = CustomerProfileSerializer() class Meta: model = User fields = ('id', "first_name", "last_name",'customer') def update(self,request, instance, validated_data): user = self.request.user instance.user.first_name=user.get('first_name') instance.user.last_name = user.get('last_name') instance.user.save() customer_data = validated_data.pop('customer',None) if customer_data is not None: instance.customer.region = customer_data['region'] instance.customer.city = customer_data['city'] instance.customer.area = customer_data['area'] instance.customer.address = customer_data['address'] instance.customer.save() return super().update(instance,validated_data) My views: class CustomerUpdateView(UpdateAPIView): permission_classes = [IsAuthenticated] queryset = Customer.objects.all() serializer_class = CustomerUpdateSerializer The url … -
queryset.count() is different with len(queryset)
models: class option(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) class Follow(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='is_following') follow = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='is_followed') functions: follows = Follow.objects.filter(user=request.user).exclude(follow__option__isnull=True).distinct().order_by("-option__pk") follows_2 = Follow.objects.filter(user=request.user).exclude(follow__option__isnull=True).order_by("-option__pk") print(follows.count()) >>>2 print(str(len(follows))) >>> 14 print(follows_2.count()) >>>2 Why follows.count() and follows.count() is different? It seems that distinct() works nothing.. How to make print(str(len(follows))) also print 2? -
Django: Get latest of grouped related objects
Django's approach to GROUP BY is rather indirect and difficult to understand at times. Consider this: class Player(model.Model): name = models.CharField() class Game(model.Model): name = models.CharField() class Match(model.Model): game = models.ForeignKey(Game, related_name='matches') date_time = models.DateTimeField() class Score(model.Model): match = models.ForeignKey(Match, related_name='scores') player = models.ForeignKey(Player, related_name='scores') Now we want all the latest Score objects for each player in a given game. How can we get this? I have one method that appears to work but I am uneasy with the lack of documentation around the method and confidence that it is generally "right" and/or canonical in this application. latest_scores = Score.objects.filter( game_pk=game_pk, match__pk=Subquery( Score.objects .filter(Q(player=OuterRef('player'))) .values('match__pk') .order_by('-match__date_time')[:1] ), output_field=models.PositiveBigIntegerField() ) ) The problem I have with this is not that it works (which it seems to) it's the lack of confidence I have in it as a general solution for lacking clear documentation on how a WHERE clause matching a subquery that references the outer query works and what the efficiency implications are. Most documentation I can find on subqueries avoids this complexity and says the subqueries are evaluated first then the outer query. Which makes sense and in an exemplary way with all the examples I can find where the … -
Django multiprocess does not work in production using apache2
I have deployed a Django project to production that fails to handle requests properly due to python multiprocess in my backend script. The problem is in my contact form in the webpage, where user should input name, email and a message they will like to send. Once they click on send the message, a recaptcha is performed and if that returns true, the message will be sent via email using Python's multiprocess. So the process looks like user input message form -> message form post -> reCaptha check -> if passed -> multiprocess to send the message via an email Everything worked fine when tested in development mode, but in deployment with apache2 I receive the following error Environment: Request Method: POST Request URL: https://www.dimsum.dk/hdnytorv Django Version: 3.1.3 Python Version: 3.8.5 Installed Applications: ['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'] Traceback (most recent call last): File "/home/jianwu/HD_website/website/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/jianwu/HD_website/website/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/jianwu/HD_website/website/env/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/jianwu/HD_website/website/env/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/home/jianwu/HD_website/website/index/views.py", line 146, in post emailObject … -
Django DRF Unable to send PUT request with Image Field
I have a form in React through which I am sending some data which includes an ImageField. I am able to perform a POST request and the data is being sent to Django backend successfully. However, when I try to modify the data I get employee_image: ` ["The submitted data was not a file. Check the encoding type on the form."] This is the data coming up on GET request: [ { "id": 2, "product_name": "XYZ", "product_description": "XYZ", "product_price": "12.00", "product_unit_weight": "120.00", "product_unit_weight_units": "GM", "product_type": "CPG", "product_image": "http://192.168.29.135:8000/media/product_images/xyz.png" }, This is my models.py file: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer def post(self, request, *args, **kwargs): product_name = request.data['product_name'] product_description = request.data['product_description'] product_price = request.data['product_price'] product_unit_weight = request.data['product_unit_weight'] product_unit_weight_units = request.data['product_unit_weight_units'] product_type = request.data['product_type'] product_image = request.data['product_image'] Product.objects.create(product_name=product_name, product_description=product_description, product_price=product_price, product_unit_weight=product_unit_weight, product_unit_weight_units=product_unit_weight_units, product_type=product_type, product_image=product_image) return Response({'message':'Product created successfully'}, status=200) def update(self, request, *args, **kwargs): print('Put method running') pk = self.kwargs.get('pk') product = get_object_or_404(Product.objects.all(), pk=pk) print(product) if (product.product_image.startswith('http')): img_name = dataDict["product_image"].split("/")[-1] product_img_temp = ContentFile(request.get(dataDict["product_image"]).content, name=img_name) dataDict['product_img'] = product_img_temp serializer = ProductSerializer(product, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I tried following this response and edited my models.py with the update() as shown above. But the error that I … -
Django how to validate if a user already exists
this is my model class UserAttributes(models.Model): airport = models.ForeignKey('airport.Airport', related_name='user_attributes_airport', on_delete=models.SET_NULL, null=True, blank=True) location = PointField(blank=True, null=True) user = models.ForeignKey( 'users.AerosimpleUser', related_name='user_attributes', on_delete=models.CASCADE, null=True, blank=True) views.py class LocationViewSet(viewsets.ModelViewSet): serializer_class=LocationRetrieveSerializer http_method_names = ['get', 'post', 'patch', 'put'] def get_permissions(self): switcher = { 'create': [IsAuthenticated], 'list': [IsAuthenticated], 'retrieve': [IsAuthenticated], 'update': [IsAuthenticated], 'partial_update': [IsAuthenticated], } self.permission_classes = switcher.get(self.action, [IsAdminUser]) return super(self.__class__, self).get_permissions() def get_queryset(self): return UserAttributes.objects.filter( airport__id=self.request.user.aerosimple_user.airport_id).order_by('pk') serializers.py class LocationRetrieveSerializer(serializers.ModelSerializer): class Meta: model = UserAttributes fields = '__all__' i want to know if the user or the airport already exists? -
Create and application Using Django frame work
The problem statement is this: create an api endpoint (you may choose what to name it) that takes a simple GET request with start_time and end_time query parameters as ISO formatted times (timezone handling not required), and return a json object with the duration in seconds between those two parameters. The endpoint should not accept a start time which is later than the end_time, or any other invalid input. You may choose how the endpoint should respond to invalid input. -
Saleor + Vue.js
By the default solear uses React, but I want to make my E-commerce site with Vue (DRF + Vue). What should I do? By the way I wanted to use the SSR for the SEO improving. Should I do it with Saleor and what the difference between saleor installation with vue and vue ssr -
i am geting internal server error in django rating
i an new in django i am trying to make star rating app by using django and javaScript but when i am clicking on star in console i am getting internal server error. actually I am also getting error message which i already have provided in javascript else condition. i have mainly problem in views.py because its not saving data in server. i also trying to add studentProfile model objects in view bu gating same error please help me? views.py def sendMessageView(request): object = sendMessage.objects.filter(score=0).order_by('?').first() return render(request, 'messages.html', {"object":object}) def rate_student(request): if request.method == 'POST': el_id = request.POST.get('el_id') val = request.POST.get('val') obj = sendMessage.objects.get(id=el_id) obj.score = val obj.save() return JsonResponse({'success': 'true', 'score': val}, safe=False) return JsonResponse({'success': 'false'}) models.py class studentProfile(models.Model): name = models.CharField(max_length=100, null=True, blank=True) email = models.EmailField(unique=True) rollNumber = models.IntegerField(unique=True) class Meta: ordering = ('name',) verbose_name_plural = 'Student Profile' def __str__(self): return self.name class sendMessage(models.Model): name = models.ForeignKey(studentProfile, on_delete=models.CASCADE) message = models.TextField(null=True, blank=True) score = models.IntegerField(default=0, validators=[ MaxValueValidator(5), MinValueValidator(0), ] ) def __str__(self): return str(self.pk) message.html {% extends 'base.html' %} {% block content %} <h1>message and ratting page</h1> <div> <form class="rate-form" method='POST' action="" id="{{object}}"> {% csrf_token %} <button type="submit" class="fa fa-star my_btn" id="first"></button> <button type="submit" class="fa fa-star my_btn" id="second"></button> … -
Django Admin Login page got messed up. (After git pull maybe? I am not sure)
I am not sure when did this happen, I seldom check my admin page while coding. I have been messing around with github and git bash to be familiarized with things so that I can work with a team environment. Is this because someone messed with this page on another branch and pushed changes to master branch? Anyone knows how to fix this? -
Django No matching serviceworker detected
Thanks for your time. I've been trying to set a PWA on a django project of mine: I've set the pwa files through urls and TemplateViews, and seems to be working. i'm able to run the sw.js code. get the manifest.json on tab application(Chrome dev) but ain't understanding why keeps getting the same error: no matching service worker detected. you may need to reload the page or check that the scope of the service worker for the current page encloses the scope and start url from the manifest i know that are a thousand of questions about that, but none with django that i could find. manifest.json: { "short_name": "Mega", "name": "MegaMagazine", "icons": [ { "src": "/static/m1.png", "type": "image/png", "sizes": "144x144" } ], "start_url": "/", "background_color": "#3367D6", "display": "standalone", "scope": "/", "theme_color": "#3367D6" } sw.js console.log('ok') install_sw.html <!doctype html> <head> <link rel="manifest" href="{% url 'manifestjson' %}"> </head> <title>installing service worker</title> <script type='text/javascript'> if ('serviceWorker' in navigator) { navigator.serviceWorker.register("{% url 'sw.js' %}").then(function (registration) { console.log('Service worker registrado com sucesso:', registration); }).catch(function (error) { console.log('Falha ao Registrar o Service Worker:', error); }); } else { console.log('Service workers não suportado!'); } </script> Files: enter image description here urls.py: urlpatterns = [ path('admin/', admin.site.urls), …