Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can seeimage locally in django It's not visible in the deployment environment. What should I do?
enter image description here In the development environment, there's no problem It's being uploaded. However, if you upload it to the server, you can write a post it. I can't see the picture. nginx.conf worker_processes auto; events { } http { client_max_body_size 100M; keepalive_timeout 3000; server { listen 80; client_body_buffer_size 256k; include mime.types; location /static/ { alias /data/static/; } location /media/ { alias /data/media/; } client_max_body_size 100M; location / { proxy_pass http://django_container_gunicorn:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; } } } What should I do? -
Format warning in unit test as a import of customized app comes after loading settings
In a Django project's unit test, we need to configure the settings to direct to ourapp by INSTALLED_APPS and to prevent the below run-time error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. The line of from ourapp.rest.views import retrieve_timerange gets a formatting warning saying PEP 8: E402 module level import not at top of file. However, the import line depends on the INSTALLED_APPS of the settings, so it must come after the configuration action above. I wonder if there is an elegant way to resolve this formatting issue. Sample source code of the unit test: import os import django from django.conf import settings import unittest from unittest import TestCase os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ourproject.settings") django.setup() from ourapp.rest.views import retrieve_timerange class TestViews(TestCase): def setUp(self): ... def __run_get_test(self): ... -
django: m2m field may not be empty
Students can be assigned to many groups. One student can be assigned to many groups One Group can hold many students. With code below I can create Student with no group or assigned to some groups. I can change everything with success, exept... Exept that I can not remove all groups assigned to student. I assume that some student can unsubscribe from all groups. But django don't like that and throw error: {'groups': [ErrorDetail(string='This list may not be empty.', code='empty')]} Code: Models: class Group(models.Model): group_name = models.CharField(max_length=30, unique=True, null=True, blank=True) class Student(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) groups = models.ManyToManyField(Group) Create Student: new_student = Student.objects.create( first_name = request.data["first_name"], last_name = request.data["last_name"], ) groups_id = request.data["group_id"] if(groups_id): for group_id in groups_id: new_student.groups.add(group_id) Change Student: def change_student(request, id): student_to_change = Student.objects.get(id=id) serializer = StudentSerializer( instance=student_to_change, data={ 'first_name': request.data["first_name"], 'last_name': request.data["last_name"], 'groups': request.data["groups"], } ) if serializer.is_valid(): serializer.save() And when I try to execute change_student with for example: request.data : {'id': 16, 'first_name': 'John', 'last_name': 'Smith', 'groups': []} I get {'groups': [ErrorDetail(string='This list may not be empty.', code='empty')]} error And serializers: class GroupSerializer(ModelSerializer): class Meta: model = Group fields = '__all__' class StudentSerializer(ModelSerializer): class Meta: model = Student fields = '__all__' -
Django-tables2: How to ensure consistent ordering when sorting?
When sorting the table by clicking on a header, if there are rows that have the same value, the order can not be consistent from one query to another. Is there a way to specify a "secondary" sorting criteria? For example, when user clicks on the price header to sort rows by price, behind the scene I'd like to have ordering = (price, pk) sothat the result is guarantee to be the same, given the same queryset. For now, I succeeded with price = tables.Column(order_by=["price", "id"]). However, doing this for every column is tedious, there must be a better way. Thanks. -
Re-usability of code between django and django rest framework
I have been assigned a project which has two versions of it: older one is written in django and new one written in django rest framework. I am quite new to both django and drf. While going through both codebase, I came across following code in one of the views.py in new drf version: def get_xyz(request): # some business logic return HttpResponse(json.dumps({ ... }) , content_type="application/json" , status=status.HTTP_200_OK) Then in older version of the app, I found function with exactly same above structure in its views.py. This created following confusions in me: Can we use function based views (as above) written in (non-drf) django app as it is in drf based app? Can we use class based views (as shown below) from non-drf django app as it is in the drf based app? class AbcClass(View): def get(self, request): # business logic return HttpResponse(json.dumps({ ... }) , content_type="application/json" , status=status.HTTP_200_OK) def post(self, request): # business logic return HttpResponse("success", status.HTTP_200_OK) Does all django framework (non-rest) classes (like View above) work perfectly in drf? Can we make frontend app written in react (or angular) send requests and receive responses from old django app (similar to how frontend apps built with these UI frameworks … -
Why can't I filter the data by one known in django&
I have a painted filter in view.py which works wonderfully. When I use a common abbreviation in html code, like {{form.as_p}} or {{form|crispy}}, then I can find the data I need, according to one known one. In my case, this is by course, by semester, by type of subject, by institute, and so on, and when I start writing my html code, in order for the search to give the correct answer, all fields must be filled in, although in forms and models I determined that all fields are not required, it turns out that an error in the html code, but I do not know where( veiws.py: def buy_files(request): bdfiles = FeedFile.objects.all() # bdfiles = UploadFile.objects.all() form = FileFilterForm(request.GET) if form.is_valid(): if form.cleaned_data["number_course"]: bdfiles = bdfiles.filter(feed__number_course = form.cleaned_data["number_course"]) if form.cleaned_data["number_semestr"]: bdfiles = bdfiles.filter(feed__number_semestr = form.cleaned_data["number_semestr"]) if form.cleaned_data["subjectt"]: bdfiles = bdfiles.filter(feed__subjectt = form.cleaned_data["subjectt"]) if form.cleaned_data["type_materials"]: bdfiles = bdfiles.filter(feed__type_materials = form.cleaned_data["type_materials"]) if form.cleaned_data["institute"]: bdfiles = bdfiles.filter(feed__institute = form.cleaned_data["institute"]) return render(request, 'chat/files/buyfile.html', {'bdfiles': bdfiles, 'form':form}) html code: <div style="float: right; margin-bottom: 10%; margin-top: 10%;" class="form-group row" data-aos="fade-up"> <form action="" method="get" style="width:90%"> {% csrf_token %} <!-- {{form|crispy}}--> <p><label class="form-label">Курс: </label> {{ form.number_course }}</p> <div class="form-error">{{ form.number_course.errors }}</div> <p><label class="form-label">Семестр: </label> {{ form.number_semestr }}</p> … -
Reverse for 'update' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['update/(?P<id>[0-9]+)/\\Z']
I am trying to update my ActiveMember model which has a OneToOneField with Members. I am running into this error. Reverse for 'update' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['update/(?P[0-9]+)/\Z'] I am new to django and not sure how to solve it. forms.py from dataclasses import fields from random import choices from socket import fromshare from django import forms from django.forms import ModelForm, DateField, widgets from .models import Member, ActiveMember from datetime import datetime, timedelta class MemberForm(ModelForm): class Meta: model = Member fields = ( 'full_name', 'email', 'phone', 'image', 'date_created', ) def __init__(self, *args, **kwargs): super(MemberForm, self).__init__(*args, **kwargs) self.fields['image'].required = False self.fields['email'].required = False self.fields['date_created'].disabled = True class ActiveMemberForm(ModelForm): class Meta: model = ActiveMember fields = ( 'member', 'start_date', 'end_date', 'status', ) widgets = { 'start_date': widgets.DateInput(attrs={'type': 'date'}), 'end_date': widgets.DateInput(attrs={'type': 'date'}), } models.py from django.db.models.signals import pre_save from django.dispatch import receiver import os from django.db import models from django.utils import timezone from datetime import datetime, timedelta from django.utils.text import slugify from .helper import upload_to_image_post # Create your models here. def default_start_time(): #now = datetime.now() now = timezone.now() start = now.replace(hour=23, minute=59, second=0, microsecond=0) return start if start > now else start + timedelta(days=1) class Something(models.Model): timestamp … -
Authorization header is not sending when using Swagger documentation on drf-spectacular
I'm using drf-spectacular to document and test my endpoint. My code look like this: @extend_schema( parameters=[ OpenApiParameter(name='Authorization', description='Authorization token', required=True, type=str, location=OpenApiParameter.HEADER), OpenApiParameter(name='my-key1', description='My key 1 info', required=True, type=str, location=OpenApiParameter.HEADER), OpenApiParameter(name='my-key2', description='My key 2 info', required=True, type=str, location=OpenApiParameter.HEADER), ], description='Info about the endpoint', responses={ 200: inline_serializer( name='Successfull response', fields={ "result_code": serializers.IntegerField(default=200), "result_description": serializers.CharField(default="Transaccion Exitosa"), "data": DocumentSerializer(many=True), } ), }, ) @api_view(["GET"]) def my_endpoint_function(request): pass As you can see I'm declaring 3 headers parameters, Authorization, my-key1 and my-key2. But when I try to use the Swagger documentation only my-key1 and my-key2 are sending. Here's an example: As you can see in the Swagger documentation I'm sending the three headers I mentioned above, but in the curl only two of them are sending. Does anyone know how to fix this? I need to test my endpoints in the documentation. Thank you for your time. -
Django REST framework: error in HTML form in browsable API
I have this model: class WeaponClass(models.Model): """Table with all possible weapon classes.""" label = models.CharField(max_length=32) acronym = models.CharField(max_length=8) class Meta: ordering = ['id'] verbose_name_plural = 'weapon classes' def __str__(self): return f"{self.label}, {self.acronym}" with this serializer: class WeaponClassSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="weapon_classes-detail") class Meta: model = WeaponClass fields = ['url', 'label', 'acronym'] Now, I have player, that has weapon class: class PlayerSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="players-detail") user = UserSerializer() weapon_class = WeaponClassSerializer() class Meta: model = Player fields = ['url', 'user', 'weapon_class'] When I display player, everything is working perfectly how I want it, except for one thing. When I view browsable API from django rest framework, Weapon Class name in HTML form is outputting <BoundField value=Medium Bruiser errors=None>. It should output 'Weapon Class', just like the part with 'User'. When I open Weapon Class, title on that page is normal, it says 'Weapon Class Instance', same as 'Player Instance' in pictures below. Its not affecting anything, but I'm really wondering why is it doing this: I circled the problem. -
Django matching query does not exist after creating superuser account
i'm working on someone code, after migration i create superuser account but EC_Admins matching query does not exist after login. here is my views @login_required(login_url='home') @staff_member_required(login_url='home') def adminhome(request): adminhome.username = request.session['admin_id'] a = EC_Admins.objects.get(ecadmin_id=adminhome.username) adminhome.adminimage = a.ecadmin_image return render(request,'admin/adminhome.html',{'username':adminhome.username,'image':adminhome.adminimage}) and log file File "C:\Users\user\Digital_Voting\EC_Admin\views.py", line 23, in adminhome a = EC_Admins.objects.get(ecadmin_id=adminhome.username) -
Import Error When Running Django From Windows
Trying to run Django (version 2.1) from Window’s Python 3.10.6. I received an Import Error from manage.py: 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?" Have tried multiple things, with no luck: Installed Django on virtualenv through pip: PS C:\Users\nickg\vidly6> newenv\Scripts\activate (newenv) PS C:\Users\nickg\vidly6> newenv install django==2.1 (newenv) PS C:\Users\nickg\vidly6> django-admin startproject vidly6 . (newenv) PS C:\Users\nickg\vidly6> pip install virtualenv PS C:\Users\nickg\vidly9> code . Installed Django on pipenv: PS C:\Users\nickg\vidly6> pipenv install django==2.1 PS C:\Users\nickg\vidly6> pipenv shell Used instructions from Django’s site (created vidly9 file here so I could apply it to a different file): PS C:\Users\nickg\vidly9> vidly9-env\Scripts\activate.bat PS C:\Users\nickg\vidly9> python -m pip install django==2.1 PS C:\Users\nickg\vidly9> pipenv shell PS C:\Users\nickg\vidly9> django-admin startproject vidly9 . PS C:\Users\nickg\vidly9> code . Yesterday, when going through Django’s steps, I received a warning that the script was in the directory, but not in path: C:\Users\nickg\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\Scripts So I went to System Properties -> Environmental Variables -> User Variables. It was there that in the “Path” variable, and added it as a value. Didn't work either. -
Django: how to configure Apache to serve Django apps with mod_wsgi
I tried to set up a Django app with Apache and mod_wsgi, but ran into a problem that I have no ideas where is the cause. The app works fine with the command "python manage.py runserver", but when I tried to run it with Apache, I got the following errors in the Apache error log file. Current thread 0x00007fb4880ad940 (most recent call first): <no Python frame> Python path configuration: PYTHONHOME = '/data/anaconda3/envs/partsdb' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/data/anaconda3/envs/partsdb' sys.base_exec_prefix = '/data/anaconda3/envs/partsdb' sys.platlibdir = 'lib64' sys.executable = '/usr/bin/python3' sys.prefix = '/data/anaconda3/envs/partsdb' sys.exec_prefix = '/data/anaconda3/envs/partsdb' sys.path = [ '/data/anaconda3/envs/partsdb/lib64/python38.zip', '/data/anaconda3/envs/partsdb/lib64/python3.8', '/data/anaconda3/envs/partsdb/lib64/python3.8/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' I have the following lines in an Apache conf file. WSGIPythonHome /data/anaconda3/envs/partsdb WSGIPythonPath /data/partsdb/partsdb WSGIScriptAlias / /data/partsdb/partsdb/wsgi.py <Directory "/data/partsdb/partsdb"> <Files wsgi.py> Require all granted </Files> </Directory> I also replaced the following two lines in the Apache conf file WSGIPythonHome /data/anaconda3/envs/partsdb WSGIPythonPath /data/partsdb/partsdb with the following two lines, but got the same errors. WSGIDaemonProcess partsdb … -
Django Form - Validator caused TypeError
I try to make validator for date and time via regex for data coming from Django Form. I can not figure out why I get 'type" is not iterable when I add validator o another field. views.py: def saveGate(request): if request.method == 'POST': form = NewGateForm(request.POST) # check whether it's valid: if form.is_valid(): g = Gate() g.save() gv = GateVersion() gv.gateInternalId = g gv.version = form.cleaned_data['version'] gv.state = form.cleaned_data['state'] gv.toBeReleased = form.cleaned_data['toBeReleased'] ga = GateAtributes() ga.gateInternalId = g ga.name = form.cleaned_data['nameOfGate'] ga.description = form.cleaned_data['description'] ga.gateExpression = form.cleaned_data['gateExpression'] ga.type = form.cleaned_data['type'] ga.save() gv.save() return HttpResponseRedirect('done/') else: return HttpResponse(ValidationError) else: raise Http404("Unexpected HTTP method.") url.py urlpatterns = [ path('', views.gates, name='gates'), path('detail/<str:gateInternalId>/', views.gateDetail, name='detail'), path('new/', views.newGate, name='new'), path('new/save', views.saveGate, name='save'), path('edit/', views.editGate, name='edit'), path('new/done/', views.done, name='done'), path('new/version/<str:gateInternalId>/', views.newVersion, name="newVersion"), path('new/version/saveVersion', views.saveVersion, name='saveVersion'), path('api/gates', views.apiGates) ] models.py class GateAtributes(models.Model): gateInternalId = models.ForeignKey(Gate, on_delete=models.CASCADE) atributesInternalId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=500, blank=True) description = models.CharField(max_length=5000, blank=True) gateExpression = models.CharField(max_length=150, unique=True, null=False) SHORT_TERM = 'ST' LONG_TERM = 'LT' GATE_TYPE_ENUM = [ (SHORT_TERM, 'Short-term'), (LONG_TERM, 'Long-term'), ] type = models.CharField(max_length=2, choices=GATE_TYPE_ENUM, default=SHORT_TERM) def __str__(self): return self.name def __iter__(self): return [ self.gateInternalId, self.atributesInternalId, self.name, self.description, self.gateExpression, self.type ] forms.py class NewGateForm(forms.Form): nameOfGate = forms.CharField(max_length=500, widget=forms.TextInput(attrs={'class': 'form-control … -
Generate a custom response for an API endpoint in Django Rest Framework using drf-spectacular
I'm trying to generate the documentation for an function based view in DRF using the drf-spectacular library. The response that I'm trying to generate should look like this: As you can see "data" is a list. I tried to do the following: class DocumentSerializer(serializers.Serializer): date = serializers.IntegerField(default=123) total_documents = serializers.IntegerField(default=1890) @extend_schema( parameters=[ OpenApiParameter(name='authorization', description='Authorization token', required=True, type=str, location=OpenApiParameter.HEADER), ], description='Info about the endpoint', responses={ 200: inline_serializer( name='Successfull response', fields={ "result_code": serializers.IntegerField(default=200), "result_description": serializers.CharField(default="Transaccion Exitosa"), "data": DocumentSerializer(), } ), }, ) @api_view(["GET"]) def my_endpoint_function(request): pass As you can see "data" should be a list of DocumentSerializer, but I don't know how to achieve that. The result I'm obtaining with the code above is the following: Because I don't know how to make that data has a list of DocumentSerializer. It will be great if you can help me, I've searching in the documentation but at this point I'm stuck. -
Fechas con Django
Tengo un formulario donde registro la fecha en que creo el formulario y me pide la fecha de cierra para editar, pero cuando creo el formulario me pide que le diligencia la fecha de cierre. ¿Como puedo hacer para que cuando envié el formulario del template me reciba el espacio en blanco y no me genere error. Estas son las dos fechas del modelo, el campo fecha, se diligencia al momento de crear el formulario, pero la fecha de cierre no sabemos cuando se va cerrar, pero enotnces si no coloco una fecha me sale un error. fecha = models.DateField(null=True) fecha_cierre = models.DateField(null=True, blank=True) Es posible que el campo sea vacío? -
Queryset from non-related model in __init__ modelform method
I have two model classes. They are not related models (no relationship). # models.py class Model1(models.Model): description = models.TextField() option = models.CharField(max_length=64, blank=False) def __str__(self): return self.option class Model2(models.Model): name = models.CharField(max_length=64, blank=False) def __str__(self): return self.name I have respective form from where I am submitting and saving data in my table. I want to use my Model2 data to fill-in 'option' field as select field, so I am introducing below init method. # forms.py class Model1Form(forms.ModelForm): def __init__(self, *args, **kwargs): all_options = Model2.objects.all() super(Model1Form, self).__init__(*args, **kwargs) self.fields['option'].queryset = all_options class Meta: model = Model1 fields = ('description', 'option') It does not render the dropdown on my template, so I am wondering whether it is right way to address the issue (acknowledging that models are not related to each other). -
How can I redirect to a page depend on different user group correctly by django?
I am creating a feature to let the banned user (user without any group) go to a specific page banned_alert when they click the "post", because they are not allowed to do so. But then when I test this feature, the Chrome shows This page isn’t working | the IP redirected you too many times. Can somebody tell me how to do it correctly? Did I miss any configuration? Below is my code snippets. Thank you for your time! base.html: (has_group function already works correctly somewhere else) {% load get_group %} {% if request.user|has_group:"mod" or request.user|has_group:"default" or user.is_staff %} <a class="nav-link" href="/create-post">Post</a> {% else %} <a class="nav-link" href="/banned_alert">Post</a> {% endif %} banned_alert.html: {% extends 'main/base.html' %} {% block title %}Your account has been banned by Admin{% endblock %} {% load crispy_forms_tags %} {% block content %} <h2>Please contact the Admin!</h2> {% endblock %} view.py def banned_alert(request): if request.method == 'GET': return redirect('/banned_alert') urls.py urlpatterns = [ path('', views.home, name='home'), path('home', views.home, name='home'), path('sign-up', views.sign_up, name='sign_up'), path('create-post', views.create_post, name='create_post'), path('banned_alert', views.banned_alert, name='banned_alert'), ] -
Form is getting wrong instance
I have a view where I list a bunch of child objects belonging to the parent object. Each child's object has a form in the template where they can update their feeling. However, the instance of the form is not showing the correct value. The view looks like this right now: def child_page(request, pk=None): parent = Parent.objects.get(pk=pk) children = Children.objects.filter(parent=parent, user=request.user) form = ChildForm(request.POST or None) if request.POST: child_id = request.POST.get('child_id', None) child_feeling = request.POST.get('feeling') child.feeling = child_feeling child.save() return redirect('index') context = { 'children': children, 'form': form } return render(request, 'test.html', context) I tried to for loop through the child objects and giving the instance like this: for x in children: print(x) form = ChildForm(request.POST or None, instance=x) Which did neither work. The output of the print is all the existing objects. I can't understand why this is happening. With this method, the last elements instance is being showed in all elements instance. How should I get the instance of a single child object and pass it in as the instance, so that each form shows the instance belonging to the child object that is trying to be updated? -
starting a django project
Im brand new to django and am wondering if i could get some help, Im working my way through the guide on the django website and have got to the point of starting a new project with ...\> django-admin startproject mysite after running this command in the terminal I get back an error saying django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + django-admin + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoun dException + FullyQualifiedErrorId : CommandNotFoundException Im not a huge fan of the windows terminal and try my best to understand the errors it throws at me but cant. could someone help me out with this please. -
Recursive sql query for django M2M
I need help writing a recursive sql command that will be used as a function (get_children) when a M2M is used. models.py class ConditionGroup(models.Model): name = models.CharField(max_length=100, unique=True) child_groups = models.ManyToManyField( "self", related_name="parent_groups", blank=True, symmetrical=False ) def get_children(): query = """ WITH RECURSIVE parents AS ( SELECT data_collector_conditiongroup.*, 0 AS relative_depth FROM data_collector_conditiongroup WHERE id = %s <<HELP>> ) ORDER BY relative_depth; """ return self.Meta.model.objects.raw(query, [self.id]) Then add the following data: _unrelated_sub_group = ConditionGroup.objects.create(name="unrelated_sub") _unrelated_group = ConditionGroup.objects.create(name="unrelated") _unrelated_group.child_groups.add(_unrelated_sub_group) sub_group_a_1 = ConditionGroup.objects.create(name="sub_group_a1") group_a1=ConditionGroup.objects.create(name="group_a1") group_a1.child_groups.add(sub_group_a_1) group_a=ConditionGroup.objects.create(name="group_a") group_a.child_groups.add(group_a1) sub_group_b = ConditionGroup.objects.create(name="sub_group_b") group_b = ConditionGroup.objects.create(name="group_b") group_b.child_groups.add(sub_group_b) group=ConditionGroup.objects.create(name="group_a") group.child_groups.add(group_a) group.child_groups(group_b) This can be looked at as unrelated unrelated_sub group group_a group_a1 group_b What I need is a recursive sql function in Django such that when I query for the id of "group" it results in a queryset containing group, group_a, group_a1, group_b -
Django REST Framework | many-to-many relation returning "detail: not found"
I'm using Django REST framework. I've created a model for items in an inventory system and also a through table (named subassembly) for many-to-many relationship between items themselves, so an item can be a subpart of other items and vice versa. I'm just not sure I've done it right and I can't seem to get any results. When I visit the backend at a URL such as http://localhost:8000/api/subassemblies/2/, the response is {"detail": "Not found."} but I'm hoping to see all of an item's subparts, or "children". PUT or any other type of request has the same outcome. If it matters, when accessing the subassemblies from the admin page, I can create relationships between items just fine. But only one at a time though. And I need to be able to edit all of an item's subparts in one go (at least, frontend-wise). Currently, the request body is structured like so: { "parent_id": 2, "children": [ { "child_id": 5, "qty": 2 }, { "child_id": 4, "qty": 3 }, ] } This also allows me to use .set() on a particular items children which is useful because I think it also removes any prior children that are not included in the new … -
Run middleware for specific links
do I'm trying to write the code for a social media website. I need every use link to be checked, for e.g. if the user has no followers, turn the number to 0, and if it has no followings, turn it back to 0. it works fine for certain users, but creates issues with some other ones, I will put my code below. *UserFollowing is a model which determines who follows who. models: `class UserFollowing(models.Model): user = models.ForeignKey(User, related_name="following",on_delete=models.CASCADE) following_user= models.ForeignKey(User, related_name="followers",on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True)` URLS: from django.urls import path from . import views from.views import CreatePost urlpatterns = [ path('explore/', views.Listexplore.as_view(), name='page-explore'), path('user/<str:username>/', views.UserList.as_view(), name='user-posts'), path('post/<int:pk>/', views.DetailPost.as_view(), name='post-detail'), path('post/<int:pk>/update/', views.UpdatePost.as_view(), name='post-update'), path('post/<int:pk>/delete/', views.DeletePost.as_view(), name='post-delete'), path('post/create/', CreatePost.as_view(), name='post-create'), path('about/',views.about,name='page-about'), path('home/',views.Listhome.as_view(),name='page-home'), path('tests/',views.test,name="page-test"), ] view: def post(self, request,**kwargs): user2 = get_object_or_404(User, username=self.kwargs.get("username")) try: UserFollowing.objects.get(following_user=user2, user=request.user) created = UserFollowing.objects.get(following_user=user2, user=request.user) created.delete() request.user.profile.follower -= 1 user2.profile.following -= 1 request.user.save() user2.save() except UserFollowing.DoesNotExist : created = UserFollowing.objects.create(following_user=user2, user=request.user) request.user.profile.follower += 1 user2.profile.following += 1 created.save() request.user.save() user2.save() return redirect(request.META['HTTP_REFERER']) def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get("username")) return post.objects.filter(author=user).order_by("-time") def get_context_data(self, **kwargs): context = super(UserList, self).get_context_data(**kwargs) context['user2'] = get_object_or_404(User, username=self.kwargs.get("username")) my_user= User.objects.get(username=self.request.user.username) try: UserFollowing.objects.get(following_user=context['user2'], user=my_user) follow=True except UserFollowing.DoesNotExist : follow=False context['follow']=follow return context the middleware i wrote: … -
How do i create a direct message in django channels
I have watched a couple of tutorials on Django channels but i can't figure out how to create a direct message in my website. Every tutorial's always creating a room and then adding multiple users. I want to build a message system whereby users can message other users i.e only 2 participant. Like a p2p message -
How to correctly configure Gmail to send E-mail with Django. The official configuration does not work for me
I am preparing an online portfolio made with Django and one of the features is a form with which you can contact me via E-mail. To verify that this functionality worked correctly, I have been testing it with MailTrap and it works perfectly, now for the production version I want the E-mails to reach my Gmail mail, but despite the fact that in theory I have followed all the steps, no I get it to work, it only worked for me with MailTrap. In my Gmail account I already activated two-step verification and created a specific password for the application. The lower security option apparently does not exist since May of this year. This is the configuration of my Settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = "my-e-mail@gmail.com" EMAIL_HOST_PASSWORD = 'smbumqjiurmqrywn' EMAIL_PORT = 587 EMAIL_USE_TLS = True This password is just an example, it is just to show how it is set. And this is the method to send the E-mail. I am using EmailMessage but with send_mail the result is the same: def contact(request): contact_form = ContactForm() if request.method == 'POST': contact_form = ContactForm(data = request.POST) if contact_form.is_valid(): name = request.POST.get('name', '') email = request.POST.get('email', '') content = … -
Unexpected Keyword Argument in Django forms
The error that I am getting is: TypeError at /newapplicantregisteration/ newapplicantregisteration() got an unexpected keyword argument 'applicantname' I a m trying to create a form and pass input data to the backend. What can I do