Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unexpected result : "detail": "Method \"GET\" not allowed."
I am learning django restframework for the first time , and I am not able to debug this error since a while , please help in debugging this issue. Thanks! HTTP 405 Method Not Allowed Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Method \"GET\" not allowed." } Here is my code of views.py from django.shortcuts import render from rest_framework import generics, status from .serializers import RoomSerializer, CreateRoomSerializer from .models import Room from rest_framework.views import APIView from rest_framework.response import Response class RoomView(generics.ListAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer class CreateRoomView(APIView): serializer_class = CreateRoomSerializer def post(self, request, format=None): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() serializer = self.serializer_class(data=request.data) if serializer.is_valid(): guest_can_pause = serializer.data.get('guest_can_pause') votes_to_skip = serializer.data.get('votes_to_skip') host = self.request.session.session_key queryset = Room.objects.filter(host=host) if queryset.exists(): room = queryset[0] room.guest_can_pause = guest_can_pause room.votes_to_skip = votes_to_skip room.save(update_fields=['guest_can_pause', 'votes_to_skip']) return Response(RoomSerializer(room).data, status=status.HTTP_200_OK) else: room = Room(host=host, guest_can_pause=guest_can_pause, votes_to_skip=votes_to_skip) room.save() -
Django: QuerySet.update() returns FieldError when using Count() with filter
Given that: class User(models.Model): organization = models.ForeingKey( "Organization", related_name="users", ... ) is_active = models.BooleanField(default=True) class Organization(models.Model): user_count = models.IntegerField(default=0) When I run this, if we run line 2 or 3 exclusively, both fail: # Line: 1 active_count = Count("users", filter=Q(users__is_active=True)) # Line: 2 Organization.objects.update(user_count=active_count) # Line: 3 Organization.objects.annotate(num_users=active_count).update(user_count=F("num_users") I get the following error: FieldError: Joined field references are not permitted in this query Annotating (annotate()) instead of updating, works just fine. I couldn't find examples of this solution using Subquery() What's an alternative to this requirement? Am doing making a design mistake perhaps? -
Models Django not iterable
I have some problems with Django models, I would like to iterate data got from the textfield from the form based on model. But I can't it still an error: TypeError at /kod/start/ 'Passwords' object is not iterable Request Method: POST Request URL: http://127.0.0.1:8000/kod/start/ Django Version: 3.2.8 Exception Type: TypeError Exception Value: 'Passwords' object is not iterable Exception Location: /home/natalia/PycharmProjects/django_project/kodszyfru/views.py, line 52, in start Python Executable: /home/natalia/PycharmProjects/django_project/venv/bin/python3 Python Version: 3.8.10 Python Path: ['/home/natalia/PycharmProjects/django_project', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/natalia/PycharmProjects/django_project/venv/lib/python3.8/site-packages'] Server time: Fri, 22 Oct 2021 16:03:53 +0000 Code models.py from django.db import models # Create your models here. class Passwords(models.Model): text = models.TextField(max_length=2000,null=True) cipher = models.CharField(max_length=64) def __str__(self): return self.text views.py def start(request): password_form = PasswordsForm(request.POST or None) if password_form.is_valid(): text = password_form.save() try: for i in text: value = (alphabet[i]) klucz = 10 new_value = int(value) + klucz if new_value > 70: new_value = new_value - 70 for key, value in alphabet.items(): if value == str(new_value): print(key, end='') return '' except KeyError: return ('Nie znaleziono wartości' + i + ' w słowniku!') return render(request, 'kod.html', {'kod': kod}) return render(request, 'start.html', {'password_form': password_form}) I would be grateful for help!! Natalia -
Apply filter to field with lookup
I have seen a couple of similar questions on StackOverflow (Troubleshooting "Related Field has invalid lookup: icontains", Django error Related Field got invalid lookup: icontains, Related Field got invalid lookup: icontains, Django: Unsupported lookup 'case_exact' for CharField or join on the field not permitted, Filtering on Foreign Keys in Django) but unfortunately the answers on those questions have not helped me. If a hotel only has four double rooms and there are already four bookings for the first week of October, I want to prevent the next user being able to make a fifth booking for the first week of October. This was working - RoomBookings.objects.filter(HotelName__icontains=hotel.HotelName, RoomType__icontains= hotel.RoomType, ArrivalDate__lt=RoomBookingsForm['DepartureDate'], DepartureDate__gt=RoomBookingsForm['ArrivalDate']) But then I changed the HotelName field in the RoomBookings model from CharField to ForiegnKey. And now I cannot figure out how to do a reverse lookup. These are my failed attempts - # queryset2 = RoomBookings.objects.filter(HotelName__HotelName__icontains=hotel.HotelName) # queryset2 = RoomBookings.objects.filter(HotelName__Hotel__HotelName__icontains=hotel.HotelName) # queryset2 = RoomBookings.objects.filter(HotelName__Hotel__HotelName_exact=hotel.HotelName) # queryset2 = RoomBookings.objects.filter(HotelName__HotelName_exact=hotel.HotelName) class Hotel(models.Model): HotelName = models.CharField(max_length=60, null=False) HotelOwner = models.CharField(max_length=60, null=True) FirstLineAddress = models.CharField(max_length=60, null=False) SecondLineAddress = models.CharField(max_length=60, null=True) PostCode = models.CharField(max_length=60, null=False) Country = CountryField(max_length=120, null=True) PhoneNumber = PhoneNumberField(null=True, blank=False, unique=True) Email = models.EmailField(max_length=254) def __str__(self): return self.HotelName class RoomType(models.Model): HotelName … -
How to add new field in model after custom migration which access model before new field?
I have custom migration file which creates entry in table user. Initial working project has these migrations: 1. 001_initial.py # creates model with some fields 2. 002_custom_user_data.py # adds data in "user" due some middle requirement after some time. Now I want to add one more column to this table as "config_data". For this I have followed below steps: 1. python manage.py makemigrations <app-name> # creates one more migration file` 003_add_config_data_field.py 2. python manage.py migrate # raise an error migrate command raises below error. Applying my_user.001_initial.py... OK Applying my_user.002_custom_user_data.py ...Traceback (most recent call last): File "/home/myhome/.local/share/virtualenvs/myproject/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column my_user.config_data does not exist LINE 1: ..., "my_user"."address", This is because migration 002 tries to access my_user table before the add field migration(003) is migrated in the table, which is raising UndefinedColumn config_data error. Any idea how can be this resolved as these migrations should work for fresh DB as well as production dB in which till 002 is migrated earlier. Below is the migration for 002_custom_user_data.py # Generated by Django 3.2.2 from django.db import migrations from myapp.models import MyUser def create_user(apps, schema_editor): user = MyUser.objects.get_or_create(id=123) user.address = 'demo' user.save() def delete_user(apps, schema_editor): MyUser.objects.filter(id=123).delete() class … -
When I loop through from the database and render it to the page with VUE-Js v-for , it becomes disorganized
So when I loop through my data from the API, I am trying to fit the data into bootstrap rows and columns, but it keeps getting rendered wrongly. I am using the VUE-Js v-for directive to loop through the data I am getting from my Django rest API.[enter image description here][1] This is when I pass the data to the component [[1]: https://i.stack.imgur.com/UGtRp.png][1] This is when I am trying to loop through the data[ [1]: https://i.stack.imgur.com/OjsZF.png][2] This is how it renders to the page [[1]: https://i.stack.imgur.com/bRZRy.png ] -
¿Como filtrar las opciones de un campo select en base al valor de otro campo del mismo tipo en un formulario Django? [closed]
El problema que tengo es el siguiente, quiero acceder al valor seleccionado en tiempo real de un campo select en mi formulario y en base a este, filtrar las opciones para el cliente. El campo en específico es el que corresponde en el model Request al atributo product_type, el cual según la opción que seleccione a partir de un choice, se filtre el segundo campo, el de product (Product tiene una fk que apunta al product_type) mis models.py class ProductType(models.Model): name = models.CharField("Nombre", max_length=100) def __str__(self): return f'{self.name}' class Product(models.Model): name = models.CharField("Producto", max_length=250) price = models.IntegerField("Price") type = models.ForeignKey(ProductType, on_delete = models.CASCADE) def __str__(self): return f'{self.name}' class Request(models.Model): CUSTOMER_TYPE = [ ('IND', 'Individuos'), ('NEG', 'NEGOCIOS'), ] COMPANIES = [ ('CLA', 'Claro'), ('PER', 'Personal'), ('TUE', 'Tuenti'), ('MOV', 'Movistar'), ('OTR', 'Otro'), ] types = ProductType.objects.all() PRODUCT_TYPE = [] for o in types: key = o.name[:3] value = o.name t = (key,value) PRODUCT_TYPE.append(t) customer_type = models.CharField(max_length=150, choices=CUSTOMER_TYPE) product_type = models.CharField(max_length = 150, choices = PRODUCT_TYPE) product = models.ForeignKey(Product, on_delete=models.CASCADE) date_of_sale = models.DateTimeField(auto_now_add=True) request_source = models.ForeignKey(RequestSource, on_delete=models.CASCADE) seller = models.ForeignKey(User, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) #Portability current_company = models.CharField(max_length=150, choices=CUSTOMER_TYPE) mobile_to_carry = models.CharField("Número a portar", max_length=13) pin = models.IntegerField("Pin") #Internet services address_coordinates = … -
Please help: Reverse for 'all_clients' with keyword arguments '{'client_id': 3}' not found. 1 pattern(s) tried: ['clients/all_clients/$']
I am new to django and I am having trouble implementing the edit template to my project. I am encountering the following error: Reverse for 'all_clients' with keyword arguments '{'client_id': 3}' not found. 1 pattern(s) tried: ['clients/all_clients/$'] I have looked on the site for similar occurrences such as Reverse for 'plan_edit' with keyword arguments but I haven't been able to pin point the issue. I believe the issue arises when I add a hyperlink to my all_clients.html template. Also, the template pages for /clients/edit_client/?/ will load, however after submission using the save changes button the NoReserse Match error resurfaces as it attempts to load the clients/all_clients page. Any help on this matter would be greatly appreciated. See code below: models.py from django.db import models # Create your models here. class Client(models.Model): #A client is composed of the company general info text = models.CharField('Company Name',default = 'Company Name', max_length = 200) phone_num = models.CharField('Phone Number', default = '000-000-000', max_length = 12) ceo_name = models.CharField ('CEO', max_length = 50) num_employees = models.IntegerField('Number of Employees', default = 0) maintenance_schedule = models.CharField('maintenance schedule', max_length = 100) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text class Location(models.Model): #Location holds … -
Can I delete the third-party Python library `future` after moving exclusively to Python 3?
The future module (https://pypi.org/project/future/) is "the missing compatibility layer between Python 2 and Python 3." I have a Django project that was ported from Python 2 to 3 long ago, but future is still a requirement. My question is: now that the project only needs to run on Python 3, is there much danger in deleting the requirement for future? My own investigations: After deleting future from requirements.txt, the unit tests still pass. Grepping my project source, I don't see any imports of builtins, which future shadows in Python 2. The future docs say The imports have no effect on Python 3. On Python 2, they shadow the corresponding builtins, which normally have different semantics on Python 3 versus 2, to provide their Python 3 semantics. So deleting future seems pretty safe, but is there anything I'm missing? Thanks. -
+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) TypeError: 'module' object is not callable
here is my django project's urls.py from django.urls import path from .import views from django.conf import settings from django.conf.urls import static urlpatterns = [ path('',views.index,name='home'), path('abouts/about/',views.about,name='about'), path('abouts/contact/',views.contact,name='contact'), path('orders/cart/',views.cart,name='cart'), path('shops/dashboard/',views.dashboard,name='dashboard'), path('shops/orders/',views.orders,name='orders'), path('shops/checkout/',views.checkout,name='checkout'), ] +static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) and the part of settings.py where I defined media url and media root import os # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' STATICFILES_DIRS = [ BASE_DIR/ 'static', ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_URL='/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') but the server says ile "C:\Users\ITS\Desktop\e-com\commerce\shop\urls.py", line 15, in <module> ] +static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) TypeError: 'module' object is not callable I do this always but now it showing me this. thanks in advance for helping. -
show the particular table row based on checkbox
I want to display the table row based on the multi choice selection where I'm retrieving the data from the database there would be 1000+ rows among that I need to display only the particular row. I'm noob in JavaScript and took this snippet from How to show table rows based on checkbox selected I tried to modify the code as per the requirement but I couldn't able to figure out. I have cut the td part to reduce the code length there would be 16 columns around. pls help me out if any other JS script would be provided also it would be much helpful. <div>Country</div> <div class="row" name="country_checkbox" id="id_row" onclick="return filter_type(this);"> <ul id="id_country"> <li><label for="id_country_0"><input type="checkbox" name="country" value="NORTHAMERICA" placeholder="Select Country" id="id_country_0"> NORTHAMERICA</label> </li> <li><label for="id_country_3"><input type="checkbox" name="country" value="LATAM" placeholder="Select Country" id="id_country_3"> LATAM</label> </li> <li><label for="id_country_2"><input type="checkbox" name="country" value="ASIA" placeholder="Select Country" id="id_country_2">ASIA</label> </li> </ul> </div> <table class="datatable" id='table_id'> <thead> <thead> <tr> <th>Region</th> <th> Area </th> <th> Country </th> </tr> </thead> <tbody> <tr id="trow"> {% for i in database%} <td>i.Region</td> <td>i.Area </td> <td>i.Country</td> </tr> </tbody> <script> // checkbox selection function filter_type(box) { //alert("checked"); var cbs = document.getElementsByTagName('input'); var all_checked_types = []; for(var i=0; i < cbs.length; i++) { if(cbs[i].type == … -
Automatic reply/confirmation emails for Django CMS form
does anyone have experience with configuring/overriding the Django CMS FormPlugin to send out automatic confirmation emails? -
Multiple images for a project in django
Am creating a web app in django where I have a model called projects which carries data of a project with an image. I have another model called ProjectImages which allows one to add multiple images to a project. I am trying to query the images related to a specific project but they are mot being rendered on the webpage. I will appreciate any help. Here are my models models.py class Projects(models.Model): title = models.CharField(max_length=100, null=True, blank=True) image = models.FileField(upload_to='media/images', null=True, blank=True) video = models.FileField(upload_to='media/videos', null=True, blank=True) description = models.TextField(null=True, blank=True) client = models.CharField(max_length=300, null=True, blank=True) completed = models.BooleanField(default=True) def __str__ (self): return self.title class Meta: verbose_name_plural = 'Projects' ordering = ('-id',) class ProjectImages(models.Model): project = models.ForeignKey(Projects, on_delete=models.CASCADE) image = models.ImageField(upload_to='media/images', blank=True, null=True) def __str__ (self): return self.project.title forms.py more_project_images = forms.FileField(required=False, widget=forms.FileInput(attrs={ 'class':'form-control', 'multiple':True })) class Meta: model = Projects fields = '__all__' views.py form = ProjectsForm() if request.method == "POST": form = ProjectsForm(request.POST, request.FILES) files = request.FILES.getlist('more_project_images') if form.is_valid(): project = form.save() for f in files: project_image = ProjectImages(project=project, image=f) project_image.save() projectdetails.html {% for project in project.projectimages_set.all %} <div class="col-md-3 p-2"> <img src="{{project.image.url}}" class="img-fluid" style="object-fit: contain;" alt=""> </div> -
Django REST framework unrecognized
I already have django rest framework installed in my project, as you see when I run pip freeze: However, when I try to import any module it does not recognize it, so it is not possible for me to go check the function or class or whatsoever I am importing. Who knows what the problem is? -
Send Event after Celery Signal call
I have a Django project and call a task named my_task and listen to different signals which are sent by the task. I am using django_eventstream inside my project to send to my eventstream. from django_eventstream import send_event when I listen for celery builtin signal after_task_publish the following way @after_task_publish.connect(sender='my_task') def task_sent_handler(sender=None, headers=None, body=None, **kwargs): print("task_sent") message = "task_sent" send_event("eventchannel", "my_event", message) the message is sent to my existing eventstream and is working as expected. print statement is printed into webserver console but when I listen to celery builtin signal task_success the following way @task_success.connect(sender=my_task) def task_success_handler(sender=None, result=None, **kwargs): print("task_success") message = "task_success" send_event("eventchannel", "my_event", message) send_event will not be sent to my eventstream print statement will print into celery worker console I am struggling to find the reason for that behavior. What is the difference between both signals or what is the difference between both functions which are triggered by the signals? Following Versions are used: Django=3.2.6 celery=5.1.2 redis=3.5.3 django-eventstream=4.2.0 -
UNIQUE constraint failed: post_author.href in django
I will create a different author table using the user table available in django and I want to combine this custom table I created with the column in the post model. Thus, I will have both the author table and the post table with the posts shared by these authors separately. And also, I will make the user models that I will create in the future with the ready user table. but I am getting the error I mentioned. How can I solve this, what are the alternative ways? from django.db import models from django.contrib.contenttypes.models import ContentType from django.db import models from django.urls import reverse from .utils import get_read_time from django.conf import settings from django.utils import timezone from markdown_deux import markdown from django.utils.text import slugify from django.contrib.auth.models import User from django.db.models.signals import pre_save from django.utils.safestring import mark_safe class GENDER(models.TextChoices): Erkek = "Erkek" Kadın = "Kadın" Diğer = "Diğer" NONE = "Belirtmek İstemiyorum" class Category_Choices(models.TextChoices): BİLİNMEYENLER = '13İlinmeyenler' KİŞİSEL_GELİŞİM = 'Kişisel Gelişim' İLHAM_AL = 'İlham Al' YATIRIM_HABERLERİ = 'Yatırım Haberleri' GİRİŞİMCİLİK = 'Girişimcilik' ENGLİSH_NEWS = 'English News' BAŞARI_HİKAYELERİ = "Başarı Hikayeleri" class Color_Choices(models.TextChoices): INDIGO = 'indigo' green = 'green' yellow = 'yellow' RED = 'red' blue = 'blue' gray = 'gray' … -
Import "rest_framework" could not be resolved "django-rest-framework"
I have installed the Django framework but it always shows a yellow line under it as if the project is not defined Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_filters', 'rest_framework', 'rest_framework.authtoken', 'rest_framework.routers', 'hauptapp', ] views.py Zb Import "rest_framework" could not be resolved When i write pip freeze find Django==3.2.7 django-environ==0.7.0 django-filter==21.1 django-import-export==2.5.0 django-mssql-backend==2.8.1 django-mssql-backend-aad==0.2.1 django-pyodbc==1.1.3 django-rest-framework==0.1.0 djangorestframework==3.12.4 djangorestframework-csv==2.1.1 -
Django REST Framework - How to compare two given values?
at my Django API application, I have a serializer that should validate a given pin but I'm always running into: TypeError: string indices must be integers def validate_old_pin(self, value): user = self.context['request'].user if value['old_pin'] != user.pin: # <- Breakpoint raise serializers.ValidationError( ({'old_pin': _("Your old PIN was entered incorrectly. Please try again.")}) ) return value Why do I get this? What is the most effective way to simply check if the two pin field match? Thanks in advance. -
I would like to disable the clickable link only for an object in Django-admin
I would like to disable the clickable link in the django admin object so that the displayed link is only as plain text without <a href ... in HTML. The current code looks like this current situation in the code here is where I would like to disable the clickable link, which would be displayed as plain text e.g. in /csvinput/3c1927f2-9ef6-45b8-a9aa-0021ef64a46f/change/.(of course I would like to keep the functionality for uploading the csv file mean /csvinput/add/) display on page of instance object /csvinput/3c1927f2-9ef6-45b8-a9aa-0021ef64a46f/change/ Many thanks for every thought or idea. -
Django admin page if statements
I'm building a webpage to present sports results but on the admin page I want it, to when a certain sport is set, the points will change to be a certain number of points like this: sports = [ ('Voléi', 'Voleibol'), ('Fut', 'Futebol'), ] team_name = models.CharField(max_length=50, blank=False, null=False, default="") sport = models.CharField(max_length=20, blank=False, null=False, choices=sports) final_score = models.IntegerField(blank=False, default=0) game_date10 = models.DateField() game_description = models.TextField(blank=True, null=True) The Sport is a list of tuples to choose and when you choose, for example, voleibol the final_score field is supposed to change to 1 or 2 points and not infinite, can I do that? -
Cannot find pg_config executable
Having no idea what pg_config is, I searched online and it seems to be part of or connected to PostgreSQL. I don't have or use that though and never have but I suspect that I may be getting this because I recently started using azure libraries in Python (I never had this problem before). Here is one of the error messages: WARNING: Discarding https://files.pythonhosted.org/packages/aa/8a/7c80e7e44fb1b4277e89bd9ca509aefdd4dd1b2c547c6f293afe9f7ffd04/psycopg2-2.9.1.tar.gz#sha256=de5303a6f1d0a7a34b9d40e4d3bef684ccc44a49bbe3eb85e3c0bffb4a131b7c (from https://pypi.org/simple/psycopg2/) (requires-python:>=3.6). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. Using cached psycopg2-2.9.tar.gz (379 kB) Preparing metadata (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'C:\Users\E\AppData\Local\Programs\Python\Python310\python.exe' -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\E\\AppData\\Local\\Temp\\pip-install-q50_w0n5\\psycopg2_b3e7f5e155154965bfc0d5340d85b1ff\\setup.py'"'"'; __file__='"'"'C:\\Users\\E\\AppData\\Local\\Temp\\pip-install-q50_w0n5\\psycopg2_b3e7f5e155154965bfc0d5340d85b1ff\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89' cwd: C:\Users\E\AppData\Local\Temp\pip-install-q50_w0n5\psycopg2_b3e7f5e155154965bfc0d5340d85b1ff\ Complete output (23 lines): running egg_info creating C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89\psycopg2.egg-info writing C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89\psycopg2.egg-info\PKG-INFO writing dependency_links to C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89\psycopg2.egg-info\dependency_links.txt writing top-level names to C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89\psycopg2.egg-info\top_level.txt writing manifest file 'C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89\psycopg2.egg-info\SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with … -
Python class variable is None despite being set
I'm struggling with thread communication in Python. I'm clearly missing something, but I'm new to Python so I don't know very well what I'm doing. When the server gets a GET request, I want it to get two numbers (x and y coords) from a separate thread, which constantly updates those values and to return those numbers as a response. I have a simple Django project with the following structure: it is very basic, made according to tutorial. When the server starts, I start a thread that looks launches my coordinate generator in a separate thread: class GpsMockCoordsServiceConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'gps_mock_coords_service' def ready(self): if os.environ.get('RUN_MAIN', None) != 'true': _thread.start_new_thread(CoordsTracker.launch_recognition, ()) CoordsTracker class looks like so: coords = None class CoordsTracker: #coords = None #tried placin it here, but same effect - it is None when retreived from views.py logger = logging.getLogger("CoordsTrackerLogger") @staticmethod def draw_contours(mask, frame, color): ...... for stuff in stuffs: ...... CoordsTracker.set_coords((x, y)) ...... @staticmethod def launch_recognition(): ........ while True: ........ CoordsTracker.draw_contours(....) ........ @staticmethod def set_coords(new_coords): global coords CoordsTracker.logger.debug("setting coords " + str(new_coords)) coords = new_coords # here coords var is OK @staticmethod def get_coords(): CoordsTracker.logger.debug(coords) # Here it is OK if I call this method … -
In Django, what is the better way to pass arguments to a create view?
I need help with two questions. Number one: I have Orders model and generic create view for it and OrderDetails model with create view. After order is created the get_absolute_url method in Orders model redirects to a page with OrderDetails creation form. I want this OrderDetails create view to get arguments from order we just created such as order.pk, now I have to fill this field manually. So, is get_absolute_url method is what I need, or should I override dispatch method in my view, but may be I need to work on get_success_url method? Number two: when I go to Order creation page, how to automatically fill Employee field? E.g. I'm logged in system as Bob Smith and when I create new order I don't want to set myself there manually, I want system do it for me. Here's models: class OrderDetails(models.Model): order = models.OneToOneField('Orders', models.DO_NOTHING, primary_key=True) product = models.ForeignKey('products.Products', models.DO_NOTHING) unit_price = models.FloatField() quantity = models.SmallIntegerField() discount = models.FloatField() class Meta: managed = False db_table = 'order_details' unique_together = (('order', 'product'),) class Orders(models.Model): customer = models.ForeignKey('contractors.Customers', models.DO_NOTHING, blank=True, null=True) employee = models.ForeignKey('employees.Employees', models.DO_NOTHING, blank=True, null=True) order_date = models.DateField(blank=True, null=True) required_date = models.DateField(blank=True, null=True) shipped_date = models.DateField(blank=True, null=True) ship_via = … -
How To set edit / delete permissions for the creator only django
How To Give User Permission To Delete Or Edit It's Post @login_required(login_url="login") def editsell(request , pk): context= {} user = request.user if not user.is_authenticated: return redirect('login') sell_listing = get_object_or_404(listingsell , id=pk) if request.POST: form = UpdateSellForm(request.POST or None , request.FILES or None , instance = sell_listing) if form.is_valid(): obj = form.save(commit = False) editsell.user == user obj.save() context['success_message'] = "Updated" sell_listing = obj form = UpdateSellForm( initial = { "title" : sell_listing.title, "subtitle" : sell_listing.subtitle, "description" : sell_listing.description, "image" : sell_listing.image, "image2" : sell_listing.image2, "image3" : sell_listing.image3, "image" : sell_listing.image, "number_phone" : sell_listing.number_phone, "ville" : sell_listing.ville, } ) context['form'] = form return render(request , 'Swapdz/add_listing.html' , context) -
AttributeError: module 'speedtest' has no attribute 'Speedtest' test_get_server is not defined
!am trying to get the download and upload speed in python by using the "speedtest" module, but it gives me that error when I use the module: AttributeError: module 'speedtest' has no attribute 'Speedtest'. and I was only declaring the variable, that is my code : import speedtest test = speedtest.Speedtest()