Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i want email has to be unique
while creating a new user i want that email has to be uniques for every user by which no user can same email twice views.py def register(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') email = form.cleaned_data.get('email') return redirect('/login/') else: form = SignUpForm() return render(request, 'register.html', {'form': form}) forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=True, help_text='Required.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, required=True, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',) but this is not working user got created with same email this is my approach any suggestion -
store selected image(image) or upload new image to Django model
I am using Django 3.1.2 On order page I am providing option to user that either he can upload a new image or can select image available. According to his selection to Upload image or select image value is to be stored in Django model field. If the user uploads the Image it is to be stored in model otherwise, If user selects an existing image its path or image to be saved in model. Can you please give an example? -
Get a hard query from django orm. Django rest framework
I have two models, Project and ShareProject. I need to list project where ShareProject.user = request.user. I am confused how can I get this queryset. class Project(models.Model): name = models.CharField(max_length=16, verbose_name='название', blank=False) user = models.ForeignKey(User, on_delete=models.CASCADE) prototype = models.ForeignKey('Prototype', on_delete=models.CASCADE) colors = jsonfield.JSONField() class SharedProject(models.Model): from_user = models.ForeignKey(User, to_field='email', on_delete=models.CASCADE, related_name='from_user') to_user = models.ForeignKey(User, to_field='email', on_delete=models.CASCADE, related_name='to_user') project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='share_project') permission = jsonfield.JSONField() all_users = models.BooleanField() -
How to autofill form based on the selected 'id' in django
I have a form like this: how to fill the disabled form field based on the selected 'No. Pelayanan'. This 'No.Pelayanan' is a select field, so when i choose (fill the field) it's autofill the form. i'm looking for any reference to how to do this. thank you! -
FieldError: Cannot resolve keyword 'username_iexact' into field
When I try to reach GroupList. I m getting FieldError: Cannot resolve keyword 'username_iexact' into field. Which is occuring in try block of get_queryset() in views.py.I tried a lot but Don't know how to fix this. This is What I'm getting: File "C:\Users\welcome\Desktop\python\python&Django\socialmedia project\simplesocial\posts\views.py", line 29, in get_queryset self.post_user=User.objects.prefetch_related('posts').get(username_iexact=self.kwargs.get('username')) File "C:\anaconda\envs\virblogEnv\lib\site-packages\django\db\models\query.py", line 418, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "C:\anaconda\envs\virblogEnv\lib\site-packages\django\db\models\query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\anaconda\envs\virblogEnv\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "C:\anaconda\envs\virblogEnv\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\anaconda\envs\virblogEnv\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\anaconda\envs\virblogEnv\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q child_clause, needed_inner = self.build_filter( File "C:\anaconda\envs\virblogEnv\lib\site-packages\django\db\models\sql\query.py", line 1258, in build_filter lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "C:\anaconda\envs\virblogEnv\lib\site-packages\django\db\models\sql\query.py", line 1084, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) File "C:\anaconda\envs\virblogEnv\lib\site-packages\django\db\models\sql\query.py", line 1481, in names_to_path raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'username_iexact' into field. Choices are: date_joined, email, first_name, group, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, password, posts, user, user_groups, user_permissions, username here is my views.py:- from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy # POSTS VIEWS.PY from django.http import Http404 from … -
Django HttpResponse result outputting in console but None on site
I got three numbers, that I'm randomly outputting. Django returns me a random number just fine in console but when checking the app through browser, it's returning 'None'. The GET is returning a 200 response, with a random value as expected but None on the site. Any ideas? urls.py from django.urls import path from NumberApp import views urlpatterns = [ path('number/', views.number), ] views.py from django.http import HttpResponse import random def number(request): number = ['1', '2', '3',] random_number = print(random.choice(number)) return HttpResponse(random_number) -
How to filter objects in a class based view django
I have a class for a blog post detail like this: class MaghaleDetail(DetailView): model = MaghaalaatPost template_name = 'Blog/Blog-elmi-detail.html' context_object_name = 'maghaale' slug_url_kwarg = 'the_slug' slug_field = 'slug' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["related_items"] = self.object.tags.similar_objects()[:3] context["images"] = MaghaalaatImages.objects.all() return context the images context shows every single image because I set it to all(). how do I filter it to show only the images to this specific post? -
Django - Pagination
I'm working on To-Do App. I have two kinds of data, Upcoming To-do Item and Completed To-do Items. So, I'm filtering data in views.py as upcoming items and completed items. I want to display them on the same page using pagination. I'm getting result too but if upcoming item completed in page-1 I was unable to visit page-2 because upcoming item for page-2 was empty but I have items on completed items. I couldn't see that. main.html {% extends 'todo/index.html' %} {% load crispy_forms_tags %} {% block content %} <nav aria-label="..."> <ul class="pagination justify-content-center"> {% if page_obj.has_previous and page_obj2.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.previous_page_number }}" tabindex="-1">&laquo;</a> </li> {% endif %} <li class="page-item active"> <a class="page-link" href="?page={{ page_obj.page_number }}">{{ page_obj.number }}</a> </li> {% if page_obj.has_next and page_obj2.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.next_page_number }}">&raquo;</a> </li> {% endif %} </ul> </nav> <div class="center-column"> <h2 class="heading" style="text-align: center;">Hello {{ request.user.username }}, Here's your ToDo List</h2> <form action="" method="POST" id='form-create'> {% csrf_token %} <div style="text-align: center;"> {{ todo_form.title }} <button type="submit" class="form-control btn btn-primary mb-3 mr-sm-2">Add Items</button> </div> </form> <h4 class="heading" style="text-align: center;">Upcoming ToDo Items</h4><br> <div class="row"> <div class="col" id="upcomItem"> <ul class="list-group" id="upcomingItems"> {% for i in page_obj %} <li class="list-group-item … -
How to separate user authentication in Django3 by the types of user?
is it possible to make an authentication option for users depending on their types in Django3? For instance, I have Customer and Seller which has one User model. When I am trying to sign as a Customer customer1@test.com with a sign-in/?next=/customer/ link it's signed as a user, if I will try to sign with the same Customer customer1@test.com into Seller sign-in/?next=/seller/ it will allow the same customer1@test.com user. How to split them and restrict users depending on sign URL link or maybe split the User model depending on the type of User(Seller, Customer). Thank you. Here is my model: import uuid from django.db import models from django.contrib.auth.models import User, AbstractUser from django.utils import timezone from django.utils.translation import gettext_lazy as _ class Types(models.TextChoices): CUSTOMER = "CUSTOMER", "Customer" SELLER = "SELLER", "Seller" class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_type = models.CharField(_('Type'), max_length=50, choices=Types.choices, default=Types.CUSTOMER) avatar = models.ImageField(upload_to='customer/avatars/', blank=True, null=True) phone_number = models.CharField(max_length=50, blank=True) stripe_customer_id = models.CharField(max_length=50, blank=True) stripe_payment_method_id = models.CharField(max_length=50, blank=True) stripe_card_last4 = models.CharField(max_length=50, blank=True) def __str__(self): return self.user.get_full_name() class Seller(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_type = models.CharField(_('Type'), max_length=50, choices=Types.choices, default=Types.SELLER) lat = models.FloatField(default=0) lng = models.FloatField(default=0) paypal_email = models.EmailField(max_length=255, blank=True) fcm_token = models.TextField(blank=True) def __str__(self): return self.user.get_full_name() -
crispy-forms add javascript sum of fields
I want to sum groups of select choice result dynamically in my template. all forms are select fields like this (models.py) evolQuote = ( (1, 'High'), (0, 'Undetermine'), (-1, 'Low')) cycleMarket = models.IntegerField(choices=evolQuote, null=False, blank=False, default=0) news = models.IntegerField(choices=evolQuote,null=False, blank=False) my template is: <form method="post">{% csrf_token %} <div class="form-group col-md-2 mb-0" name="market-1" onchange="sumamount();"> {{ form.cycleMarket|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0" name="market-2" onchange="sumamount();"> {{ form.news|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0" name="market-3" onchange="sumamount();"> {{ form.managementPostion|as_crispy_field }}</div> <div class="col col-md-2 mb-0" name="indicator-1"> {{ form.parabolics|as_crispy_field }} </div> <div class="col col-md-2 mb-0" name="indicator-2"> {{ form.trix|as_crispy_field }} </div> <div class="col col-md-2 mb-0" name="indicator-3"> {{ form.arron|as_crispy_field }} </div> my attempt javascript: function sumamount(){ sum=0; $("input[name^='market-']").each(function(){ sum+=Number($(this).val()); }); console.log(sum) $("#fundamentals").val(sum); } But console log sum equals zero all the time. -
How to validate inlineformset_factory while validating the parent form?
I'm working on a Django project and I'm unable to find a way to validate an inlineformset_factory while validating the parent form. Its master/detail form approach SaleMSTForm is a parent model form from the SaleMST model and SaleDTLForm is a detail form from SaleDTL model. When I submit the form the parent form works fine and displays errors that it supposes to display while validation but the formset doesn't display any error and it got reset after the submission error. Also, I want to save both forms even if an error occurs the parent form shouldn't be saved. here's my code: models.py class SaleMST(models.Model): customer = models.ForeignKey(Customer, on_delete=models.RESTRICT) date = models.DateField() desc = models.CharField(max_length=200, blank=True) disc = models.DecimalField(max_digits=20, decimal_places=2, blank=True) created_by = models.CharField(max_length=20, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) modified_by = models.CharField(max_length=20, null=True, blank=True) modified_at = models.DateTimeField(auto_now=True) def __str__(self): return self.desc class SaleDTL(models.Model): mst = models.ForeignKey(SaleMST, on_delete=models.RESTRICT) product = models.ForeignKey(Product, on_delete=models.RESTRICT) desc = models.CharField(max_length=200, blank=True) qty = models.IntegerField() def __str__(self): return self.desc forms.py class SaleMSTForm(forms.ModelForm): class Meta: model = SaleMST fields = ['customer', 'date', 'desc', 'disc'] widgets = { 'customer': forms.Select(attrs={ 'class': 'form-control' }), 'date': forms.DateInput(attrs={ 'class': 'form-control', 'type': 'date' }), 'desc': forms.TextInput(attrs={ 'class': 'form-control' }), 'disc': forms.TextInput(attrs={ 'class': 'form-control' }), … -
Cannot Authenticate Test Requests with Both User Token and API Key in Django Rest Framework
My project requires two authentication methods for some endpoints: A global API key using this app. A user authentication token using the default one provided by DRF All works fine when working with the API using Postman or an iOS app, but I couldn't make the authentication work in my tests. The user auth works fine, but the global key fails. This is how the HTTP headers look in Postman: X-Api-Key: KEY_VALUE Authorization: Token TOKEN_VALUE I tried to experiment with the code in the shell and authentication worked fine using the exact same code used in the test! Only in the tests it fails so I'm not really sure how to debug this further. This is a small sample of the project underneath hopefully it could help someone spot the issue. But if I missed posting something please let me know and I'll update it. app.views.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.permissions import IsAuthenticated from rest_framework_api_key.permissions import HasAPIKey class MyView(APIView): permission_classes = [HasAPIKey, IsAuthenticated] def get(self, request, format=None): return Response(status=status.HTTP_200_OK) app.tests.py from rest_framework.test import (APITestCase, APIRequestFactory, force_authenticate) from rest_framework import status from accounts.models import User from .views import MyView class MyTests(APITestCase): def … -
Deploying django3 project with mod_wsgi
I'm experimenting to publish my django project with Apache mod_wsgi. I created a simple django3 project named sampleapp in virtualenv. Then, I configured my /etc/apache2/sites-enabled/000-default.conf file as follows <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined WSGIDaemonProcess sampleapp python-home=/var/www/html/sampleapp/env python-path=/var/www/html/sampleapp:/var/www/html/sampleapp/env/lib/python3.7/site-packages WSGIProcessGroup sampleapp WSGIScriptAlias /sampleapp /var/www/html/sampleapp/sampleapp/wsgi.py process-group=sampleapp </VirtualHost> Although my virtualenv's python version is 3.7, mod_wsgi is used system's python version(3.5), so it doesn't see my virtualenv and doesn't use its python version. My apache error log as follows: [Sat Feb 20 15:36:02.390188 2021] [mpm_prefork:notice] [pid 20090] AH00169: caught SIGTERM, shutting down [Sat Feb 20 15:36:03.226065 2021] [mpm_prefork:notice] [pid 20204] AH00163: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/3.5.2 configured -- resuming normal operations [Sat Feb 20 15:36:03.226278 2021] [core:notice] [pid 20204] AH00094: Command line: '/usr/sbin/apache2' [Sat Feb 20 15:36:03.294321 2021] [wsgi:error] [pid 20207] mod_wsgi (pid=20207): Call to 'site.addsitedir()' failed for '(null)', stopping. [Sat Feb 20 15:36:03.295568 2021] [wsgi:error] [pid 20207] mod_wsgi (pid=20207): Call to 'site.addsitedir()' failed for '/var/www/html/sampleapp/env/lib/python3.7/site-packages'. [Sat Feb 20 15:36:07.084368 2021] [wsgi:error] [pid 20207] mod_wsgi (pid=20207): Call to 'site.addsitedir()' failed for '(null)', stopping. [Sat Feb 20 15:36:07.084455 2021] [wsgi:error] [pid 20207] mod_wsgi (pid=20207): Call to 'site.addsitedir()' failed for '/var/www/html/sampleapp/env/lib/python3.7/site-packages'. [Sat Feb 20 15:36:07.085660 2021] [wsgi:error] [pid 20207] [remote 127.0.0.1:47028] … -
How convert sql join query into django queryset
I am trying to write django sql query on two tables i.e. table1, table2 and display query data in table3. Could someone show how to convert the following SQL join query to the Django queryset. Sql query INSERT INTO table3(project_name,task_name,set_status,date,created_by) SELECT table1.projects_name, table2.task_name,'pending' AS set_status, table1.created_date, table2.created_by_id FROM table1 RIGHT JOIN table2 ON (table1.id = table2.projects_name_id AND table1.created_by_id = table2.created_by_id) Model class Table1(models.Model): projects_name = models.CharField(max_length=100) created_date = models.DateTimeField(auto_now_add=False, blank=True) created_by = models.ForeignKey(User, related_name="projectcreatby", on_delete=models.CASCADE) class Table2(models.Model): projects_name = models.ForeignKey(Projects, related_name="projects", on_delete=models.CASCADE) task_name = models.CharField(max_length=100) created_by = models.ForeignKey(User, related_name="taskcreateby", on_delete=models.CASCADE) class Table3(models.Model): project_name = models.CharField(max_length=100) task_name = models.CharField(max_length=100) set_status = models.CharField(max_length=20, blank=True) date = models.DateTimeField(auto_now_add=False, blank=True) created_by = models.CharField(max_length=100) -
Django Unit Testing : MultipleChoiceField dependent on objects created during setUp
I'm trying to test a form which has a MultipleChoiceField which is populated with content from the database. Currently the test is failing, because the choices passed are invalid. The reason being that the field doesn't seem to have any data on it. TEST RESULTS & DEBUG PRINT STATEMENTS <QuerySet []> System check identified no issues (0 silenced). <QuerySet [<Subject: Subject object (1)>, <Subject: Subject object (2)>]> <ul class="errorlist"><li>subjects<ul class="errorlist"><li> Select a valid choice. Subject object (1) is not one of the available choices.</li></ul></li></ul> CODE # TEST def test_lecturer(self): print(Subject.objects.all()) subjects = [self.subject, self.subject2] response = self.client.post(reverse('manager:register'), {'email' : self.lecturer_email, 'is_lecturer' : True, 'subjects' : subjects }) lecturer = UserProfile.objects.get(email=self.lecturer_email) self.assertEqual(lecturer.can_edit, subjects) # FORM class UserCsvForm(forms.Form): try: subjects = [(x,x.title) for x in Subject.objects.all()] except: subjects = [] print(Subject.objects.all()) ... OTHER FIELDS ... subjects = forms.MultipleChoiceField(choices=subjects, required=False) It seems like the form is being called before the test is setup, but shouldn't the form only be generated once the post request is sent? -
Saving data from views.py in django DB
in my Django App, I have created a model under my models.py. I am wondering if I can save data directly from my views.py. This is what I have tried: userinfo.info = UserInfo.objects.create(info=response.text) userinfo.save() where UserInfo is my model name, and info is the field name. Thanks -
Reverse for 'blogdetails' with no arguments not found. 1 pattern(s) tried: ['blog/details/(?P<slug>[-a-zA-Z0-9_]+)$']
It is the browser [This is my models.py[This is views.py file][Urls.py][2]3gur.com/1O0Kx.jpg -
I have a problem with <a> Tag when using block content in django
First of all I am new to django. I have a project with 4 pages and pages root is look like below: myProject/create/ myProject/create/project myProject/create/activity myProject/create/discipline I made a base.html file in templates/myapp/base.html and add a sidebar there. I added links of all pages in in base.html to access to other pages. then with the {% extend %} formula I extended sidebar from this page to see a it on other pages too and its working. So my structure of project is look like this: myProject ├── create │ ├── project │ ├── activity │ ├── discipline when I am in "create" page and I click on project page, I goes on that page and its working. but the problem is when I am in sub pages like "project" page and I click on other pages (ex: activity) it goes to: MyProject/Create/project/activity which is not true. what should I do to be able to go to myProject/create/activity and not to MyProject/Create/project/activity from sub pages ? -
how can get consumed Incomming message and Store it in variable Directly without methods (Read my Description)
I want to get Incoming Message Body and process it then store it in variable and then do what ever i want, maybe return to template or anything , I don't want to using call_back_method i want to use it Directly and store it in variable it is my consumer custom function: async def consumer(exchange_name=None, exchange_type=None, queue_name=None, call_back_method=None, loop=None): if not loop: loop = asyncio.get_event_loop() connection = await connect_robust( "amqp://user:example@**********:5672/", loop=loop ) channel = await connection.channel() if exchange_name and exchange_type: exchange = await channel.declare_exchange(exchange_name, exchange_type, durable=True) if queue_name is None: queue = await channel.declare_queue('default') queue = await channel.declare_queue(queue_name) await queue.bind(exchange) await queue.consume(callback=call_back_method) # return call_back_method else: queue = await channel.declare_queue(queue_name) await queue.consume(callback=call_back_method) here my consumer call back method : async def get_content(message: IncomingMessage): async with message.process(): value = message.body.decode('utf-8') return value.encode() Ultimately, this is what I want: message = await consumer(queue_name="Hello", exchange_name="publisher", call_back_method=get_content) print(message) # Message that i get from RabbitMq queue and is this really possible or if its not how can solve this problem -
Creating a copy of a Django JSONField value
I am trying to create a copy of a JSON model field using .copy() however any changes I make to the copy are still being reflected in the database which I don't want. I could iterate the model field and create a new dictionary but I figured theres a more pythonic way.. Models.py Class User(models.model): settings = models.JSONField(default=dict(color = "Yellow", shape = "Square")) views.py ... user = User.objects.get(id=1) settings = user.settings settings_copy = user.settings.copy() #settings model field is being changed here despite being a copy settings_copy['color'] = Blue ... -
how to send an email with django rest framework
i have asked this question quite a lot of times in the python discord and other places but i still can't find out how to send an email to verify an account or reset a password in django rest framework. i have watched these tutorials https://www.youtube.com/watch?v=2kKwPk5qPUs https://www.youtube.com/watch?v=BXg-b20Xusw&t=671s https://saasitive.com/tutorial/django-rest-framework-reset-password/ https://djoser.readthedocs.io/en/latest/getting_started.html i have also tried djoser but that hasnt worked and i have also tried the twilio sendgrid api with this tutorial https://www.mindbowser.com/integrating-sendgrid-with-django-rest-framework/ so does anyone have any answers on how to send an email with django rest framework? -
Django Rest Auth 'str' object has no attribute 'decode'
I am trying to authenticate via django rest-auth. When i authenticate,i get this error. Error: AttributeError at /rest-auth/login/ 'str' object has no attribute 'decode' /app/.heroku/python/lib/python3.9/site-packages/rest_framework_jwt/utils.py, line 92, in jwt_encode_handler Now the issue is that i have not customized any of the codes related to "rest_framework_jwt" etc.. I only provided necessary urls and files to make them work correctly. Requirements.txt asgiref bson coreapi-cli dataclasses dj-database-url django-address django-admin django-allauth django-better-admin-arrayfield django-cors-headers django-extensions django-filter django-flags django-friendship django-jsonfield django-rest-auth django-rest-framework django-snippet django-tags-input django-waffle django-graphql-jwt djangorestframework-bulk djangorestframework-jwt djongo drf-dynamic-fields drf-extra-fields drf-nested-serializer drf-writable-nested grpcio gunicorn joblib jsonfield markdown msedge-selenium-tools pillow psycopg2 psycopg2-binary scipy tabulate virtualenv webdriver-manager whitenoise runtime.txt python-3.9.2 urls.py urlpatterns = [ path('rest-framework/', include('rest_framework.urls')), url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), ] -
The login session is not alive after setup in django unitest
I have the following issue. I'm following some tutorials to get some understanding of Django and I want to do now a test of a view: view.py: class OwnerListView(LoginRequiredMixin, generic.ListView): model = Owner paginate_by = 10 model.py: class Owner(models.Model): username = models.TextField(max_length=100) first_name = models.TextField(null=True, max_length=100) last_name = models.TextField(null=True, max_length=100) email = models.EmailField(null=True) def __str__(self): """String for representing the Model object.""" return self.username def get_absolute_url(self): """Returns the url to access a particular instance of the model.""" return reverse('owner', args=[int(self.pk)]) class Meta: ordering = ['-username'] url.py (for the app): from django.urls import path from . import views urlpatterns = [ path('owners', views.OwnerListView.as_view(), name='owners'), ] And here comes my question. I want to test the view which requires the user to be logged in. But I'd like to do that at the beggining of the test and then do all the tests that I want to do, because I think is more time/code/processing efficient. So I create the following code: tests/test_views.py: from django.test import TestCase, Client from django.urls import reverse from django.contrib.auth.models import User from inventory_items.models import Owner class OwnerListViewTest(TestCase): @classmethod def setUpTestData(self): # Create 13 authors for pagination tests number_of_owners = 13 for owner_id in range(number_of_owners): Owner.objects.create( first_name=f'FirstName {owner_id}', last_name=f'LastName {owner_id}', … -
Uncaught TypeError: t is null when plotting Polygon in Leaflet
I am trying to plot a polygon on a Leaflet map. I'm using Django with a postgis database (as bundled with Geodjango). I posted here last week, seeking advice on getting the polygon data out of the database and plotted on a map. I had 1 answer to this question which I think gets me very close to a resolution. The key, it seems, is to use Django's json_script tag. Having incorporated the answer's code into my app I get the error: Uncaught TypeError: t is not null. In views.py I have serialised the PolygonField() in my Django model: def viewjob(request): req = request.GET job_name = newJob.objects.values_list('job_name', flat=True).get(pk=req['search']) job_desc = newJob.objects.values_list('job_desc', flat=True).get(pk=req['search']) json_loc = newJob.objects.filter(pk=req['search']) json_loc = serialize('geojson', json_loc, geometry_field='job_loc') context = { 'job_name': job_name, 'job_desc': job_desc, 'json_loc': json_loc } print(context) return render(request,'viewjob.html', context) My template now looks like: {% extends "base.html" %} {% block body %} {% load leaflet_tags %} {% leaflet_js %} {% leaflet_css %} <style> .leaflet-container { width: 600px; height: 400px; } #specialbigmap { height: 800px; } .django-leaflet-raw-textarea { width: 100%; } </style> <h1>{{ job_name }}</h1> <h3>{{ job_desc }}</h3> <br> <h5>Your Area</h5> {{json_loc}} <br> <br> {{ json_loc|json_script:"json-loc" }} <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript"> function map_init(map, options) { // … -
Encounter an error on ma django project, since i am a beginner help mee
I am working on my django project an E-shop. and i was trying to handle an post request and i got stuck with this error so , help plz. Error msg :- Cannot assign "1": "Order.product" must be a "Product" instance Here is my code from django.views import View from django.shortcuts import render, redirect from django.contrib.auth.hashers import check_password from store.models.customer import Customer from store.models.products import Product from store.models.orders import Order from .cart import Cart class Checkout(View) : def post(self, request): address = request.POST.get('address') phone = request.POST.get('phone') customer = request.session.get('customer') cart = request.session.get('cart') products = Product.get_product_by_id(list(cart.keys())) for product in products : order = Order(customer = customer, product = product.id, price = product.price, address = address, phone = phone, quantity = cart.get(product.id), ) order.place_order() return redirect("cart_page")