Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django model to yeild specific HTML output without redundancy in the model
I have 3 models (supervisor, students, and allocation) I am building an allocation system where multiple students can be allocated to one supervisor Now I want my model to be able to yeld this output Example of how i want the output to come out Here are the structure of my model class StudentProfile(models.Model): stud_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True) user_id = models.OneToOneField(User,blank=True, null=True, on_delete=models.CASCADE) programme_id = models.ForeignKey(Programme, on_delete=models.CASCADE) session_id = models.ForeignKey(Sessi`**enter code here**`on, on_delete=models.CASCADE) type_id = models.ForeignKey(StudentType, on_delete=models.CASCADE) dept_id = models.ForeignKey(Department, on_delete=models.CASCADE) class SupervisorProfile(models.Model): super_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE) dept_id = models.ForeignKey(Department, on_delete=models.CASCADE) class Allocate(models.Model): allocate_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True) stud_id = models.ForeignKey(StudentProfile, on_delete=models.CASCADE) super_id = models.ForeignKey(SupervisorProfile, on_delete=models.CASCADE) now my main focus is the Allocate model where the allocation is made, and there is a lot of redundancy any suggestions on how to improve my model to remove redundancy in yielding the expected HTML output would be appreciated π -
How to solve No module named 'django.contrib.staticfilespages' in Django?
I was studying from the book "Django for Beginners" by William S. Vincent. Whenever I try to run the code from chapter 2, Hello World App, I get "No module named 'django.contrib.staticfilespages' " This question has already been asked by someone else on Django.fun but no answers there. I can't find anyone else having a similar problem on the internet. Also Pycharm is not showing any error to help me with this. File "C:\Users\rexze\PycharmProjects\djangoProject\manage.py", line 22, in <module> main() File "C:\Users\rexze\PycharmProjects\djangoProject\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\rexze\PycharmProjects\djangoProject\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\rexze\PycharmProjects\djangoProject\venv\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Users\rexze\PycharmProjects\djangoProject\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\rexze\PycharmProjects\djangoProject\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) mod = import_module(mod_path) File "C:\Users\rexze\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django.contrib.staticfilespages' (venv) PS C:\Users\rexze\PycharmProjects\djangoProject> python manage.py startserver Traceback (most recent call last): File "C:\Users\rexze\PycharmProjects\djangoProject\manage.py", line 22, in <module> β¦ -
Django form fields required and optional configuration
I am in a middle of a project. I have a model :- class CustomersModels(models.Model): def servChoices(servs): lst = [x.serv_name for x in servs] ch =() for a in lst: ch += (a,a), return ch customer_name = models.CharField(max_length=100) comp_name = models.CharField(max_length=100) ph_no = models.CharField(max_length=12) webs_name = models.URLField(max_length=200) service_insterested = models.OneToOneField(ServiceModel, on_delete = models.CASCADE) def __str__(self): return self.customer_name I have a corresponding form for this model. Now what i want is the fields customer_name, comp_name, webs_name to be optional in one page. And required in another page. Please guide me to establish the task in the most convenient manner -
Using Django model manager to return a queryset based on a complex class method
I have a model called Stockentry: class Stockentry(models.Model): id = models.AutoField(primary_key=True, unique=True) distributor = models.ForeignKey( Distributor, blank=True, null=True, on_delete=models.SET_NULL) ... def is_payment_overdue(self): days = self.daysdue() if self.paid == True: # Already paid return False # Not already paid try: if days >= self.distributor.credit_days: # Is overdue if has already exceeded the credit period extended by distributor to dealer return True else: # Is not overdue return False except: # TODO. Currently a temporary catchall return False I am using DRF. I wish to have a query like this to return a queryset where is_payment_overdue is True stockentries = Stockentry.objects.filter(store=store).is_overdue() I started like this: class StockentryManager(models.Manager): def get_queryset(self): return super().get_queryset() def is_overdue(self): myset = super().get_queryset() And went through the docs, but couldnt understand how to utilize this to my specific scenario. I also came across a SO post, which wasnt a minimal complete example, and lacked specifics of implementation. Kindly explain how to go about implementing this for my code. -
Unable to Deploy Django in Heroku
I am unable to deploy django in Heroku. I think the problem lies with Ajax because all of the pages seems to render in heroku. Error that I got is: InvalidCursorName at /incidentReport/general cursor "_django_curs_140297876031040_sync_1" does not exist During handling of the above exception (relation "incidentreport_accidentcausation" does not exist LINE 1: ...cidentreport_accidentcausation"."updated_at" FROM "incidentr... ^ ), another exception occurred: Thank you HTML <!-- Page Content --> <div class="container-fluid"> <!-- Page Title --> <div class="d-flex bd-highlight"> <div class="pg-title p-2 flex-grow-1 bd-highlight"> <h4>Incident Report</h4> </div> </div> <!-- User Report Table --> <div class="card shadow mb-5 d-flex "> <!-- Top Pagination --> <div class="card-header py-3"> <ul class="nav nav-tabs"> <li class="nav-item"> <a class="nav-link active" href="{% url 'incident_report_general' %}">General</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'incident_report_people' %}">People</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'incident_report_vehicle' %}">Vehicle</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'incident_report_media' %}">Media</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'incident_report_remarks' %}">Remarks</a> </li> </ul> </div> <div class="card-body"> <div class="table-responsive"> <table> <form id="form_incidentgeneral" action="{% url 'incident_report_general' %}" enctype="multipart/form-data" method="post" data-acc-url="{% url 'ajax_load_accident' %}"> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputEmail4">Date</label> {{user_report_form.date}} </div> <div class="form-group col-md-6"> <label for="inputPassword4">Time</label> {{user_report_form.time}} </div> </div> <hr> <div class="form-row"> <div class="form-group col-md-12"> <label for="inputAddress">Street Address</label> {{user_report_form.location}} </div> </div> <hr> β¦ -
Direct URL to a file in Django Template
I have a CSV file that users downloaded online and saved in a directory on my app. I am trying to create a link to this file so that the user can click the link and the file can be downloaded automatically to their computer. The code below keeps telling file not found. Please does anyone know how to solve this? {% extends 'base.html' %} {% block main %} <p> <a href="/kaggle_dataset/emmy/IRIS.csv" download> Download File </a> </p> {% endblock main %} -
What does a class followed by method does in Python
In Django urls there is this code: path("login/", Login.as_view(), name="loggps") Login is a class and as_view() is a method but is not in the Login class, probably is in a Parent class. What does Class.method does in Python? -
'NoneType' object has no attribute 'save' Django
I'm getting this error when I try to log in with a nonvalid user, I want to be redirected to the login page instead. It highlights the user.save() on muy views.py views.py def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): user = authenticate(request, **form.cleaned_data) user.save() if user: login(request, user) return redirect('home') else: return redirect(reverse('login')) else: form = LoginForm() return render(request, 'accountApp/login.html', {'form': form}) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm class LoginForm(forms.Form): username = forms.CharField(max_length=100) password = forms.CharField(widget=forms.PasswordInput) login.html {% block content %} <form method="post"> {% csrf_token %} <h1>Login</h1> <fieldset class="form-group" style="width: 250px;"> {{ form|crispy }} </fieldset> <button type="submit">Log In</button> </form> {% endblock %} -
How can I define or customize my django user from a existintg user model table in SQLSERVER?
I have a database in SQLSERVER with an user table. it contains atributtes like id,email, password, name, lastname,verificationCode and this table is connected with other and it keep going. I know that django has an authentication method and it works with django user model. the question is. How can I define (or customize) my django user model from a existintg user table in SQLSERVER with the purpose to use django auth system and no be redundant with the datas? -
Diaz Canel Singao
I have these problem, I need to generate a col-md-4 from Django-Admin, the trouble is that I want to show other col-md-4 just if the previous col-md-4 get 10 items. Please help me, is my tesis <div class="col-lg-4"> <div class="single-price" style="border-radius: 8px;"> <ul class="price-list"> {% for doc in Documento %} {% if 10 >= forloop.counter %} <li class="d-flex align-items-center"><a href="{{ doc.documento.url }}" download="" target="_blank" rel="noopener noreferrer"> <img src="{{ doc.Γcono.url }}" alt="" style="width: 40px; margin-right: 10px;"> </a> <span style="text-align: left;">{{ doc.nombre }}</span> <!-- <a href="/static/descargables/Ctto-Marco-MAR-2022-.docx" download="true" class="price-btn">Descargar</a> --> </li> {% endif %} {% endfor %} </ul> </div> </div> {% endfor %} -
clone django model with copy function
I have a model and I want to copy all of my data when copy function called and it make a copy of my books with new datetime I wrote this: class Book(models.Model): name = models.CharField(max_length=255) created_date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey('Author', on_delete=models.CASCADE) def copy(self): new_book = Book() new_book.name = self.name new_book.created_date = models.DateTimeField(auto_now_add=True) new_book.author = self.author new_book.save() class Author(models.Model): name = models.CharField(max_length=255) but author won't copied well -
Resolve UUID to DangoObjectNode in Subquery
I've got a database with an simple Employee model and node in Django. IΒ΄m using Graphene to create an API around this that allows a user to retrieve the right data. class Employee(models.Model): id = models.UUIDField(primary_key=True, unique=True, ) name = models.CharField(max_length=128) class EmployeeNode(DjangoObjectType): class Meta: model = Employee fields = "__all__" interfaces = (graphene.relay.Node, ) Now in addition to this, I have a query that finds a "buddy" for every Employee, which is another Employee (ID) in the database, and a function (details irrelevant here) that finds the correct "buddy" in the database using some not further specified Django query. class EmployeeNodeWithBuddy(DjangoObjectType): buddy_id = graphene.UUID() class Meta: model = Employee fields = "__all__" interfaces = (graphene.relay.Node, ) @classmethod def get_queryset(cls, queryset, info): set_with_buddy_annotation = queryset.annotate( buddy_id=ExpressionWrapper(Subquery( ### Omitting the details of this query ### ).only('id')[:1], output_field=models.UUIDField() ), output_field=models.UUIDField()) ) return set_with_buddy_annotation This works ok, but what I actually want is not the ID of the buddy, but the actual EmployeeNode. I canΒ΄t figure out if there is a good way to annotate/add info to this query to make it return the thing I want. It would look like: class EmployeeNodeWithBuddy(DjangoObjectType): buddy_id = graphene.UUID() buddy = graphene.Field(EmployeeNode) # Field with EmployeeNode β¦ -
Django - i cant migrate my model "prestamo"
this is my model https://i.stack.imgur.com/XqonC.jpg} and this is my error https://i.stack.imgur.com/qVa5M.jpg i dont know how to solve it -
Nginx 502 gateway error with AWS RDS Aurora, Django, and Daphne
I am trying to run an open source cloud project described here. I want to use an AWS RDS Aurora instance, instead of the project's default database, so I followed their instructions to do that here. However, when I reload the server: bash ~/cloud_station_deployment/reload_server.sh and go to my website's URL, I get a 502 Bad Gateway error with Nginx: How should I solve this error? This is what I tried to find the cause of the problem: sudo systemctl status nginx output: β nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Active: active (running) since Fri 2022-09-30 19:32:21 UTC; 2h 23min ago Docs: man:nginx(8) Main PID: 2532 (nginx) Tasks: 2 (limit: 1140) CGroup: /system.slice/nginx.service ββ2532 nginx: master process /usr/sbin/nginx -g daemon on; master_process on; ββ3174 nginx: worker process Sep 30 19:32:20 ip-172-31-83-16 systemd[1]: Stopped A high performance web server and a reverse proxy server. Sep 30 19:32:20 ip-172-31-83-16 systemd[1]: Starting A high performance web server and a reverse proxy server... Sep 30 19:32:21 ip-172-31-83-16 systemd[1]: nginx.service: Failed to parse PID from file /run/nginx.pid: Invalid argument Sep 30 19:32:21 ip-172-31-83-16 systemd[1]: Started A high performance web server and a reverse β¦ -
Why is my JavaScript function adding increasingly more rows?
I have a document with many buttons, all of which contain onclick="myFunction()" inside the button tag. When I click the 1st button, 1 row is added to my table, as desired. However, as I click the 2nd button, 2 rows are added to my table, and so on, i.e. i rows are added on the ith button click. How can I fix my JavaScript function to only add 1 row for each new button click? function myFunction() { table_body = document.getElementById("t_body"); document.addEventListener('click', (e) => { let element = e.target; if(element.tagName == "BUTTON") { row = table_body.insertRow() cell1 = row.insertCell(); cell1.innerHTML = element; cell2 = row.insertCell(); cell2.innerHTML = element.id; cell3 = row.insertCell(); cell3.innerHTML = element.id; cell4 = row.insertCell(); cell4.innerHTML = element.id; element.style.backgroundColor = '#004d00'; element.style.color = 'white'; } }); } -
How update the CheckboxSelectMultiple from django in html
I was using this tutorial in my code, to have an update page in my work, but I'm having a hard time showing the information of a CheckboxSelectMultiple on this update page. How do I do this? -
Django POST method is not receiving all input fields from HTML
please I would like to ask for help. I'm creating a web-based application and I'm having a hard time when I try to get the data from the HTML form and receive it through the POST method in Django. It's pulling data only from one field and I really appreciate your help in figuring out why it's not pulling information from the other fields only from the location field. Thank you very much! HTML = create-request.html <form action="{% url 'save_request' %}" id="checklistForm" name="checklistForm" enctype="multipart/form-data" method="POST"> {% csrf_token %} <section id="step-1" class="form-step"> <div class="mt-3"> {% include 'home/1_resource-request.html' %} </div> </section> </form> HTML = home/1_resource-request.html {% block stylesheets %}{% endblock stylesheets %} {% block content %} <div class="pcoded-content"> <div class="pcoded-inner-content"> <div class="main-body"> <div class="page-wrapper"> <div class="row"> <div class="col-sm-12"> <div class="card"> <div class="card-header"> <h5>Resource Request</h5> </div> <div class="card-body"> <div class="row"> <div class="col-md-6"> <form> <div class="form-group"> <label for="checklistID">Checklist Number</label> <input type="text" class="form-control" id="checklistID" name="checklistnum" placeholder="123456" disabled/> </div> <div class="form-group"> <label for="location_ID">CMPA Location</label> <select class="form-control" id="location_ID" name="location"> <option selected>Select</option> <option>Brazil</option> <option>Canada</option> <option>Mexico</option> <option>SSA</option> <option>United States</option> </select> </div> </form> </div> <div class="col-md-6"> <form> <div class="form-group"> <label for="support_id">CMPA Support Needed</label> <select class="form-control" id="support_id" name="support"> <option selected>Select</option> <option>Both</option> <option>PMA - Financial Management</option> <option>PMO - Project Administration</option> </select> </div> β¦ -
Django: prefetch_related in nested serializers does not reduce thousands of db queries, and can even introduce more
I have a strange situation. I've done so much reading on avoiding the N+1 problem and have tried prefetching but to no avail. My setup is like this: Models: class A(models.Model): # some stuff class B(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE, related_name="b_objs") class C(models.Model): somefield1 = models.CharField(max_length=100) somefield2 = models.CharField(max_length=100) # Assume that classes Y and Z exist. We don't care about them. # In the serializer, the fields don't include 'y' and 'z' y = models.ForeignKey(Y, on_delete=models.CASCADE) z = models.ForeignKey(Z, on_delete=models.CASCADE) class D(models.Model) b = models.ForeignKey(B, on_delete=models.CASCADE, related_name="d_objs") c = models.ForeignKey(C, on_delete=models.CASCADE) Visually: D --> B --> A D --> C --> Y and Z (Again, we don't care about C's FKs to Y and Z) There is 1 A object, 8 B objects pointing to A, 188 C objects, and 1291 D objects pointing to some combination of those 8 Bs and 188 Cs. When I serialize an A object, it propagates down and serializes all of these objects. The serializers are like so: class CSerializer(serializers.ModelSerializer): class Meta: model = C fields = ['somefield1', 'somefield1'] class DSerializer(serializers.ModelSerializer): c = CSerializer() class Meta: model = D fields = '__all__' class BSerializer(serializers.ModelSerializer): d_objects = serializers.SerializerMethodField(method_name='get_d_objects') class Meta: model = B fields β¦ -
Django No Module Named... when calling a function in another folder
I have a Django application and in my views.py file I am trying to call a function that is located in another file in another folder, still in the same app. My folder structure looks like: .administraion βββ background_tasks β βββ magic_update_set.py βββ migrations β βββ __init__.py βββ __init__.py βββ admin.py βββ config.py βββ models.py βββ tests.pu βββ urls.py βββ views.py In the magic_update_set.py file I have the following function: def magic_set_update_bg_task(options): ... In my vioews.py I have: from background_tasks.magic_update_set import magic_set_update_bg_task ... def update_magic_set_function_queue(request): options = { 'code': request.POST['code'], } magic_set_update_bg_task(options, verbose_name='Set Update') return HttpResponse(status=200) Error: Traceback (most recent call last): File "C:\Users\rossw\Documents\Projects\card_companion\manage.py", line 22, in <module> main() File "C:\Users\rossw\Documents\Projects\card_companion\manage.py", line 19, in main execute_from_command_line(sys.argv) File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\core\management\base.py", line 393, in execute self.check() File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\urls\resolvers.py", line 416, in check for pattern in self.url_patterns: File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = β¦ -
Django, sqlite in memory in production
I did this in settings.py 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3' }, 'in_memory_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ":memory:" } I have a small amount of data that I would like to store in a database in memory, but I have a problem. Everything works well in the default database, but in "in memory" it is not possible to save any record, the error `no such table comes out. As a result, I don't quite understand how to work with such a database, it seems to me that it is deleted after the migration. How to work with it, handle it? What are your ideas? I just need to migrate one table, write data there, then read and delete them as in the default database. -
Django ListView: how to show few entry and protect the other
I have a model with few entries. I'd like to show only few of them and protect the others... example: class Squadra(models.Model): ... tipo = models.IntegerField(choices=TIPO_SQUADRA, default=1) ... Then I have a ListView which return only few Squadra objects using a filter: all_squadre = Squadra.objects.filter(tipo=3) and a url file including this: path('squadra_table/<int:squadra>/', views.SquadraTableListView.as_view() ), My problem is that someone could get to the Squadra page and then he could try to change randomly the ID <int:squadra> in the url and access other entries which I'd like to keep protected... How can I do that? Thanks for helping Attilio -
Removing data in a Django Template Forloop
I have a for loop in a Django Project as following: {% for i in active_session.log.values %} {% if i.log_order == b.order and i.log_exercise == e.name %} <button type="submit" id="submitlog" class="......"> <i class="fa-solid fa-check"></i> </button> {% else %} <button type="submit" id="submitlog" class="......"> <i class="fa-solid fa-x"></i> </button> {% endif %} {% endfor %} This is the current outcome: My question: How can I get rid of the X in the and only keep the check buttons I have tried the following but did not work: {% if active_session.log.log_order == b.order and active_session.log.log_exercise == e.name %} this is the required outcome: -
Django how to check if a table is being used as a foreignkey of another table
So, I have two models, Order and Orders, and for each item that I have in my session(cart) Im creating an Order_object(saving in database) and after each item is saved I want to do a check for every Order telling which ones are not a foreign key in Orders, if not, create an Orders_object than add each Order who is not a foreign key of Orders And I wish that each Orders have multiple Order Models.py class Order(models.Model): ----fields--- class Orders(models.Model): order = models.ManyToManyField(Order) ----other fields ------ I want to dosomething like this but I dont know if it will work, can somebody confirm if this works?: Note: even if this code that I wish to test works, im not adding multiple Order_object in Orders_object, im just creating an Orders_object containing only one Order_object for order_object in Order: check_if_doesnt_have_foreign_key = True for orders in Orders: if orders.order == order_object check_if_doesnt_have_foreign_key = False break: if check_if_doesnt_have_foreign_key == True: orders = Orders(order=order_object) orders.save() -
Django ModelViewSet returning full HTML 500 error on duplicate field set to unique=true
I have been trying to fix this all morning but can't seem to find the issue. I have a specific API returning an IntegrityError duplicate key error in the form of the Django HTML error traceback instead of returning a detail error on the form field. Exception Type: IntegrityError at /api/chats/ Exception Value: duplicate key value violates unique constraint "chats_chat_title_853c3234_uniq" DETAIL: Key (title)=(New Chat) already exists. Model with a title field set to unique: class Chat(TimestampedModel): """ A chat between multiple users. """ uuid = models.UUIDField(default=uuid4, null=False) title = models.CharField( max_length=255, null=False, unique=True, blank=False) Serializer for the chat: class ChatSerializer(serializers.ModelSerializer): title = serializers.CharField(max_length=255) def create(self, validated_data): """ Creates a new Chat and adds the m2m employees to it """ user = self.context['request'].user title = validated_data['title'] # Add the user to the chat employee_ids = validated_data.pop("employee_ids") employee_ids.append(user.id) # Create and save the chat # Add the employees to the chat # Add the sender to the chat chat = Chat.objects.create(created_by=user, title=title) chat.employees.set(employee_ids) chat.employees.add(user) chat.save() return chat And the ViewSet: class ChatViewSet(MixedPermissionModelViewSet): lookup_field = 'uuid' queryset = Chat.objects.all() serializer_class = ChatSerializer permission_classes_by_action = { 'list': [IsAuthenticated], 'create': [IsAuthenticated], 'update': [IsAuthenticated], 'retrieve': [IsAuthenticated], 'partial_update': [IsAuthenticated], 'destroy': [IsAuthenticated] } def add_user_has_viewed(self, chat): if self.request.user β¦ -
Inserting POINT Geometry from DJANGO to POSTGIS database error
Hello I try to use DJANGO to insert point clicked on Leaflet in a POSTGIS database. During the import I receive the following error : "function st_geomfromewkb(bytea) does not exist" My understanding is that the ST_GeomFromEWKB is used to insert binary representation od geometry, and this is quite weird here because what I intend to do is inserting a wkb object. my view is defined as bellow: from django.contrib.gis.geos import Point def add_site(request): if(request.method == 'POST'): site_name = request.POST.get('site_name') customer_name = request.POST.get('customer_name') lat = str(request.POST.get('lat')) lng = str(request.POST.get('lng')) point = Point(lng,lat,srid=4326).wkb logger.info(type(point)) insert = customers_sites(site_name=site_name,customer_name=customer_name,geom=point) insert.save() Any idea of what is wrong here ?? Thank you for your help !