Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable
I had to reinstall my pycharm and now when I try to run my Django server I get the following error: (card_companion_venv) PS N:\My Drive\Projects\Card Companion\card_companion> python website/manage.py runserver 0.0.0.0:8000 --settings=website.settings.base Traceback (most recent call last): File "N:\My Drive\Projects\Card Companion\card_companion\website\manage.py", line 9, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "N:\My Drive\Projects\Card Companion\card_companion\website\manage.py", line 20, in <module> main() File "N:\My Drive\Projects\Card Companion\card_companion\website\manage.py", line 11, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? The interpreter has the correct packages installed: and the terminal is using the virtual environment: (card_companion_venv) PS N:\My Drive\Projects\Card Companion\card_companion> -
Django: Prefill the values of a Django form with the values of another one in another template(view)
I'm stuck on this problem of prefilling the values of a Django form of a specific template with the values of another form that is in another html page. What I have is an administration panel with a table with all the users (every row is a user) and I have a button called Edit to edit these ones. What I would like to do is to, when this button is clicked, redirect the user to another page where there is a form that needs to be prefilled with the values of the row of the table related to that specific user. I have tried session already but it didn't work. Here's what I tried. Template with the table <form method="POST" action="/administration/modify" id="update_form"> {% csrf_token %} <input type="hidden" value="{{i.email}}" name="update_email" /> <button type="submit" name="update_user" class="btn btn-primary"> Update</button></td> View of the page with the table where the values of the form need to come: update_email=request.POST["update_email"] request.session["modify_user"]=update_email return redirect("modify") View of the page with the form that needs to be filled: if request.method=="POST": form_update_user=UpdateUserForm(request.POST) #when the user fill the form .... else: update_email=request.session.get("modify_user") user_update=Utente.objects.get(email=update_email) print("******************************************") print(user_update.name) form_update_user=UpdateUserForm(initial={"name":user_update.name, "surname":user_update.surname,"email":user_update.email,"role_name":user_update.ruolo,"ente_name":user_update.ente,"password":"","confirm_password":""}) What i have is this: Page with the form that needs to be prefilled … -
How to iterate 3 nested lists on django template
I have 3 lists on my views and I want to iterate it with django template with nestedly. Eg: here I have 3 lists name card_postings,arrays and post_content card_postings = ['Indicatif', 'Subjonctif', 'Conditionnel', 'Participe', 'Impératif', 'Infinitif'] arrays = [['Présent', 'Imparfait', 'Futur', 'Passé simple', 'Passé composé', 'Plus-que-parfait', 'Passé antérieur', 'Futur antérieur'], ['Présent', 'Imparfait', 'Plus-que-parfait', 'Passé'], ['Présent', 'Passé première forme', 'Passé deuxième forme'], ['Présent', 'Passé composé', 'Passé'], ['Présent', 'Passé'], ['Présent', 'Passé']] post_content = [["j'ai", 'tu as', 'il/elle a', 'nous avons', 'vous avez', 'ils/elles ont'], ["j'avais", 'tu avais', 'il/elle avait', 'nous avions', 'vous aviez', 'ils/elles avaient'], ["j'aurai", 'tu auras', 'il/elle aura', 'nous aurons', 'vous aurez', 'ils/elles auront'], ["j'eus", 'tu eus', 'il/elle eut', 'nous eûmes', 'vous eûtes', 'ils/elles eurent'], ["j'ai eu", 'tu as eu', 'il/elle a eu', 'nous avons eu', 'vous avez eu', 'ils/elles ont eu'], ["j'avais eu", 'tu avais eu', 'il/elle avait eu', 'nous avions eu', 'vous aviez eu', 'ils/elles avaient eu'], ["j'eus eu", 'tu eus eu', 'il/elle eut eu', 'nous eûmes eu', 'vous eûtes eu', 'ils/elles eurent eu'], ["j'aurai eu", 'tu auras eu', 'il/elle aura eu', 'nous aurons eu', 'vous aurez eu', 'ils/elles auront eu'], ["que j'aie", 'que tu aies', "qu'il/elle ait", 'que nous ayons', 'que vous ayez', "qu'ils/elles aient"], ["que j'eusse", … -
AssertionError at /graphql/ A Schema is required to be provided to GraphQLView
I have a Django API with a GraphQL route. Here is my models.py: class MyBook(models.Model): id = models.BigAutoField(primary_key= True) book_name = models.CharField(max_length= 200) title = models.CharField(max_length= 200) In my Schema.py: import graphene from graphene_django.views import GraphQLSchema from graphene_django import DjangoObjectType from publishing_house_app.models import * class BookType(DjangoObjectType): class Meta: model= MyBook fields= "__all__" class RootQuery(graphene.ObjectType): books = graphene.List(BookType) def resolve_books(self, root, info, **kwargs): MyBook.objects.all() MyBookSchema = graphene.Schema(query= RootQuery) in urls.py: from .views import * from rest_framework.urlpatterns import path from graphene_django.views import GraphQLView from .GraphQL import Schema urlpatterns = [ path("graphql/", GraphQLView.as_view(graphiql= True, schema= Schema)), ] I am getting the following error: File "C:\Python39\lib\site-packages\graphene_django\views.py", line 127, in init assert isinstance. AssertionError at /graphql/ A Schema is required to be provided to GraphQLView. -
Where to put a code that interacts with DB and should run once on the project startup in django 2.2 or higher?
I'm trying to write some code that checks on something, if exists then cool and if not creates it. The problem is, where to put this code? Django doesn't recommend putting anything that deals with DB at an app's ready() function - this is what I'm currently doing but it gives me an error on debugging and give an error too on the beginning but works later on-. Also, what I have found seems outdated and a bit hacky like putting it at urls.py or wsgi.py. I feel there must be a better way to do it. Thank you all. -
I need some help guys
TypeError at /admin/catalog/book/ display_genre() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/admin/catalog/book/ Django Version: 3.2.8 Exception Type: TypeError Exception Value: display_genre() takes 1 positional argument but 2 were given Exception Location: C:\Users\User1\Envs\my_django_environment\lib\site-packages\django\contrib\admin\utils.py, line 274, in lookup_field Python Executable: C:\Users\User1\Envs\my_django_environment\Scripts\python.exe Python Version: 3.6.1 Python Path: ['C:\Users\User1\Desktop\django_projects\locallibrary', 'C:\Users\User1\Envs\my_django_environment\Scripts\python36.zip', 'c:\users\user1\appdata\local\programs\python\python36\DLLs', 'c:\users\user1\appdata\local\programs\python\python36\lib', 'c:\users\user1\appdata\local\programs\python\python36', 'C:\Users\User1\Envs\my_django_environment', 'C:\Users\User1\Envs\my_django_environment\lib\site-packages'] Server time: Thu, 14 Oct 2021 15:56:29 +0000 -
Error in Django 3.2.7 - TemplateSyntaxError at /blog/ 'menus_tags' is not a registered tag library
While messing a little with routable pages and latest posts config, i ran into this error and i have no idea of how to fix it. Error is shown here Django 3.2.7 Python 3.9.6 debug_toolbar 3.2.2 Taggit 1.5.1 Wagtail core 2.14.1 -
'int' object has no attribute 'save' while I am trying to update multiple row
I am trying to update multiple row depends on multiple data. But while I submit, only one row update and got this error 'int' object has no attribute 'save'. I think the problem is in my view. My view are given bellow: def saleForm(request): stb = [] if request.method == 'POST': for stb_array in request.POST.getlist('stb_sl'): stb.append(stb_array) i = 0 for stb_ho in stb: stb_update = StpDetails.objects.filter(stp_sl=stb_ho).update( sale_date=date, sales_invoice=invoice, status='Sold') stb_update.save() i += 1 messages.success(request, 'You have successfully save data.') return render(request,'sale/invoice_details.html',{}) My Model: class StpDetails(models.Model): id = models.AutoField(primary_key=True) entry_date = models.DateField(default=date.today) stp_sl = models.CharField(max_length=50, unique=True) stp_name = models.CharField(max_length=30) sale_date = models.DateField(auto_now=False, null=True) sales_invoice = models.CharField(max_length=20, blank=True) install_date = models.DateField(auto_now=False, null=True) installer = models.CharField(max_length=50, blank=True) house = models.CharField(max_length=100, blank=True) status = models.CharField(max_length=7, default='Unsold') def __str__(self): return self.stp_sl -
Limit the user to give the test only once per course
I want to limit the student to attempt specific test once per course. There can be multiple quizzes but each student should be giving test once only. The student field is one to one field with user views.py has :- @login_required(login_url='studentlogin') @user_passes_test(is_student) def start_exam_view(request,pk): course=QMODEL.Course.objects.get(id=pk) questions=QMODEL.Question.objects.all().filter(course=course) """ Update Status of exam taken """ status = models.Student.objects.get(user_id=request.user.id) status.taken_status = True status.save() if request.method=='POST': pass response= render(request,'student/start_exam.html',{'course':course,'questions':questions}) response.set_cookie('course_id',course.id) return response @login_required(login_url='studentlogin') @user_passes_test(is_student) def calculate_marks_view(request): if request.COOKIES.get('course_id') is not None: course_id = request.COOKIES.get('course_id') course=QMODEL.Course.objects.get(id=course_id) total_marks=0 questions=QMODEL.Question.objects.all().filter(course=course) for i in range(len(questions)): selected_ans = request.COOKIES.get(str(i+1)) actual_answer = questions[i].answer if selected_ans == actual_answer: total_marks = total_marks + questions[i].marks student = models.Student.objects.get(user_id=request.user.id) result = QMODEL.Result() result.marks=total_marks if result.marks >= course.cutoff_marks: student.result_status = True student.save() else: student.result_status = False student.save() result.exam=course result.student=student result.save() return HttpResponseRedirect('view-result') Quiz Model :- class Course(models.Model): course_name = models.CharField(max_length=50) question_number = models.PositiveIntegerField() total_marks = models.PositiveIntegerField() cutoff_marks = models.PositiveIntegerField(default=0) def __str__(self): return self.course_name class Question(models.Model): course=models.ForeignKey(Course,on_delete=models.CASCADE) marks=models.PositiveIntegerField() question=models.CharField(max_length=600) option1=models.CharField(max_length=200) option2=models.CharField(max_length=200) option3=models.CharField(max_length=200) option4=models.CharField(max_length=200) cat=(('Option1','Option1'),('Option2','Option2'),('Option3','Option3'),('Option4','Option4')) answer=models.CharField(max_length=200,choices=cat) class Result(models.Model): student = models.ForeignKey(Student,on_delete=models.CASCADE) exam = models.ForeignKey(Course,on_delete=models.CASCADE) marks = models.PositiveIntegerField() date = models.DateTimeField(auto_now=True) Student Model:- class Student(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) profile_pic= models.ImageField(upload_to='profile_pic/Student/',null=True,blank=True) address = models.CharField(max_length=40) mobile = models.CharField(max_length=20,null=False) taken_status = models.BooleanField(default=False) result_status = models.BooleanField(default=False) @property def get_name(self): return self.user.first_name+" "+self.user.last_name @property def … -
How to route many paths to one url in django python
I would like to route all paths ending in 'search/' to one url. I have tried many ways, But nothing worked. the following is the last that I tried. path(r'^search/$', views.search, name="search"), Can you please help? -
Django form looping closing tag
i'm trying to submit more than one form with one button using this as an example. The difference is that i'm adding forms dynamically using this code: {% load crispy_forms_tags %} <form method="POST" action="{% url 'App:Submit' %}"> {% csrf_token %} {% for form in forms %} <h3>Hour {{ form.Hour }}: </h3> <form> {% csrf_token %} {{ form|crispy }} </form> <br> {% endfor %} <br> <div class="col text-center"> <button class="btn btn-primary" type="submit">Send</button> </div> </form> Using this example, in Chrome, the main <form> tag with the action closes after the first loop. Any idea why this is happening? Thanks -
How to create if statement on a redirect to change Django model
I am trying to create a if statement in my Django view that detects when I am redirected to my complete order url. I want to do this because I would like to change my Django model Order 'complete' field to true. My redirect is coming from a javascript function in my paypal intergration. checkout.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h1>Checkout</h1> <div class='container'> <div class='row'> <div class='col-6'> <form action="" method='post' id='payement-form'> {% csrf_token %} <!-- {{ form|crispy }} --> <div class='col-12' id='paypal-button-container'></div> </form> <script src="https://www.paypal.com/sdk/js?client-id="> // Required. Replace YOUR_CLIENT_ID with your sandbox client ID. </script> <script> function redirect() { var url = "{% url 'complete-order' %}" window.location.href = url } paypal.Buttons({ createOrder: function (data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '0.01' } }] }); }, onApprove: function (data, actions) { // This function captures the funds from the transaction. return actions.order.capture().then(function (details) { // This function is the redirect redirect() alert('Transaction completed by ' + details.payer.name.given_name); }); } }).render('#paypal-button-container'); </script> </div> {% endblock content %} views.py @login_required(login_url='login') def checkout(request): order = Order.objects.get(user=request.user, complete=False) context = { 'order': order } return render(request, 'videogames/checkout.html', context) @login_required(login_url='login') def paymentComplete(request): order = Order.objects.get(user=request.user, complete=True) … -
Django admin.TabularInline function in a ModelForm outside the admin
Is there any way to replicate the TabularInline function outside the admin? I'm working with this model: class Sample(models.Model): id_sample = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=20) sample_id_sex = models.ForeignKey(Sex, on_delete=models.CASCADE, db_column='id_sex', verbose_name='Sexe') indexes = models.ManyToManyField(Index, through='SamplePoolIndexCand', through_fields=('sample_id', 'index_id'), blank=True, verbose_name="Índexs") pools = models.ManyToManyField(Pool, through='SamplePoolIndexCand', through_fields=('sample_id', 'pool_id'), blank=True, verbose_name="Pools") gene_cand_lists = models.ManyToManyField(GeneCandList, through='SamplePoolIndexCand', through_fields=('sample_id', 'gene_cand_list_id'), blank=True, verbose_name="Llista de gens candidats") class Meta: db_table = 'sample' The intermediate table is: class SamplePoolIndexCand(models.Model): sample_id = models.ForeignKey(Sample, null=True, blank=True, on_delete=models.CASCADE, db_column='id_sample', verbose_name='Mostra') pool_id = models.ForeignKey(Pool, null=True, blank=True, on_delete=models.CASCADE, db_column='id_pool', verbose_name='Pool') index_id = models.ForeignKey(Index, null=True, blank=True, on_delete=models.CASCADE, db_column='id_index', verbose_name='Índex') gene_cand_list_id = models.ForeignKey(GeneCandList, null=True, blank=True, on_delete=models.CASCADE, db_column='id_gene_cand_list', verbose_name='Llista de gens candidats') class Meta: unique_together = (("sample_id", "pool_id", "index_id", "gene_cand_list_id"),) db_table = 'sample_pool_index_cand' Using TabularInline in the admin I can do this to enter multiple set of values to one sample: Is there an easy way to do this in a ModelForm? -
Django user login or sign up not working. Does Django 3.2 have backwards compatibility?
I created a Django project with Django==2.8. And after implementing the login page everything works fine. but another collaborator pulled my code but he used Django==3.2 and compiled using that. Since then my login or create user does not work. It redirects to the same page with username and password both in the URL. The project still works when I run the server but most of the backend does not work. -
Why request.POST.get always empty in Django when using with react?
I am using react with Django framework and not Django rest framework and when I send a post request from react side, the request.POST.get('token', '') is always empty. token = request.POST.get("token") I tried many things like changing content type using request.data instead but nothing is working. Can anyone please tell Why I am not getting the post variable? -
Django server returns Authentication Error
my Django server that is deployed on Linux server returns 401 authentication error even though jwt token is included in the request. It works fine on my local machine, but after I deployed on a server and tried Get, Post request from postman, it returned 401 authentication error. I"m using Django Rest Framework, corsheader, JWT token. here is my source code. setings.py import os from datetime import timedelta from django.urls import reverse from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = ['*'] # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! try: from .secret_key import * except ImportError: pass # Application definition INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'djoser', 'users', 'invitations', 'dm', 'posts', 'corsheaders', "rest_framework_serializer_field_permissions", ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] ROOT_URLCONF = '[アプリ名].urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'evers_backend.wsgi.application' ASGI_APPLICATION … -
Use Phone number Field In AbstractBaseUser Django
I am Using This Package, But When I Want To Build The Database And Migrates, It Gives Me an Error: "ImportError: Module 'Accounts.apps' does not contain a 'AccountsConfigphonenumber_field' class. Choices are: 'AccountsConfig'." How Can I Use Another Package App In The Base User Model? Models.py: class User(AbstractBaseUser): email = models.EmailField(unique=True, max_length=255) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=200) phone_number = PhoneNumberField(unique=True) address = models.TextField(max_length=1000) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = 'phone_number' objects = UserManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin Settings (This Section): INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Accounts.apps.AccountsConfig' 'phonenumber_field', ] AUTH_USER_MODEL = 'Accounts.User' Forms.py: from django import forms from .models import User from django.contrib.auth.forms import ReadOnlyPasswordHashField from phonenumber_field.modelfields import PhoneNumberField from phonenumber_field.widgets import PhoneNumberPrefixWidget class UserCreationForm(forms.ModelForm): phone_number = PhoneNumberField(widget=PhoneNumberPrefixWidget(initial='IR')) password = forms.CharField(label='Password', widget=forms.PasswordInput) class Meta: model = User fields = ('email', 'password', 'phone_number') class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: model = User fields = '__all_ Managers.py from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, phone_number, password=None): if not email: raise ValueError('Users Must Have An Email Address') if not phone_number: raise ValueError('Users Must Have A Phone … -
couldn't apply migrations from django to mssql
python manage.py migrate Operations to perform: Apply all migrations: Likes, admin, auth, contenttypes, sessions, store, tags Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "C:\Users\Sulaiman\Desktop\jango\manage.py", line 22, in main() File "C:\Users\Sulaiman\Desktop\jango\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\core\management_init_.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\core\management_init_.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\db\migrations\migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\db\migrations\operations\models.py", line 528, in database_forwards alter_together( File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\sql_server\pyodbc\schema.py", line 156, in alter_unique_together self.execute(sql) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\sql_server\pyodbc\schema.py", line 861, in execute sql = str(sql) File "C:\Users\Sulaiman\AppData\Local\Programs\Python\Python39\lib\site- packages\django\db\backends\ddl_references.py", line 201, in str return self.template % self.parts KeyError: 'include' -
Django REST Framework unable to send multiple data
I am trying to send multiple JSON data in a single POST as a list like - [ { "name": "data", }, { "name": "data", } ] but getting the following error. { "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] } Here are my codes - Serializers.py class my_serializer_name(serializers.ModelSerializer): class Meta: model = my_model fields = '__all__' def validate(self, data): #Performing validation ...... ...... viewsets.py class my_viewset(viewsets.ModelViewSet): queryset = models.my_model.objects.all() serializer_class = serializers.my_serializer http_method_names = ['get', 'post'] def list(self, request): # Note the use of `get_queryset()` instead of `self.queryset` queryset = self.get_queryset() serializer = serializers.my_serializer(queryset, many=True) return Response(serializer.data) router.py router = routers.DefaultRouter() router.register('name' , my_viewset) How to solve this issue? -
What does GEOSGeometry exactly
Sorry it may be absurde but I got confused. I have seen two ways of creating a Polygon. from django.contrib.gis.geos import GEOSGeometry, LineString, Polygon 1- geometry = GEOSGeometry(Polygon(coordinates, srid=4326)) 2- geometry = Polygon(coordinates, srid=4326) Why is it important to add GEOSGeometry instead of just using the 2) ? -
ERROR: Could not build wheels for couchbase which use PEP 517 and cannot be installed directly
I am following the couchbase documentation and tried to install the python SDK and I am getting the above error. sudo -H python3 -m pip install couchbase I am using pipenv for my virtual environment. -
Django error : object has no attribute 'resolve_expression'
Can you give me a hint where to look or what to look for? Using Python 3.7.9 and Django 3.1.8, I have the following exception when in DEBUG mode. The problem does not appear when running in normal mode. The problem is new, it was first seen this week (it might have been there before). Going back in git does not help, the problem is still there. There is a lot of code changed. Can you please give me a hint or a solution? Django is new for me and I do not know how to tackle the issue. Exception has occurred: AttributeError (note: full exception trace is shown but execution is paused at: __getattribute__) 'Organization' object has no attribute 'resolve_expression' File "****/legal_entity/submodels/organization.py", line 416, in __getattribute__ (Current frame) return super().__getattribute__(name) File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1062, in resolve_lookup_value if hasattr(value, 'resolve_expression'): File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1267, in build_filter value = self.resolve_lookup_value(value, can_reuse, allow_joins) File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1380, in _add_q split_subq=split_subq, check_filterable=check_filterable, File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1358, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "****/core/subserializers/abstract/business_object.py", line … -
How to handle Many-to-Many Relation in Django without an Intermediary Table?
I have inherited a weird table structure: class Customer(models.Model): account_number = models.CharField() class Subscription(models.Model): account_number = models.CharField() So the Customer and Subscription models are linked by their account numbers. Each customer can have multiple subscriptions, and each subscription can have multiple customers, but there is no intermediary table; there is no "Account" table. How do I handle this sort of thing? If I have a Subscription queryset, how do I go about getting the corresponding Customer queryset without doing a horribly long query like customers = Customer.objects.filter(account_number__in=list(subscriptions.values_list('account_number', flat=True))) I'm trying to avoid this because it would generate a massive query that would take a very long time to execute. -
Issue passing id into url attempting fetch in Django
I'm trying to get the user post from jsonplaceholder. I get the user id from the users endpoint, and from there I'm trying to go to the user posts endpoint. With the 'print(context)' that is in views.py I correctly get the json data of the user I passed in the 'all_users' view, but I'm getting NoReverseMatch at /users/1/ Reverse for 'user' with no arguments not found. 1 pattern(s) tried: ['users/(?P<id>[^/]+)/$'] views.py def user(request, id): response = requests.get(placeholder_url + 'users/' + str(id) + '/posts') user = response.json() context = { 'user': user } print(context) return render(request, 'user.html', context) urls.py urlpatterns = [ path('users/', all_users, name='users'), path('users/<str:id>/', user, name='user') ] users.html <p class="card-text">{{ user.email }}</p> <a href="{% url 'user' user.id %}" class="btn btn-outline-primary">See Posts</a> -
Django REST Framework - How to display an APIException if HTTP_400_BAD_REQUEST?
I'm new to DRF and just have setup my first usable POST endpoint, please see my code to create a new User object using POST: views.py: @api_view(['POST']) @permission_classes([AllowAny]) def user_create(request): if request.method == 'POST': serializer = CreateUserSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return JsonResponse(serializer.data, safe=False) serializers.py class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ('user', 'password') extra_kwargs = {'password': {'write_only': True}} # We don't want to show the hashed password def create(self, validated_data): password = validated_data.pop('password') user = User.objects.create_user( validated_data['user'], ) user.set_password(password) user.save() return user So far so good. If I now want to create a User Object using POST it works fine for the first time. But if I send the same request twice, the second request just returns "Bad Request". That also makes sense as the User object is already existing. It would be awesome if I would be able to catch this exception somehow and return a message instead of HTTP_400_BAD_REQUEST. So I checked the DRF docs right here, https://www.django-rest-framework.org/api-guide/exceptions/ It says: Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the HTTP_400_BAD_REQUEST responses that are returned …