Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django post with curl , the form data always get "None"
I'm using django 3.2 view.py # Create your views here. from django.shortcuts import render from django.views.generic import View from django.http import HttpResponse class TestView(View): def post(self, request): print(request.POST.get("value")) return HttpResponse("ok") in urls.py from django.urls.conf import path from .views import TestView from django.views.decorators.csrf import csrf_exempt urlpatterns = [ path("", csrf_exempt(TestView.as_view())), ] in another terminal run curl -X POST -d '{"value "user"}' http://<ip>:5000/ request.POST.get("value") always return None -
how to give an error that the record cannot be deleted because it has a connection with the database using try/except
I am new to python and there is problem, I need the system should display a message that it is impossible to delete the record, since it has connections in the database. my code: @permission_required ('orauth.group_delete', raise_exception = True) def group_delete (request, pk): group = get_object_or_404 (Group, pk = pk) if request.method == 'POST': group.delete () return redirect ('orauth: group_list') return render ( request, 'common / confirm_delete.html', { 'title': _ ('Deleting a role'), 'object': group, }, ) -
JavaScript "Uncaught DOMException: Failed to execute 'insertBefore' on 'Node'
can anyone help me with this message error, please? "Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node. at HTMLButtonElement." I don't know javascript, but I need this code in my Django(a python framework) app to create a dynamic form. I pick up this code in this tutorial https://engineertodeveloper.com/dynamic-formsets-with-django/ . My template is almost identical to tutorial's template. The difference between then is that my formset have three fields to fill and the tutorial's formset(not the main form) has one field. JavaScript code by https://engineertodeveloper.com/dynamic-formsets-with-django/ : const imageForm = document.getElementsByClassName("image-form"); const mainForm = document.querySelector("#pet_form"); const addImageFormBtn = document.querySelector("#add-image-form"); const submitFormBtn = document.querySelector('[type="submit"]'); const totalForms = document.querySelector("#id_form-TOTAL_FORMS"); let formCount = imageForm.length - 1; function updateForms() { let count = 0; for (let form of imageForm) { const formRegex = RegExp(`form-(\\d){1}-`, 'g'); form.innerHTML = form.innerHTML.replace(formRegex, `form-${count++}-`) } } addImageFormBtn.addEventListener("click", function (event) { event.preventDefault(); const newImageForm = imageForm[0].cloneNode(true); const formRegex = RegExp(`form-(\\d){1}-`, 'g'); formCount++; newImageForm.innerHTML = newImageForm.innerHTML.replace(formRegex, `form-${formCount}-`); mainForm.insertBefore(newImageForm, submitFormBtn); totalForms.setAttribute('value', `${formCount + 1}`); }); mainForm.addEventListener("click", function (event) { if (event.target.classList.contains("delete-image-form")) { event.preventDefault(); event.target.parentElement.remove(); formCount--; updateForms(); totalForms.setAttribute('value', `${formCount + 1}`); } }); My Django template: <div … -
Why does Django auto_now_add fail with not null on insert or update
I am trying to implement a data warehouse. So the django system will query an api at regular intervals to update the database. I am using client ids as the primary key which might be the problem but when I do save I obviously want it to create or update. I get this error whatever I do! django.db.utils.IntegrityError: null value in column "created" violates not-null constraint So originally I just had my model like this: class PersonalTaxClient(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) invoice_client = models.ForeignKey(InvoiceClient, blank=True, null=True, on_delete=models.PROTECT) client_name = models.CharField(max_length=100) email = models.CharField(max_length=100) Then I tried: class PersonalTaxClient(models.Model): created = models.DateTimeField(editable=False) updated = models.DateTimeField() client_code = models.CharField(max_length=20, primary_key=True) invoice_client = models.ForeignKey(InvoiceClient, blank=True, null=True, on_delete=models.PROTECT) client_name = models.CharField(max_length=100) email = models.CharField(max_length=100) # history = HistoricalRecords() def save(self, *args, **kwargs): ''' On save, update timestamps ''' print(timezone.now()) if not self.client_code: self.created = timezone.now() self.modified = timezone.now() return super(PersonalTaxClient, self).save(*args, **kwargs) and try to update like this: >>> from sbsite.models import PersonalTaxClient >>> p = PersonalTaxClient(client_code="HHH001", client_name="Bob") >>> p.save() I get the same error. I've read about 20 other SO pages but am none the wiser..............! -
Django child models don't inherit Meta inner class
I have two Django 3.0 models, one of which is a subclass of the other: # models.py class BaseCategory(models.Model): class Meta: verbose_name_plural = "categories" class Category(BaseCategory): # fields 'n' stuff Only the Category model is registered in the Admin # admin.py @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): # stuff here In the Admin, the Category model is labeled "Categorys", despite the fact that it should have inherited the Meta inner class and its verbose_name_plural attribute from BaseCategory. In fact, if I copy the same code into the Category model, # models.py class Category(BaseCategory): class Meta: verbose_name_plural = "categories" # fields 'n' stuff the model is correctly labeled "Categories" in the Admin. This indicates that the Category class is not inheriting the Meta inner class of BaseCategory. Why does a child class not inherit the Meta inner class? Is there another way for me to only specify verbose_name_plural once instead of copying the exact same code into every child of BaseCategory? -
django-mssql-backend - Invalid connection string attribute (0)
OK, I'm slowly going crazy. I want to connect Django 3 to MSSQLv15 Server. Connection works if I use Trustedconnection=yes (using win credentials), it also works on Ubuntu if I'm using FreeTDS v7.4 but it won't work in Windows if I want to use service account or personal credentials without Trustedconnection. Is it some kind of dependency issue? I have tried various library version combos, but to no avail. Error message is: conn = Database.connect(connstr, django.db.utils.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'DOMAIN\\user'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0)") Requiremetns.txt asgiref 3.3.4 Django 3.2 django-mssql-backend 2.8.1 djangorestframework 3.12.4 pip 20.2.3 pyodbc 4.0.30 pytz 2021.1 setuptools 49.2.1 sqlparse 0.4.1 Not working (Win) DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'db_name', 'HOST': 'hostname', 'USER': 'DOMAIN\\user', 'PASSWORD': 'pass', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', } } } Working (Win) DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'db_name', 'HOST': 'hostname', 'USER': '', 'PASSWORD': '', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'Trusted_Connection': 'yes', } } } Working (Ubuntu) django==2.1.0 django-pyodbc-azure-2019 DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'db_name', 'HOST': … -
Django-parler does not return translated fields in the queryset
I am making an ajax request to the server to get all the news. Here is the function in views def get_news(request): if request.method == 'GET': queryset = News.objects.all().order_by("-date_news").values() all_n = list(queryset) return JsonResponse({'queryset':all_n}) But when displaying the result, there are not enough fields in which the translation is used. My model class News(TranslatableModel): translations = TranslatedFields( title_news = models.CharField(max_length = 120), desc_news = models.TextField(null=True, blank=True), ) main_image = models.ImageField(upload_to='img/news-mebelain') date_news = models.DateField(null=True, blank=True) the response from the server comes something like this date_news: "2021-03-30" id: 40 main_image: "img/news/img1 -
I'm trying to update tasks in a database but it keeps creating new tasks
I'm trying to create a feature in the def home(request): view that updates a task if the name already exists in the database. Is this possible? The code is below and help will be much appreciated. P.S. I wrote an update function below but that also doesn't work in the way that I intend it to. The error was "expecting integer not builtin function". from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.models import Group, User, Permission from django.contrib.auth import authenticate, login, logout from django.contrib.contenttypes.models import ContentType # the user from .models import Task from .forms import TaskForm def home(request): # add new task if request.user.is_authenticated: if request.method == 'POST': name = str(request.POST['task-name']) desc = str(request.POST['task-desc']) deadline = request.POST['deadline'] task = Task(task_name=name, task_desc=desc, task_deadline=deadline) if name in Task.objects.filter(task_name=name): task.save(update_fields=['task_name', 'task_desc', 'task_deadline']) else: task.save() #messages.success(request, "You've added a task.") return render(request, 'home.html', {}) else: return render(request, 'home.html', {}) def logout_view(request): # check if user is logged in when logout button is pressed if request.POST.get('logout'): print("user has logged out") logout(request) return render(request, 'logout.html', {}) def register(request): # collects customer group from database customers = Group.objects.get(name='customers') customers.has_change_permission(request, obj=Task) customers.has_view_permission(request, obj=Task) # task_content = ContentType.object.get_for_model(Task) # permission = Permission.objects.create( # codename="can_update_tasks", # … -
Django testing Forms.FileField
I'm trying to test my Comment Form with FileField. class CommentForm(forms.ModelForm): files = forms.FileField( widget=ClearableFileInput( attrs={"multiple": True, "class": "form-control", "id": "formFile"} ), required=False, label=_("Files"), ) def __init__(self, *args, **kwargs): self.ticket = None super().__init__(*args, **kwargs) class Meta: model = Comment fields = ["body", "files"] labels = {"body": _("Comment body")} def save(self, commit=True, new_status=None): instance = super(CommentForm, self).save(commit=False) if commit: instance.save() file_list = [] for file in self.files.getlist("files") or self.initial.get("files") or []: file_instance = self.save_attachment(file=file) file_list.append(file_instance) if len(file_list) > 0: async_task(add_attachments, file_list, instance.ticket.get_pk()) Writing test without attachment upload is easy, but problem starts when I want to test my form with files. I could not test whether async_task is called, and when I try to mock files and pass them to the Form, the attachment object does not apper in test database Here is my test: @patch("myapp.forms.comments.async_task", autospec=True) def test_create_comment_with_attachment(self, async_task): file_mock = mock.MagicMock(spec=File) file_mockname = "test_name.pdf" form = CommentForm( data={ "body": "Test comment", "files": mock.MagicMock(file_mock) } ) form.ticket = self.ticket self.assertTrue(form.is_valid()) form.save() attachment = Attachment.objects.last() print(attachment) The result of printing attachment is None, while I expected my file_mock to appear. Can anyone help my with testing attachment upload? -
when exactly django query execution occures
In a technical interview a questioner asked me a weird question regarding to the execution of querysets. Suppose we have a profile model like below: class Profile(models.Model): user = models.OneToOneField('User').select_related(User) surname = models.TextField(null=True) q = Profile.object.all() or q = Profile.object.get(id=1) l = q.filter(active=True) he asked how many query execution has been happened and I replied as the python interpreter executes Profile.object.all() at the begging then one query is already done. However, he answered zero, and one if we call the query, something like this: for a in l: a.surname Is his answer true in django? another doubt was about models.OneToOneField('User'), why he didn't use django.contrib.auth.models.User and defined models.OneToOneField('User').select_related(User) -
Image not loading on a class based view DJANGO for Twitter Card
I am trying to load the image on Twitter card and i am using 'SITE_PROTOCOL_URL': request._current_scheme_host, in function based views it is working well but in a class based view its not loading. I tried different ways but still doesnt work and i am stuck on it here is my code in view: def category(request,slug,pk): query_pk_and_slug = True katego=Kategori.objects.all() kategorit=Kategori.objects.get(title=slug, fotot_e_kategoris=slug) lajmet=Lajmet.objects.filter(kategorit=kategorit, verified=True).order_by('-data_e_postimit') lajms=Lajmet.objects.filter(kategorit=kategorit, verified=True).order_by('-data_e_postimit')[3:] lajmets=Lajmet.objects.filter(kategorit=kategorit, verified=True).order_by('-data_e_postimit')[7:] sponsor=SponsorPost.objects.all().order_by('-data_e_postimit') paginator = Paginator(lajmets, 15) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request,'main/category-news.html',{ 'SITE_PROTOCOL_URL': request._current_scheme_host, 'lajmet':lajmet, 'kategorit':kategorit, 'katego': katego, 'lajms': lajms, 'page_obj': page_obj, 'sponsor':sponsor }) class LajmetListView(ListView): model = Kategori model = Lajmet template_name = 'main/lajme-home.html' # <app>/<model>_<viewtype>.html context_object_name = 'lajmets' query_pk_and_slug = True def get_context_data(self, **kwargs): context = super(LajmetListView, self).get_context_data(**kwargs) context['lajmet'] = Lajmet.objects.order_by('-data_e_postimit').filter(verified=True) context['katego'] = Kategori.objects.all() context['shikime'] = Lajmet.objects.all().order_by('-shikime') context['SITE_PROTOCOL_URL'] = self.request._current_scheme_host return context And Template : {% if object.slug in request.path %} <title>{{object.titulli}}</title> <meta name="twitter:card" value="summary_large_image"> <meta name="twitter:site" content="@gazetarja_"> <meta name="twitter:creator" content="@SimonGjokaj"> <meta name="twitter:title" content="{{object.titulli}}"> <meta name="twitter:description" property="og:description" content="{{object.detajet|striptags|truncatewords:30}}"> <meta name='twitter:image' content="{{SITE_PROTOCOL_URL}}{{object.fotografit.url}}"> {% elif request.path == '/' %} <title>Portali Gazetarja - LAJMI FUNDIT</title> <meta name="twitter:card" value="summary_large_image"> <meta name="twitter:site" content="@gazetarja_"> <meta name="twitter:creator" content="@SimonGjokaj">' <meta name="twitter:title" content="Portali Gazetarja - LAJMI FUNDIT"> <meta name="twitter:description" content="Gazetarja i'u sjell në kohë reale, sekond pas sekonde informacione … -
How can I put 2 views in one template? Django
To put multiple forms in one view we are using request.POST.get(name argument of form), but When I am doing that with my register and login page than the login page is working, but I cant see the register form. The problem is to check if request is POST and than return the result for each case. def index(request): # login view if request.user.is_authenticated: return render(request, 'authenticated.html') else: if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('index') else: messages.error(request, 'Username or password is incorrect, try again!') return render(request, 'index.html') def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST or None) if form.is_valid(): form.clean_email() form.save() username = form.cleaned_data.get('username') messages.success(request, f'Successfully created account for {username}') return redirect('index') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) Html for login and registration <form method="post" name="login"> {% csrf_token %} <input type="text" name="username" placeholder="username"> <input type="password" name="password" placeholder="password"> <input type="submit" value="Login Yeah!"> </form> <form method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Sign Up"> </form> -
How to access multiple Data from jquery class to another input field to extract using python
kindly check out this image for further proceedings. Here we had used a jquery function to do the multiple CC. and we want to access those data to the second field from there will be stored to DB using python. -
How to redirect to an authenticated view with access token from another app in Django?
I have a Django website with two apps running on it. On app 1 the user receives an auth token and is supposed to be redirected to app 2 with said token. App 2 requires authentication in all views through APIView's permission_class "IsAuthenticated". app2/urls.py: app_name = 'app2' urlpatterns = [ path('',views.waitingroom_view.as_view(), name = 'waitingroom_index'), path('authenticated/',views.authentication_view.as_view(), name ='authentication') ] app2/views.py: class waitingroom_view(APIView): def get(self, request): return redirect('app1/index') My code correctly authenticates the user by giving them authentication tokens (refresh and access tokens) through a requests.post function: app1/views.py: def get_authentication_tokens(request, username, password): #BEWARE: hardcoded URL url = 'http://127.0.0.1:8000/api/token/' postdata = { 'username': username, 'password': password, } r = requests.post(url, data=postdata) tokens_json = r.json() #splits the respective tokens into 2 variables: "refresh" and "access" refresh_token = tokens_json['refresh'] access_token = tokens_json['access'] return access_token, refresh_token response = requests.get('http://0.0.0.0:8000/authenticated', auth=BearerAuth(access_token)) return HttpResponse(response) This returns a .html page that requires an auth token to access. However, the return is on app 1 instead of redirecting to app 2 with auth token. How do I redirect to an authenticated view (app 2) from another app (app 1) (that generated the auth token)? -
django model select_related or prefetch_related child model
Newbie here, I have two models which are below class ReceipeMaster(models.Model): receipe_type = models.CharField(max_length=50, choices=TYPE_OPTIONS, default=TYPE_OPTIONS[0]) item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='receipe') units = models.IntegerField(default=1) status = models.BooleanField(default=True) class ReceipeDetail(models.Model): master = models.ForeignKey(ReceipeMaster, on_delete=models.CASCADE, related_name='items') item_type = models.ForeignKey(Item_type, null=True, on_delete=models.PROTECT) item = models.ForeignKey(Item, on_delete=models.PROTECT) quantity = models.IntegerField() I have a detailed view DetailView class ReceipeDetailView(PermissionRequiredMixin, DetailView): permission_required = 'item_management.view_receipemaster' model = ReceipeMaster template_name = 'receipes/show.html' context_object_name = 'receipe' I would like to prefetch_related or select_related on the ReceipeMaster model and as well as the ReceipeDetail model. Simply prefetch on both models. Regards -
What is the best video storage solution
I have an application which connects to Instagram API and pulls massive amount of data everyday. My next challenge is to pull and save many Instagram users stories to a storage, then let my application users to see/view those stories in my django web app. I need to save nearly 50 GB of short videos (stories) everyday This makes nearly 20 TB of data for a year, so the storage must be at least that big The amount of stories that will be watched per day on my web app will be < 1000 (less than 1 GB) I don't have any experienced developers/engineers around me, so I do my own research about the subject. Azure Blog Storage looks like the solution that fit my needs but also a very expensive one (200-400$ per month). I have experience with Postgres and MySQL databases but not with Cloud services like Google or Azure, so any links, advices and tips are appreciated highly. -
Show a message in Django after a function completes, without having the user wait for it to complete
Say I have this view: import threading def MyView(request): thr = threading.Thread(target=my_func, args=(request,)) thr.start()#Runs a function that the user should not wait for return render(request, "my_site") where def my_func(request): #Some function that takes 10 second and the user should not wait for this sleep(10) messages.success(request, "Your meal is ready!") return render(request, "my_other_site") What I want to do is; I have a function of which the user should not wait for to complete i.e they should be able to continue browsing, and then when the function is done, I want to show them a message either using messages or a pop-up box or something third. Is there a way to do that in Django (since it all runs synchronous I can't think of a way), or what would be the most optimal way ( -
Discard records using serializers of Django rest framework
I need to discard all records that have no associated images. This must be implemented in serializers. If there is a solution in the views, it is also welcome. I have these models class Activity(models.Model): """ Class Activity """ name = models.CharField(max_length = 200, null = False, blank = False) create_at = models.DateTimeField('Create date', auto_now_add = True, editable = False) update_at = models.DateTimeField('Last update', auto_now = True) class Image(models.Model): """ Image of an activity """ activity = models.ForeignKey(Activity, related_name = 'images', on_delete = models.CASCADE) image = models.ImageField(upload_to = 'files/images') And following serializers class ImageModelSerializer(serializers.ModelSerializer): """ Image model serializer """ class Meta: model = Image fields = ('id', 'image') class ActivityModelSerializer(serializers.ModelSerializer): """ Activity model serializer """ images = ImageModelSerializer(read_only = True, many = True) class Meta: model = Activity fields = ('id', 'name', 'images', 'create_at') Here are examples of the response I need to get. Example: Correct [ { "id": 1, "name": "Activity 1", "images": [ {"id": 1, "image": "path to image 1"}, {"id": 2, "image": "path to image 2"} ], "create_at": "2021-04-07T15:58:15.409054Z" }, { "id": 3, "name": "Activity 3", "images": [ {"id": 3, "image": "path to image 1"}, {"id": 4, "image": "path to image 2"} ], "create_at": "2021-04-07T15:58:15.409054Z" } ] … -
Django model query .values() on a JSONfield
I have a JSONfield that contains a lot of data that I need to aggregate over, but i'm having a little trouble doing so. So I have a field in the JSON data that contains the amount of cores for a specific node, and i'd like to grab all these values in the DB and count them afterwards. I've tried the following data = Node.objects.filter(online=True).values( data__golem.inf.cpu.cores).annotate(the_count=Count(data__golem.inf.cpu.cores)) But that didn't work out, which might be because JSONfield doesn't support .values() queries? I'm not sure if that's the case anymore but it was mentioned at an old answer back from 2017. Next thing I tried was to just filter the by online=True and loop over each element in the QuerySet and then get the golem.inf.cpu.cores manually and add that to a dict and add it all together in the end. But that results in a KeyError and that's because of the punctations in the fieldname I would assume? How can I go on about this? print(obj.data['golem.inf.cpu.capabilities']) KeyError: 'golem.inf.cpu.capabilities' views.py @api_view(['GET', ]) def general_stats(request): """ List network stats. """ if request.method == 'GET': #data = Node.objects.filter(online=True) query = Node.objects.filter(online=True) for obj in query: print(obj.data['golem.inf.cpu.capabilities']) serializer = NodeSerializer(data, many=True) return Response(serializer.data) else: return Response(serializer.errors, … -
Django - Limiting selection of many to many field on ModelForm to just values from parent record
Could really use some help. I have a django app that has the following tables: Mission. Package. Target. Flight. A mission has 1 or many packages. 1 or many targets and 1 or many packages. A package has one or many flights. A Flight has a many to many relationship such that there is a multi-select field that allows you to select pre-added targets (added as children of the mission parent) to the flight. The problem is the dropdown shows all targets ever added to the database. I was expecting it would only show targets that belong to the mission parent. How do I limit the target options that appear in the Flight form, to just those of targets that belong to a mission? Mission Model class Mission(models.Model): # Fields campaign = models.ForeignKey( 'Campaign', on_delete=models.CASCADE, null=True) number = models.IntegerField( default=1, help_text='A number representing the mission order within the campaign.', verbose_name="mission number") name = models.CharField( max_length=200, help_text='Enter Mission Name') description = models.TextField( help_text='Enter Mission Description/Situation.', default="Mission description to be added here.") Package Model class Package(models.Model): # Fields mission = models.ForeignKey( 'Mission', on_delete=models.CASCADE, null=True) name = models.CharField( max_length=200, help_text='Enter Package Name', verbose_name="Package Name") description = models.TextField( help_text='Enter Mission Description/Situation.', null=True, blank=True, verbose_name="Description … -
Djoser user creating route return a socket error
I'm using Djoser to create a user from my front-end. When I create a user from the React app with this request const newStudent = () => { fetch(`${process.env.REACT_APP_SERVER_URL}/auth/users/`, { method: 'POST', headers: { "Accept": "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ email: "mss@domain.hr", display_name: "Maa", username: "as", password: "sa", role: 1 }) }) } The request completes, the new user gets created but this nice error pops up in the Django console ---------------------------------------- Exception occurred during processing of request from ('192.168.1.6', 49473) Traceback (most recent call last): File "C:\Python39\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Python39\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Python39\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\Mislav\.virtualenvs\backend-EBmKnWnA\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\Mislav\.virtualenvs\backend-EBmKnWnA\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Python39\lib\socket.py", line 704, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine ---------------------------------------- The interesting thing is that other requests work fine after the socket error Doing the exact same request from postman doesn't cause the error [08/Apr/2021 13:15:46] "POST /auth/users/ HTTP/1.1" 201 104 My Djoser setup DJOSER = { 'USER_ID': 'id', 'LOGIN_FIELD' : 'username', 'LOGOUT_ON_PASSWORD_CHANGE': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': … -
Invalid block tag on line 2: 'else', expected 'endblock'. Did you forget to register or load this tag?
I followed one django tutorial on youtube. I am currently category page where I want to have urls like this: "../search/<category_name>" I have no problem loading the page until I want to search the category. I am using the name in the category database which is 'django' so that I can avoid error. The URLs FYI, I'm using vscode and run the code in django html language. I have read some discussion regarding to this issue. I have followed one advice to rearrange so that it can read the code easily but when I save the code is going back to the state shown in the picture below. Therefore, I encounter an error due to invalid block tag. Django html code back to its state when I save picture Invalid block tag Output -
Django annotate and apply different aggregation functions on the same field
I'm using django annotate and I want to apply multiple aggregations on the same field: queryset = queryset.apply_filters( user=user, start_date=start_date, end_date=end_date ).values('product').annotate( avg_a=Avg('field_a'), total_a=Sum('field_a'), ) But I'm getting the following FieldError: django.core.exceptions.FieldError: Cannot compute Sum('field_a'): 'field_a' is an aggregate I'm quite sure that SQL queries like this one: SELECT AVG(field_a), SUM(field_a) FROM random_table GROUP BY product Are totally valid. To recap: How I could apply multiple aggregation functions on the same field using annotate? -
Make HTML custom field sortable in django-admin
I have a very simple model that just consists of a name and serial number. I can use that serial number to ask for a status on an API and I want to display the result as icon/HTML: class ProductAdminForm(admin.ModelAdmin): class Meta: model = Product fields = ["get_status", "name",] def get_status(self, obj): status = get_status_from_API(obj)["status"] style = """style="height: 10px; width: 10px; border-radius: 50%; COLOR display: inline-block;" """ if status == 2: new_style = style.replace("COLOR", "background-color: green;") elif status == 2: new_style = style.replace("COLOR", "background-color: red;") else: new_style = style.replace("COLOR", "background-color: grey;") return mark_safe(f"""<span class="dot" {new_style}></span>""") How can I make the get_status column sortable? -
New ckeditor's plugin is not showing
I am trying to add a Plugin in django-ckeditor in my BlogApp. How i am trying to do :- I have downloaded a plugin from ckeditor site named hkemoji and I have pasted it in the main plugins file of ckeditor but when i try to check in browser then it is not showing in Browser. I have seen many tutorial but nothing worked for me. Any help would be appreciated. Thank You in Advance.