Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM Query Too Slow
I use this database table with more than 10000000 datas. enter image description here And use query SELECT mytable.project, COUNT(*) AS `total` FROM mytable WHERE (`mytable`.`date` >= '2022-04-05' AND NOT (`mytable`.`user` = 'sw_int')) GROUP BY `mytable`.`project` ORDER BY `total` But this takes too many time despite the use of indexes. (about 20 secs) How can I solve this problem? -
Access data from html form in Django
I have created a form in an application that goes like this : <form action="" style="max-width:500px;margin:auto"> <div class="input-container_sensor_form"> <div class="row"> <div class="col-6"> <input class="input_field_sensor_form" type="text" placeholder="Sensor name" name="sensor_name"> </div> <div class="col-6"> <span class="text-center"> <select name="sensor_form_sensor_category" class="sensor_form_sensor_category" id="sensor_form_sensor_category" class="select2-hidden-accessible" aria-hidden="true" data-select2-id="sensor_form_sensor_category"> <option></option> <option name="tree_sensor" >Tree Sensor</option> <option name="weather_sensor" >Weather Station</option> </select> </span> </div> </div> </div> <div class="row"> <div class="col-6"> <input class="input_field_sensor_form" type="text" id="latitude" placeholder="Latitude" name="latitude"> </div> <div class="col-6"> <input class="input_field_sensor_form" type="text" id="longitude" placeholder="Longitude" name="longitude"> </div> </div> </div> <br> <div id="map_sensor_form"></div> <br> <input type="hidden" id="field_id" name="field_id" value=""> <button type="submit" class="btn_sensor_form">Register</button> </form> with the following form : class AddSensor(forms.Form): sensor_name = forms.CharField(max_length=200 ) choice = forms.ChoiceField() longitude = forms.DecimalField(max_digits=22, decimal_places=16) latitude = forms.DecimalField(max_digits=22, decimal_places=16) How do i match the inputs with the form ? I've seen in the django doc that its referencing it through label but I do not have any. I want to keep the form as it is . -
Pydantic ValidationError for inheritance(nested) model
There is a structure to models with inheritance class CampaignAdditionalData(BaseModel): campaigns: List[CampaignData] stages: List[CreativeUsageStage] language_mode: ReplicationLanguageMode creative_rotation_type: CreativeRotationType class CampaignData(BaseModel): title: NonEmptyString geo_segment: NonEmptyString ac_type: ACType conversion: Conversion asset_type: GoogleCampaignAssetType date: datetime.date name: NonEmptyString budget: PositiveDecimal cpa: PositiveDecimal This is how the code calls for the processing of incoming parameters def check_campaigns_data(request: HttpRequest) -> JsonResponse: data = json.loads(request.body.decode('utf-8')) try: campaign_data = parse_obj_as(CampaignAdditionalData, data) except ValidationError as e: response = {'status': 'validation_error', 'errors': e.errors()} return JsonResponse(response) ..... .... If an exception occurs, e.g. in the geo_segment field in the CampaignData the command print(response) inside except block return { 'status': 'validation_error', 'errors': [{'loc': ('__root__', 'campaigns', 0, '__root__'), 'msg': 'No such geo segment found', 'type': 'assertion_error'}] } From this you can see that the pydantic ValidationError returns the field campaigns of the general CampaignAdditionalData model as loc value ('__root__', 'campaigns', 0, '__root__') Is there any way to get the name of the geo_segment field in the error message, i.e. go even lower in the field hierarchy? -
Should I use join query or subquery on Django ORM?
I have made a matching program. Based on the example as blew, I want a list that is a like record to user 1. The list have to exclude the users who have user 1's reaction. class Like(models.Model): from_user = models.ForeignKey(User, related_name='from_user', on_delete=models.CASCADE) to_user = models.ForeignKey(User, related_name='to_user', on_delete=models.CASCADE) [ Like ] from_user | to_user | 2 | 1 | 3 | 1 | 4 | 1 | 5 | 1 | 6 | 1 | 7 | 1 | 1 | 3 | 1 | 4 | [ Result ] from_user | to_user | 2 | 1 | 5 | 1 | 6 | 1 | 7 | 1 | 3 and 4 user have a reaction of user 1, So they are excluded. And this is the query I have made. I know this is not an efficient way. users = User.objects.filter( id__in=Subquery( Like.objects.filter(to_user=request.user.id).exclude( id__in=Subquery( Like.objects.filter( from_user=request.user.id, to_user__in=Subquery( Like.objects.filter(to_user=request.user.id).values('from_user') ) ).values('id') ) ).values('from_user') ) ) I have found FilteredRelation() function. But I don't know it fits in this case. Is there any better idea? If this query is used by many users, definitely response speed will be very slow... -
Drf: sending OTP with requests package after register
I was trying to create an Sms verification system after a user registers but I don't know how and where to put the logic and from where to call it. class RegisterSerializerBase(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField( write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('email', 'firstname', 'lastname', 'password', 'password2', 'phone',) extra_kwargs = {'password': {'write_only': True}, 'password2': {'write_only': True}, 'firstname': {'required': True}, 'lastname': {'required': True}, } def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError( {"password": "Password fields didn't match."}) return attrs def create(self, validated_data): instance = User.objects.create( email=validated_data['email'], firstname=validated_data['firstname'], lastname=validated_data['lastname'], phone=validated_data['phone'], is_active='True', type=User.TYPES.OWNER, ) instance.set_password(validated_data['password']) instance.save() return instance #creating the otp will use the PyOtp package if this doesn't work def create_otp(instance): S = 6 not_unique = True while not_unique: unique_otp = ''.join(random.choices(string.digits, k=S)) if not OTP.objects.filter(otp=unique_otp): OTP.objects.create( user=instance, otp=unique_otp, ) not_unique = False return unique_otp sending the request to the endpoint with the OTP so it can send the msg to the user via SMS def send_otp(unique_otp): url = "https://api.telda.com.et/api/write/SendOTP" payload = json.dumps({ "phone": 'number', "message": "125KHF", "iso3166Code": "et", "otp": unique_otp, "senderName": "Me", "remark": "gg", "sendDate": datetime.now }) headers = { 'accept': 'text/plain', 'Content-Type': 'application/json', 'Authorization': 'Basic MsXOTpPg2UghEQSfKjO8Tqcvu1Biz6KjNTAwMDkzNTY1NTIwMA==' … -
How to use this SQL statement in Django ORM
Please help me with converting this SQL statament in Django ORM SELECT postupci.Postupak ,SUM(unosi.Komada), unosi.Radnik" \ " FROM unosi INNER JOIN postupci ON unosi.Operacija = postupci.Id" \ " AND unosi.Datum >= 2022-11-01 AND unosi.Datum < 2022-12-10 \ " GROUP BY postupci.Postupak" -
connecting aws rds retun Is the server running on that host and accepting TCP/IP connections?
I'm trying to connect my app with aws rds postgresql database, that i hosted the app on heroku server but its throws me an error when i'm trying to run python manage.py makemigrations. THE ERROR: Is the server running on that host and accepting TCP/IP connections? i added rds.force_ssl in aws and i download it certificate and put inside my project directory, as heroku recommended that. I also added my username, password, and url endpoint in heroku setting under DATABASE_URL sections. this is my first time connecting live server for my django app. and I did not download and installed postgresql in my windows machine which i think is not the problem. DATABASE CONFIGURATION: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '5432', } } i don't know what's going on. is anyone who can help me please -
Add SQL check keyword in django model
I have a Django model with a list of choices: class MyModel(models.Model): CHANGE_TYPE_CHOICE = ( ("creation", "Création"), ("modification", "Modification") ) change_type = models.CharField( max_length=128, choices=CHANGE_TYPE_CHOICE ) Unfortunately, another app need top have access to this SQL table. I'd like to add a SQL CHECK (since using enum in django seems to be overly complex) is there a way of providing specific field db creation or do I have to do it manually on the db side? -
upload progress bar with session django -example
example source code github link Django-rest progress bar upload 0 i created a normal django model.ModelForm and it is worked perfectly until i tried to add Progress bar for files uploading -
Django change <a> tag on template depending on a condition
I have posts with the option of saving it. The view works properly but I can't see the change in the button. I want that when it is not saved by a user the button says "Save post" and when it is already saved the button should say "unsave". I'm getting problems with this last part. Here part of the code. views.py def post(request): posts = Post.objects.all().order_by("-date_created") return render(request, "post/food-feed.html", {"posts": posts}) def save_post(request, pk): post = get_object_or_404(Post, id=pk) if post.favorite_posts.filter(id=request.user.id).exists(): post.favorite_posts.remove(request.user) else: post.favorite_posts.add(request.user) return HttpResponseRedirect(request.META["HTTP_REFERER"]) template <a href="{% url 'save-post' post.id %}" class="btn btn-primary float-start">Save post</a> urls.py path("post/<int:pk>/save", views.save_post, name="save-post") What do I need to add to make the statement work? -
How to add a field to a ModelForm based on the choice in a previous field?
I have a ModelForm: class OfferModelForm(forms.ModelForm): class Meta: model = Offer fields = ['service', 'quantity'] def __init__(self, *args, hub=None, **kwargs): super(OfferModelForm, self).__init__(*args, **kwargs) self.hub = hub self.helper = FormHelper() self.helper.form_class = 'form-horizontal style-form centered' try: self.fields['service'].queryset = self.hub.get_services() except KeyError: pass # to handle I want the quantity field to be present or not according to the choice made in the service field. Do I have to resort to JS and AJAX or there is a functionality in Django I'm unaware of? Thanks in advance. -
Filter object that includes an in between month in DateField in Django
I have a model as follows: class CustomMonth(models.Model): start_date = models.DateField("Start Date") end_date = models.DateField("End Date") There are models that have start_date and end_date like this - 2020-08-31 to 2020-10-02. Now this instance includes September month in that year2020. So I want to filter out the instances that include September month meaning 9. Or if there is any instance like 2021-04-28 and 2021-06-01 then I want it to come when I query for 5th month. How can I filter it in that way? -
Issue with django manage.py runserver
I am trying to start my django testing instance inside a docker, while I was able to setup the pip installation. Somehow,I am getting this error. Any help would be appreciated. root@f54977373728:/code# python manage.py check /usr/local/lib/python2.7/site-packages/OpenSSL/_util.py:6: CryptographyDeprecationWarning: Python 2 is no longer supported by the Python core team. Support for it is now deprecated in cryptography, and will be removed in the next release. from cryptography.hazmat.bindings.openssl.binding import Binding Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/usr/local/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/code/app_usage/models.py", line 8, in <module> from profiles.models import CustomUser File "/code/profiles/models.py", line 29, in <module> from atsn.models import HOD, ProductionDepartment File "/code/atsn/models.py", line 5, in <module> from atsn.constants import PERIOD_TYPE, PROCESS_STATUS File "/code/atsn/constants.py", line 1, in <module> from model_helpers import Choices File "/usr/local/lib/python2.7/site-packages/model_helpers/__init__.py", line 1, in <module> from .upload_to_helpers import upload_to, UploadTo File "/usr/local/lib/python2.7/site-packages/model_helpers/upload_to_helpers.py", line 84 **file_info, ^ SyntaxError: invalid syntax -
Understanding working of multiple gunicorn process
I have no knowledge of what I'm trying to understand, surfing the internet brought me here. I use django-rest-framework, gunicorn, and Nginx. Suppose I have 3 workers process of gunicorn setup. and I have a very simple view that reads a value from the database, performs a different task that takes around 1 second, increments the value by 1, and saves it back to the database. class View(): value = MyModel.objects.get(id=1).integerValueField otherTask() #takes around 1 second (assume) updatedValue = value + 1 MyModel.objects.filter(id=1).update(integerValueField=updatedValue) return Will this always work? what if a different worker process of gunicorn is handling the request of concurrent users? If the database is updated by a different process in between reading the value and updating the value by some other worker process? Is this locked somehow to maintain integrity? if I can get valid links to read more about the topic, will work well for me. -
How to add profile fields in User Model in Admin area of Django and save data accordingly using Signals
I am trying to add fields of Profile Model to the admin area where we create user fortunately using the below code it shows Profile model fields in that area but once a save it shows NOT NULL constraint failed: main_profile.phone_number why phone_number fields values are not passing it to signals main.signals.py from .models import Profile from django.dispatch import receiver from django.db.models.signals import post_save from django.conf import settings @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_profile_for_new_user(sender, **kwargs): if kwargs['created']: Profile.objects.create(user=kwargs['instance']) main.models.py #code is working fine if I set phone_number fields to null class Profile(models.Model): birth_date = models.DateField(null=True) phone_number = models.IntegerField() address = models.CharField(max_length=255, null=True, blank=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) core.models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): email = models.EmailField(unique=True) admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .models import User from main.models import Profile class UserProfileInline(admin.TabularInline): model = Profile @admin.register(User) class UserAdmin(BaseUserAdmin): inlines = [UserProfileInline] add_fieldsets = ( ( None, { "classes": ("wide",), "fields": ('username', 'email', 'password1', 'password2', 'first_name', 'last_name'), }, ), ) -
Django get_next_by_date conditions not rendering properly in template
I have a model named "Manga". In this model I have manytomanyfield object called chapters with this model. class Chapter(models.Model): chapter=models.IntegerField() manga=models.ForeignKey(Manga, null=True, on_delete=models.CASCADE) images=models.ManyToManyField(Image, blank=True) date= models.DateTimeField() def __str__(self): return f"{self.manga} Chapter {self.chapter}" class Meta: ordering = ('-date',) I get Chapter in my view with def chapterview(request, manga_id, chapter_id): manga=Manga.objects.get(id=manga_id) chapter=Chapter.objects.filter(manga=manga).get(id=chapter_id) pages=chapter.images.all() And next and previous chapters with: try: nextchapter=chapter.get_next_by_date except Chapter.DoesNotExist: nextchapter=None try: prevchapter=chapter.get_previous_by_date except Chapter.DoesNotExist: prevchapter=None The problem is that these template conditions Don't work properly: {% if nextchapter and not prevchapter %}, {% elif nextchapter and prevchapter %}, {% else %} Only {% elif nextchapter and prevchapter %} works. And since this conditions are for next/previous buttons to render, I get error because next chapter does not exist but there is the button to go to that page which I click beforehand. I want to prefferably get rid of get_next_by_date method and just get the next Chapter of manytomanyfield. How can I achieve this? -
TypeError: ChangeList.__init__() missing 1 required positional argument: 'search_help_text' . when i try to edit from admin dashboard in django
i am building a ecommerece website using django and . i am getting this error when i try to edit category from admin dashboard i am using jet django dashboard [where ever i click to edit a value i get the following error ][1] i tried to use jet-dashboard and i am getting this error . Before i could edit in default admin dashboard . thanks in advance Request Method: GET Request URL: http://127.0.0.1:8000/admin/main/category/1/change/ Django Version: 4.0 Python Version: 3.10.2 Installed Applications: ['main', 'jet.dashboard', 'jet', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'paypal.standard.ipn'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', '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') Template error: In template C:\Users\blazi\Envs\Himation\lib\site-packages\jet\templates\admin\base.html, error at line 122 ChangeList.__init__() missing 1 required positional argument: 'search_help_text' 112 : 113 : {% block footer %}<div id="footer"></div>{% endblock %} 114 : 115 : {% jet_delete_confirmation_context as delete_confirmation_context %} 116 : {{ delete_confirmation_context }} 117 : 118 : {% jet_change_form_sibling_links_enabled as show_siblings %} 119 : {% if change and show_siblings %} 120 : <div class="changeform-navigation"> 121 : {% spaceless %} 122 : {% jet_previous_object as sibling %} 123 : <a{% if sibling.url %} href="{{ sibling.url }}"{% endif %} class="changeform-navigation-button segmented-button left{% if not sibling %} disabled{% endif %}" title="{{ sibling.label }}"> … -
Django filter out by country and exclude those are not in that country
i want to filter with country specifi prodcut so when user change country will see country specific product, i wrote my code this way but do not working. def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == ("products__name"): kwargs["queryset"] = models.ActiveIngredient.objects.filter(products__name__in=[request._user_country]) and models.ProductName.objects.exclude(products__name__in==None) return super().formfield_for_foreignkey(db_field, request, **kwargs) -
Django - how to make a CloudinaryField not mandatory and how to allow user to delete their uploaded image?
Hej, I am just beginning to learn Django and I want my users to be able to upload a profile picture, so I extended the User model with a Profile model, however, so far I have not figured out how to make the image upload non-mandatory. And when the user has added a picture, I would like them to be able to remove it as well. Screenshot - Not able to Submit without adding file Screenshot - Not able to remove the added file models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField() profile_image = CloudinaryField('profile_image') def __str__(self): return self.user.username forms.py class ProfileForm(ModelForm): class Meta: model = Profile fields = ('bio', 'profile_image',) views.py @login_required(login_url='login') def createPost(request): form = PostForm() if request.method == "POST": form = PostForm(request.POST, request.FILES) # request.FILES necessary so that file is submitted # also required to add enctype to the form if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('home') context = {'form': form} return render(request, 'my8gag/post_form.html', context) Couldn't find anything about this in the documentation or here on SO, so would appreciate any kind of help/hints! Thanks in advance. -
How To Make Data That Come From Django Database Appear Horizontally
enter image description here In This Image The Data Is Appear In Veticall Format But I Want Data In Horizontal Foramt {% block title %}Blog{% endblock title %} {% block body %} <div class="container"> <div class="row"> {% for post in posts%} <div class="col-lg-3"> <div class="card" style="width: 31.25rem;"> <!-- <div class="card"> --> <img class="img-fluid card-img-top" src="https://images.unsplash.com/photo-1591154669695-5f2a8d20c089?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1887&q=80" alt="Card image cap" style="height: 250px;width: 500px;"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> </div> </div> <div class="post block"> <h2 class="subtitle">{{post.title}}</h2> <small>Posted At {{post.date_added}}</small> <p>{{post.intro}}</p> <a href="{% url 'post_detail' post.slug %}">Read More</a> </div> {% endfor %} {% endblock body %} Hi There I'm Newbie In Django How Can I Able To Appear Horizontally The Data Is Come From Database -
ERROR: error de sintaxis en o cerca de «<» LINE 2: SQL state: 42601 Character: 30 [closed]
estoy realizando un procedimiento almacenado que me permita listar un registro de filas condicionadas a un rango de fechas CALL public.listar_eventos( < IN ''''2022-04-14'''' date>, < IN ''''2022-04-16'''' date> ) Porque al ejecutar este procedimiento almacenado me produce este error?? ERROR: error de sintaxis en o cerca de «<» LINE 2: < IN ''''2022-04-14'''' date>, ^ SQL state: 42601 Character: 30 Teniendo en cuenta que esta fue la creacion del procedimiento almacenado. CREATE OR REPLACE PROCEDURE listar_evento(FechaMinima date, FechaMaxima date) LANGUAGE plpgsql AS $$ BEGIN SELECT clientes_cliente.nombre, clientes_evento.cliente_id, clientes_cliente.telefono, clientes_evento.ciudad,clientes_evento.fecha_evento,clientes_evento.cantidad_personas FROM clientes_evento INNER JOIN clientes_cliente ON clientes_eventos.cliente_id = clientes_cliente.id WHERE fecha_evento BETWEEN @FechaMinima and @FechaMaxima; END; $$ -
How to make your custom django migrations reversible?
My original problem was, given a db table with 60M rows I need to convert a field type from boolean to integer field. I thought of creating a custom django migration for this (please do let me know if you have a better approach than this) which looks like this- def make_changes(apps, schema_editor): vcs_model = apps.get_model('iot_app', 'AbstractVCSCompartmentData') vcs_model.objects.select_related('vcsdata').all().update(charging_status_v2=F('charging_status')) vcs_model.objects.select_related('vcsdata').all().update(charging_status_backup=F('charging_status')) # backup class Migration(migrations.Migration): dependencies = [ ('iot_app', '0030_auto_20220225_1027.py'), ] operations = [ migrations.AddField( # backup field model_name='AbstractVCSCompartmentData', name='charging_status_backup', field=models.PositiveIntegerField(blank=True, null=True), ), migrations.AddField( model_name='AbstractVCSCompartmentData', name='charging_status_v2', field=models.PositiveIntegerField(blank=True, null=True), ), migrations.RunPython(make_changes), migrations.RemoveField( model_name='AbstractVCSCompartmentData', name='charging_status', ), migrations.RenameField( model_name='AbstractVCSCompartmentData', old_name='charging_status_v2', new_name='charging_status', ), ] I want to unroll all the changes i.e., making my custom migration reversible. I have gone through RunPython doc. But I am confused as in how can i perform addition of a new field in my reverse_code() function. The idea of creating a backup field is to reinstate the db to its previous state. -
Django: AttributeError at /course/u/update-item/ 'WSGIRequest' object has no attribute 'data' using django
I get this error when i try accessing localhost:8000/course/u/update-item/: "AttributeError at /update_item/ 'WSGIRequest' object has no attribute 'data'" NOTE: When i change request.data to request.body i get another error message that says JSONDecodeError at /course/u/update-item/ Expecting value: line 1 column 1 (char 0) views.py def update_item(request): data = json.loads(request.data) productId = data['productId'] action = data['action'] print("Action:", action) print("ProductId:", productId) return JsonResponse("Item was added", safe=False) cart.js function updateUserOrder(productId, action){ console.log('User is authenticated, sending data...') var url = '/u/update-item/' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) => { return response.json(); }) .then((data) => { location.reload() }); } urls.py path('u/update-item/', views.update_item, name="update-item"), -
How to update a model with ManytoMany / ForeignKey in Django
I have a model Study containing many Targets (ManyToManyField) Each Target contains a Location (ForeignKey): class Study(models.Model): uid = models.AutoField(primary_key=True) targets = models.ManyToManyField(Target) class Target(models.Model): uid = models.AutoField(primary_key=True) location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True, blank=True ) class Localization(models.Model): x = models.FloatField(blank=True) in my view I want to update the Location that is in a specified Study -> Target def update_locations(request): data = json.loads(request.body.decode('utf-8')) if request.method == 'POST': study_to_update = Study.objects.get(uid = data["study"]) targets = study_to_update.targets.all() target_to_update = [target for target in targets if target.uid == data["target"]][0] new_location = Location(x = data["location"]) #target_to_update.remove(?) #target_to_update.add(new_location) study_to_update.save() else: return HttpResponseForbidden('Erreur dans la requéte') I don't know if this is right or not -
How to form a socket url in django channels?
How to form a socket url in django channels? I am able to use sockets in my templates, but I want to test it with postman. The URL router in routing.py consists of path('chat/<room_id>/', ChatConsumer.as_asgi()), I am accessing this URLws://127.0.0.1:8000/public_chat/1 in postman, but it says Access denied. Also, which address(127.0.0.1:8000) should I use? The one for Django Application or the redis one used for messages ?