Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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), … -
Form.errors not rendering in TemplateView
Upon submitting a form, the desired outcome is to display validation error messages in the template if the form is not valid. When it comes to what I'm actually getting, no error messages are showing up in the template at all even though the form does in fact catch the errors. I'm trying get the desired outcome using just TemplateView. class TestUserRegisterPage(TestCase): '''Verify that a message is flashed when attempting to create a new account with a username already taken.''' @classmethod def setUpTestData(cls): user = User.objects.create_user("Mock") cls.payload = { "username": "Mock", "password1": "secret", "password2": "secret" } def test_new_user_registeration_fail(self): response = self.client.post( reverse("users:register"), data=self.payload ) self.assertEqual(response.status_code, 200) print(response.content) self.assertTemplateUsed(response, "users/register.html") self.assertContains(response, "A user with that username already exists") AssertionError: False is not true : Couldn't find 'A user with that username already exists' in response -> form = self.get_context_data()['register_form'](payload) (Pdb) n > users\views.py(30)post() -> if form.is_valid(): (Pdb) form.errors {'username': ['A user with that username already exists.'], 'password2': ['This password is too short. It must contain at least 8 characters.', 'This password is too common.']} (Pdb) class UserRegisterPage(TemplateView): template_name = "users/register.html" def get_context_data(self): context = super().get_context_data() context['register_form'] = NewUserForm return context def get(self, request): context = self.get_context_data() context['register_form'] = context['register_form']() return self.render_to_response(context) … -
how to get nested objects in django
models.py class BuyNotes(models.Model): student = models.ForeignKey(to=Student, on_delete=models.SET_NULL, null=True) note = models.ForeignKey(to=Notes, on_delete=models.SET_NULL, null=True) buy_at = models.DateField(auto_now_add=True) amount = models.IntegerField(default=0, null=True) class Meta: unique_together = [['note', 'student']] views.py def allNotesStudent(request): user = User.objects.get(username=request.session['user']) student = Student.objects.get(user=user) buy_notes = BuyNotes.objects.filter(student=student).get(note) I know last line is wrong. how to get all objects of note that current login student bought -
'DatabaseOperations' object has no attribute 'geo_db_type'. When migrate
I am building a WebApp . AND I am stuck on an Error. What i am trying to do I am making a Location Based BlogApp and I am using PointField in models. The Problem 'DatabaseOperations' object has no attribute 'geo_db_type' This error is keep showing when i migrate. When i go into admin then this error is keep showing. settings.py This is the DataBase i am using. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '---------', 'HOST': 'localhost', 'PORT': '', } } What have i tried I also tried chaning 'django.db.backends.postgresql_psycopg2' to 'django.contrib.gis.db.backends.postgis'. BUT it is showing django.db.utils.OperationalError: could not open extension control file "C:/Files/PostgreSQL/13/share/extension/postgis.control": No such file or directory I also tried many answers but nothing worked for me. I have installed pip install psycopg2. -
Django Filtering Model from User Input on Query Result
I have a purchase form, where the user can lookup a customer by name in the database and have a result returned in an HTML table. The user than clicks on an element in the table to autocomplete (Javascript) immutable name fields in a form to reduce input errors. I want to also display any fraud related to the selected customer, which would come from filtering the fraud table which was loaded in the context variable ['fraud']. I want to filter this new HTML table based on the customer ID selected, which changes as the user clicks on elements in the table derived from the first query. I'm having trouble understanding how I can filter this new table, considering that the customer ID input comes from the client-side. I've thought about having a hidden div with an input field that takes the customerID and performs another query. The problem with that solution is that I lose the URL params of my first query every time the second query is performed. Is there any convention for how to properly set this up within Django? Thank you views.py @method_decorator(login_required, name='dispatch') class CustomerResultsView(ListView): model = CustomerName template_name = 'parent/child.html' context_object_name = 'filtered_customers' @method_decorator(login_required) … -
exclude many-to-many with specific value
I have a model: class Rent(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) bikes = models.ManyToManyField(Bike) when I create a new rent in the admin site, I would like to exclude the bikes that have the value of 1 for their status integer field from showing in the list to choose from. Is this possible? Thanks -
How to log messages from django websocket functions to a file?
I have an application that uses linux + ngnix + gunicorn + websockets + django. The app opens a websocket connection on a specific url with a specific configuration. However, if configuration changes, it does not connects and shows the error: WebSocket connection to 'wss://my.url/ws/tool/5283cb7b-215d' failed: Error during WebSocket handshake: Unexpected response code: 500 I am trying to log code to check what are the differences between the data sent from one to another so I can reproduce the working configuration. I already found some data and am sending same data (access_data, and so on), however I cannot see what data sockets are receiving. I tried to use django log, no success. asgi.log also doesn't shows the info too. My log calls are on consumers.py file under class ChatConsumer(AsyncWebsocketConsumer): class and functions (connect, disconnect and receive). I am trying to check which data are being received by these functions. Log files doesn't contains the messages from this functions, neither from the url that is connecting correctly to the websocket. When I access the url, I see it connects correctly but I don't see any messages in my logs. asgi.log also shows only WSCONNECTING and WSDISCONNEC messages. How to log messages …