Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Failed to start Gunicorn
Trying to deploy django app on ubuntu. start-server.sh has cd /home/django source env/bin/activate cd tutorial gunicorn tutorial.wsgi If I bash start-server.sh everything runs perfectly fine. So, I wrote following thing. gunicorn.service saved at /etc/systemd/system/ looks like [Unit] Description=Gunicorn After=network.target [Service] Type=simple User=django ExecStart=/bin/bash /home/django/bin/start-server.sh Restart=on-failure [Install] WantedBy=multi-user.target then I run sudo systemctl enable gunicorn sudo systemctl start gunicorn but now I see 502 error. when I bash start-server.sh, everything was perfect. but, somehow with gunicorn its not working. guincorn version 18.0(I tried 20.0 but no luck) sudo systemctl status gunicorn shows ● gunicorn.service - Gunicorn Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2021-06-09 16:56:59 UTC; 2min 5s ago Main PID: 26285 (code=exited, status=126) Jun 09 16:56:58 ip-184-168-120-14.ip.secureserver.net systemd[1]: gunicorn.service: Main process exited, code=exited, status=126/n/a Jun 09 16:56:58 ip-184-168-120-14.ip.secureserver.net systemd[1]: gunicorn.service: Failed with result 'exit-code'. Jun 09 16:56:59 ip-184-168-120-14.ip.secureserver.net systemd[1]: gunicorn.service: Scheduled restart job, restart counter is at 5. Jun 09 16:56:59 ip-184-168-120-14.ip.secureserver.net systemd[1]: Stopped Gunicorn. Jun 09 16:56:59 ip-184-168-120-14.ip.secureserver.net systemd[1]: gunicorn.service: Start request repeated too quickly. Jun 09 16:56:59 ip-184-168-120-14.ip.secureserver.net systemd[1]: gunicorn.service: Failed with result 'exit-code'. Jun 09 16:56:59 ip-184-168-120-14.ip.secureserver.net systemd[1]: Failed to start Gunicorn. -
`INSTALLED_APPS` from django's setting.py is not able to find my own pip package even though it is installed
I have created a pip package for my DRF application. I have tested the APIs of this package and it is working fine. Now I have decided to put it on PyPi so that my friends can also use it. This is how I uploaded my package to PyPi. (please note I already have an account on PyPi) Created source distribution - python setup.py sdist Check Manifest - check-manifest --create. Here I have made sure that all the module of my app are in the source distribution tar. The I created build distribution - python setup.py bdist_wheel sdit. wheel was already installed in my env. Then I installed twine and uploaded it to PyPi using command - twine upload --skip-existing dist/* Now to test this uploaded PyPi package I started a new Django Restframework project and installed it using pip install <package>. However when I mentioned it in the list of INSTALLED_APPS it return this error - ModuleNotFoundError: No module named. I have also check the virtual environment for the package at lib/python3.9/site-packages/ and yes I found the folder for my package. Where could I have possible went wrong. This is very weird problem. -
I used Django to creat a data to Mysql But it auto advance next Line
views I'm tring to save the eps data to Mysql url = "https://goodinfo.tw/StockInfo/StockFinDetail.asp?RPT_CAT=IS_M_QUAR_ACC&STOCK_ID=" headers = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36" } @api_view(['GET', 'POST', 'DELETE']) def eps_get(request): if request.method == 'POST': eps_serializer = EpsSerializer(data=request.data) stockID = request.data.get("StockID",0) if eps_serializer.is_valid(): eps_serializer.save() res = requests.get(url+stockID,headers = headers) res.encoding = "utf-8" soup = BeautifulSoup(res.text,"lxml") data = soup.select_one("#divFinDetail") dfs = pd.read_html(data.prettify()) df = dfs[0] df = df[df[0]=='每股稅後盈餘(元)'] Eps2021Q1 =df.iloc[0,1] Eps2020Q4 =df.iloc[0,3] Eps2020Q3 =df.iloc[0,5] Eps2020Q2 =df.iloc[0,7] Eps2020Q1 =df.iloc[0,9] Eps2019Q4 =df.iloc[0,11] Eps2019Q3 =df.iloc[0,13] Eps.objects.create( EPS2021Q1=Eps2021Q1, EPS2020Q4=Eps2020Q4, EPS2020Q3=Eps2020Q3, EPS2020Q2=Eps2020Q2, EPS2020Q1=Eps2020Q1, EPS2019Q4=Eps2019Q4, EPS2019Q3=Eps2019Q3, ) content = {'msg': 'Eps取得成功'} return JsonResponse(content, status=status.HTTP_201_CREATED) return JsonResponse(eps_serializer.errors, status=status.HTTP_400_BAD_REQUEST) models and I set it's float from django.db import models class Eps(models.Model): StockID = models.CharField(max_length=70,blank=True, null=True, default='') EPS2021Q1 = models.FloatField(max_length=200,blank=True, null=True, default="0") EPS2020Q4 = models.FloatField(max_length=200,blank=True, null=True, default="0") EPS2020Q3 = models.FloatField(max_length=200,blank=True, null=True, default="0") EPS2020Q2 = models.FloatField(max_length=200,blank=True, null=True, default="0") EPS2020Q1 = models.FloatField(max_length=200,blank=True, null=True, default="0") EPS2019Q4 = models.FloatField(max_length=200,blank=True, null=True, default="0") EPS2019Q3 = models.FloatField(max_length=200,blank=True, null=True, default="0") And my Mysql Here is my questions : I need the data save in the column but it advance next Line I just let blank and null True thank you ! =D -
ValueError while migrating a model in DJango
I am trying to create a simple model in Django. The expected fields are some text and owner's user id. However, this is what happens when I execute manage.py migrate (makemigrations worked without an error). I would appreciate any clues to this! Running migrations: Applying manage_remittance.0001_initial... OK Applying manage_remittance.0002_remittance_owner...Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: 'default' The above exception was the direct cause of the following exception: Traceback (most recent call last): ... ValueError: Field 'id' expected a number but got 'default'. models.py from django.db import models from django.contrib.auth.models import User class Remittance(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) remittance_text = models.CharField(max_length=140) def __str__(self): return self.remittance_text admin.py from django.contrib import admin from .models import Remittance admin.site.register(Remittance) -
Django form rendering api, custom renderer example
For pretty much all my Django forms, I loop through the fields and build the form HTML up manually. While reading the documentation I came across: https://docs.djangoproject.com/en/3.2/ref/forms/renderers/ I am not quite sure what the form renderer api is for. I have noticed I often style forms according to 2 different ways. Using the same Form, could I pass it into two different renderers to get the two different styles? Is my understanding correct? Can someone provide a minimum code example of how to implement the renderer API (which must at least implement render(template_name, context, request=None)). I don't quite understand how one implements the part to find the template from the template name. -
Django error: too many values to unpack (expected 2) after adding model record
The idea To make the code a bit more understandable, I will first explain what my code (from which the problem probably comes) is supposed to do in the first place: I save reports in my model. I give these reports their own ID or numbering, because this is absolutely necessary.This ID shall be structured as follows: <year><ascending number with leading zeros> Example: 2021001, 2021002, ..., 2022001 The code I have developed the following code for this purpose. Since the value is to be calculated automatically, I use the @property decorator. To be able to use the ID later more easily as a field and simply for my REST Api, I use the computed_property package. Extract from models.py: einsatznummer = ComputedTextField(blank=True, compute_from="einsatznummer_calc") @property def einsatznummer_calc(self): year_einsatz = self.einsatz_start.strftime('%Y') last_number = EinsatzPublic.objects.filter(einsatznummer__isnull=False, einsatz_start__year=year_einsatz).values_list('einsatznummer', flat=True) if EinsatzPublic.objects.filter('einsatznummer').count() >= 1: # if last_number == None : # last_number = 0 if last_number[:-1] != year_einsatz: last_number = 0 einsatznummer_gen = year_einsatz + (last_number + 1) return einsatznummer_gen else: einsatznummer_gen = (year_einsatz + 1) return einsatznummer_gen When I tried to add a record to the model (DeploymentPublic) I got the following error which I can't solve. Internal Server Error: /super/einsatzverwaltung/einsatzpublic/add/ Traceback (most recent call last): … -
Intercepting a Django 500 error for logging, without creating/serving a custom 500.html
In order to log "some dependency, somewhere deep" errors that trigger a server error 500, without stack traces in the console log on production instances due to DEBUG=False, I implemented the standard custom 500 handler that a fair number of Stackoverflow questions about printing a stack trace for a 500 error recommend: import sys import traceback def server_error_500_handler(request): type, value, tb = sys.exc_info() print('\n----intercepted 500 error stack trace----') print(value) print(type) print(traceback.format_exception(type, value, tb)) print('----\n') However, these then also all say to end with render(request, '500.html'), whereas I don't want to serve a custom 500 page, but want the code to go "back" (if there is such a thing) to just serving whatever Django itself does already. Is there some way to make it do that? Or, is there some way to listen for the 500 event without hijacking the 500 error return codepath? -
After a post request redirect to the previous inputted selection
I have a single-select dropdown menu that allows a user to choose what table they want to display. For example, Student Info College Info Career Info I get the user's input with the following post request and by default 'student_info' is displayed: > table_input_selection = request.POST.get('table_selection', 'student_info') Using django's formset, each table is dynamically populated by a df depending on which table is selected by the user. Each table allows the user to make updates to the existing table on the gui. Issue: A user can select the 'college_info' (non-default) table and make updates to the table. However, when 'Update' is clicked a redirect will default to the 'student_info' (default) table. How can I make it so that on a redirect it will not redirect to the default 'student_info', but the previous selected 'college_info' table? -
How can i resolve :unexpected eof error while parsing
PROJECT: using DJANGO to build a web app I am trying to import my context_processor into my urls.py , but keep getting the following error Error: File "C:\mysql\buisness\Main\urls.py", line 3, in <module> from . import context_processors File "C:\mysql\buisness\Main\context_processors.py", line 13 ^ SyntaxError: unexpected EOF while parsing context_processors.py: from django.shortcuts import render from .models import main from django.http import HttpResponse from django.core import serializers def dashboard(request): uname = request.POST.get('name') a = main.objects.filter(username = request.POST.get('name'), password = request.POST.get('pwd')).exists() if a is True: return render(request, 'Main/dashboard.html') else: return render(request, 'Main/login.html',{'error':"Username and password do not match", 'username':uname} urls.py: from django.urls import path from . import views from . import context_processors urlpatterns = [ path('', views.index, name="index"), path('base/',views.base, name="base"), path('contact/',views.contact,name="contact"), path('about/', views.about,name ="about"), path('browse/', views.browse,name='browse'), path('clients/',views.clients,name='clients'), path('registration/',views.registration,name='registration'), path(r'load_aop/', views.load_aop), path('test/', views.test, name="test"), path('dashboard/',context_processor.dashboard,name="dashboard"), path('login/',views.login,name="login"), path('abhi/',views.abhi,name='abhi') ] How do I solve it -
TypeError: comment_detail() missing 2 required positional arguments: 'request' and 'slug'
I got error path('post/<int:id>/comments', comment_detail(), name='comments'), TypeError: comment_detail() missing 2 required positional arguments: 'request' and 'slug' views.py from django.shortcuts import render, redirect from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .forms import CommentForm from .models import Post class BlogListView(ListView): model = Post template_name = 'home.html' context_object_name = 'posts' paginate_by = 2 queryset = Post.objects.all() class BlogDetailView(DetailView): model = Post template_name = 'post_detail.html' class BlogCreateView(CreateView): model = Post template_name = 'post_new.html' fields = ['title', 'author', 'body', 'header_image'] class BlogUpdateView(UpdateView): model = Post template_name = 'post_edit.html' fields = ['title', 'body', 'header_image'] class BlogDeleteView(DeleteView): model = Post template_name = 'post_delete.html' success_url = reverse_lazy('home') @property def image_url(self): if self.image: return getattr(self.photo, 'url', None) return None def comment_detail(request, slug): post = Post.objects.get(Post, slug=slug,) if request.method == 'POST': form = CommentForm(request.POST or None) if form.is_valid(): obj = form.save(commit=False) obj.post = post obj.save() return redirect('detail', slug=post.slug) else: form = CommentForm() context = { 'post': post, 'form': form } return render(request,'post_detail.html', context) I am trying to add comments to posts. -
ValueError: Cannot assign "{'interests': ['Technology', 'Sports', 'Health'] "Consumer.interests" must be a "Interests" instance
This is a Django + ReactJS Application where Django is the API backend and the ReactJS is the frontend. In the signup form when the user tries to register an account it returns an error ValueError: Cannot assign "['Sports', 'Health']": "Consumer.interests" must be a "Interests" instance. Unfortunately the SOF answers didn't help resolve the issue so I'm asking for your help. The registration API class RegistrationAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): print("Request: ", request.data) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() print(request.data.get('is_consumer')) if request.data.get('is_consumer') == 'True': consumer_data = request.data.get('additional') interest_data = consumer_data.get('interests') #interest_data = consumer_data.getlist('interests') print("the data is ", interest_data) dob_values = consumer_data.get("dob") dob = get_dob(dob_values) age = get_age(dob_values) gender = consumer_data.get("gender") Consumer.objects.create( user=user, interests=interest_data, dob=dob, age=age, gender=gender) User.objects.filter(pk=user.pk).update(is_consumer=True) elif request.data.get('is_business') == 'True': Business.objects.create( user=user, **request.data.get('additional')) User.objects.filter(pk=user.pk).update(is_business=True) # if serializer.is_valid(): # user = send_verification_email(request, serializer) # email sending for confirmation email_subject = 'Activate your account' email_body = 's' send_mail( email_subject, email_body, settings.DEFAULT_FROM_EMAIL, {user.email,}, ) return Response({"user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1]}) The Registration Serializer class RegisterSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = User fields = ('username', 'email', 'password', 'is_consumer', 'is_business') extra_kwargs = {'password': {'write_only': True}} model = Consumer fields = ('user','interests') def create(self, validated_data): user_data = validated_data … -
Yasg schema generation for nested serializer shows incorrect requests/responses
I have a Django API and I try to create the documentation with drf-yasg. I'm having trouble with the automatically generated schema for my nested serializer and ListAPIview. It looks like this: serializers.py class SlideDataSerializer(serializers.ModelSerializer): description = SlideDataDescriptionSerializer(many=True, read_only=True, source='slidedatadescription_set') class Meta: model = SlideData fields = ['catch', 'title', 'description', 'icon'] class SlideSerializer(serializers.ModelSerializer): datas = SlideDataSerializer(many=True, read_only=True, source='slidedata_set') class Meta: model = Slide fields = ['datas'] class PlanDataDescriptionSerializer(serializers.ModelSerializer): class Meta: model = PlanDataDescription fields = ['description'] class PlanDataSerializer(serializers.ModelSerializer): description = PlanDataDescriptionSerializer(many=True, read_only=True, source='plandatadescription_set') class Meta: model = PlanData fields = ['stripColor', 'name', 'description', 'pricePerMonth', 'currency', 'picture'] class PlanSerializer(serializers.ModelSerializer): datas = PlanDataSerializer(many=True, read_only=True, source='plandata_set') class Meta: model = Plan fields = ['mainTitle', 'datas'] views.py class ProjectList(generics.ListAPIView): permission_classes = [permissions.AllowAny] serializer_class_slide = SlideSerializer serializer_class_plan = PlanSerializer def get_queryset_object(self, Table, campaign, lang): queryset = Table.objects.filter(campaign__name=campaign).filter(language__alpha2=lang) return queryset[0] def list(self, request): Tables = [Slide, Plan] campaign = self.request.query_params.get('campaign') or "default" lang = self.request.query_params.get('lang') or "en" if not all(Table.objects.filter(campaign__name=campaign).filter(language__alpha2=lang) for Table in Tables): campaign = "default" if not all(Table.objects.filter(campaign__name=campaign).filter(language__alpha2=lang) for Table in Tables): lang = "en" slides = self.serializer_class_slide(self.get_queryset_object(Slide, campaign, lang)) plans = self.serializer_class_plan(self.get_queryset_object(Plan, campaign, lang)) return Response({ "slides": slides.data, "plans": plans.data, }) and the urls.py: openapi_info = openapi.Info( title="Projectname", default_version="v1", description="Endpoints", terms_of_service="TBD", contact=openapi.Contact(email="abc@123.com"), license=openapi.License(name="BSD … -
Django Authenticiation outside of username/password
Is there any way to authenticate with another object other than username/password? I have a dashboard where I'd like to continue to use username/password auth, however that's not suitable for an API. How can one implement an API key that can also log you in? Thank you in advance -
Django queryset to return all values matching a specific field name
I'm using Django and Django REST, and I'm looking for the syntax to be able to run a queryset again some JSON data stored in one of my fields in my database to pull out certain bits of data into a list. The data I have is as follows: { "field_a": "Registered", "field_b": { "field_b_1": "36942b25-3f90-4a89-9dc6-27deb0c2f0f6", "field_b_2": "some string", "field_b_3": "some string", "field_b_4": "some string", "field_b_5": "some string", "field_b_6": [ { "id": "39d75d16-f976-4041-8da9-8ba2bc7b16e9", "name": "some string", "short-name": "some string", "description": "some string" }, { "id": "c775653c-93fe-44ba-8cdf-d0fe90c0e61a", "name": "some string", "short-name": "some string", "description": "some string" } ] }, "field_c": "f34fe311-2d15-4bed-88e4-d19ef7cc1159" } I'm looking to have the "id" values from field_b__field_b_6 returned as a list. I will also have potential other rows in my database where the field_b__field_b_6 data may only have one "id" key. So, my desired output stored in a variable will be, based on the example above: ['39d75d16-f976-4041-8da9-8ba2bc7b16e9', 'c775653c-93fe-44ba-8cdf-d0fe90c0e61a'] And, if my data in field_b_field_b_6 only had one "id" key, then for my output to be: ['39d75d16-f976-4041-8da9-8ba2bc7b16e9'] Any help would be greatly appreciated. -
Django hash integrate with legacy database
I am working with django on a mysql legacy database. I have integrated everything but passwords. The legacy database is storing the passwords this way $2a$10$Pdg3h8AVZ6Vl3X1mMKgQDuMriv8iysnValEa5YZO3j9pEboLrOBUK and django reads only if the same hash has the bcrypt$ prefix bcrypt$$2a$10$Pdg3h8AVZ6Vl3X1mMKgQDuMriv8iysnValEa5YZO3j9pEboLrOBUK . How do I make django authenticate users by reading first example hash? And why django is adding the prefix to the password? -
Why can't I give my model formset a queryset? I want to be able to update and add via a model formset to my mdel
I have a modelform called PortfolioForm that is based on the Portfolio model, and I have a modelformset called PortfolioFormSet, that is based off the Portfolio model and the PortfolioForm. PortfolioFormSet = modelformset_factory(Portfolio, form=PortfolioForm, formset=BasePortfolioFormSet, extra=1, max_num=5, absolute_max=5, can_delete=True) In my view, I want to serve the formset populated with the data for each user, and be able to dynamically save, delete, and update data. if request.method == "GET": if request.user.username == username: return render(request, "dansapp/test.html", { "formset": PortfolioFormSet(queryset=Portfolio.objects.filter(user=request.user)) }) if request.method == "POST": formset = PortfolioFormSet(request.POST) if formset.is_valid(): instances = formset.save(commit=False) for instance in instances: instance.user = request.user instance.save() I get __init__() got an unexpected keyword argument 'queryset' as an error. For some reason quertset is not a valid arg, even though it is in the documentation. if request.user.username == username: return render(request, "dansapp/test.html", { "formset": PortfolioFormSet(initial=Portfolio.objects.filter(user=request.user).values()) }) I can hand it this, and it will be populated correctly, but nothing will save. 'PortfolioFormFormSet' object has no attribute 'save' This is the error I get. I'm not sure what to do to make this work. -
What should I use to test Django application?
I am using Django to build a website but I don't know what testing tools should I use and why? Django built-in test or Pytest. -
How to write blobs in GitHub action for auto-labeling Pull Requests?
I am trying to use this GitHub action to auto-label all the opened pull requests but I am struggling to get the globs correctly. My repo has a Django project so, for example, every ../tests/../test_*.py files should get the label test, any change in the Dockerfile in the root folder should get docker label and changes in the GitHub workflows should get actions label. The below snippet is how my globs look like and none of them work. Any thoughts on what I'm doing wrong? The documentation is a bit unclear. actions: - any: ['.github/*'] docker: - any: ['Dockerfile'] tests: - any: ['*test_*.py'] -
Djagno create a new application and enable permissions
In an existing project I want to create a logger app with the following structure logger |_ __init__.py (empty) |_ urls.py |_ logger_logs |_ __init.py (empty) |_ urls.py |_ admin.py (default) |_ apps.py (default) |_ models.py (default) |_ tests.py (default) |_ views.py and I run the following command python3 manage.py startapp logger_logs logger/logger_logs to create it. The outer urls.py is from django.urls import path, include urlpatterns = [ path('logger_logs/', include('logger.logger_logs.urls')), ] The inner urls.py is from django.urls import path from . import views urlpatterns = [ path('', views.download_logs, name='download_logs'), ] and the views.py is import os from glob import glob from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated @api_view(['POST']) @permission_classes([IsAuthenticated]) def download_logs(self, request, format=None, pk=None): // code I also have in settings.py w/in INSTALLED_APPS the line 'logger.logger_logs', and w/in the overall project urls.py w/in urlpatterns I have the line path('api/logger/', include('logger.urls')), When I do the request "POST /api/logger/logger_logs/download_logs/ HTTP/1.1" from the front-end I get a code 403 1406 and the message Forbidden (CSRF cookie not set.): /api/logger/logger_logs/download_logs/ I am aware of the case where someone can add a CSRF exemption. However, in all other applications and POST requests I have no CSRF exemption. Additionally, if I do the request … -
2 Forms in mainpage. Models, forms.py html ok but submit button not work
I stack. I try many thinks. I want to put 2 forms in my mainpage. Models, forms in index.html, ModelForm, save(), urls.. I think everything ok. But submit button do nothing. #models.py from django.db import models class Iletisim(models.Model): DURUM = [ ('KT', 'Keşif Talebi'), ('AB', 'Arıza Bildirimi'), ('IL', 'İletişimden'), ] SINIF = [ ('Konut', ( ('SI', 'Site '), ('DA', 'Apartman Dairesi'), ('VI', 'Yazlık/Bağ/Villa'), ) ), ('İşyeri', ( ('OF', 'Ofis/Büro/Dükkan'), ('FA', 'Fabrika/Şantiye/Otel/Okul'), ) ), ('DG', 'Diğer'), ] name = models.CharField(max_length=100, verbose_name="Ad/Soyad") phone = models.CharField(max_length=100, verbose_name="Telefon") address = models.CharField(max_length=250, verbose_name="Adresi") message = models.CharField(max_length=1000, verbose_name="Mesaj") email = models.EmailField(max_length=40, verbose_name="E-Posta") province= models.CharField(max_length=40,verbose_name="Şehir") tarih = models.DateTimeField(default=None) basvuru = models.CharField(max_length=2, choices=DURUM) sinif = models.CharField(max_length=2, choices=SINIF) class Meta: ordering = ["tarih", "email"] verbose_name = "Mesaj" verbose_name_plural = "Mesajlar" def __str__(self): return self.basvuru My forms folder from django.shortcuts import redirect, render from django.forms import ModelForm from apps.giris.models import Iletisim class Kesif_Form(ModelForm): class Meta: model = Iletisim fields = '__all__' def kesif_kayit(request): if request.method=='POST': form = Kesif_Form(request.POST) if form.is_valid(): yeni_kesif = Iletisim() yeni_kesif.name = request.POST.get("name") yeni_kesif.phone = request.POST.get("phone") yeni_kesif.address = request.POST.get("address") yeni_kesif.message = request.POST.get("message") yeni_kesif.email = request.POST.get("email") yeni_kesif.province = request.POST.get("province") yeni_kesif.tarih = request.POST.get("tarih") yeni_kesif.basvuru = request.POST.get("basvuru") yeni_kesif.sinif = request.POST.get("sinif") yeni_kesif.save() return redirect('index') else: form = Kesif_Form() context={'form' : form} … -
How to automatically generate django rest framework documentation with parameters?
I use redoc + drf_yasg to generate the documentation of my api made with django-rest-framwork. It works well as soon as I add an entry point it appears well in the documentation. However, I don't understand how to add in the documentation the search parameters that can be given during the query. For example, in the list function, I can pass 2 optional parameters, an id and name: class TechnicalDataViewSet(viewsets.ViewSet): """ A simple ViewSet for listing or retrieving machine. """ permission_classes = [permissions.IsAuthenticated] def list(self, request): id_machine = self.request.query_params.get('id_machine') name = self.request.query_params.get('name') queryset = TechnicalData.objects.all() if id_machine: queryset = queryset.filter(machine__id=id_machine) if name: queryset = queryset.filter(name=name) serializer = TechnicalDataSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = TechnicalData.objects.all() technical_data = get_object_or_404(queryset, pk=pk) serializer = TechnicalDataSerializer(technical_data) return Response(serializer.data) I don't see any mention of the parameters in the documentation. How can I add them? I don't know if this helps but here is how I implemented redoc: schema_view = get_schema_view( openapi.Info( title="test API", default_version='v1', description=f""" # Public API **Reserved to authenticated users** Token Lifetime : * ACCESS_TOKEN_LIFETIME : {duration(settings.SIMPLE_JWT.get('ACCESS_TOKEN_LIFETIME'))} * REFRESH_TOKEN_LIFETIME : {duration(settings.SIMPLE_JWT.get('REFRESH_TOKEN_LIFETIME'))} ### Links [Get access token](************) ### Format Use `?format=` option in url: * `?format=api` (default) * `?format=json` """, … -
Django simple-history how to track ForeignKey relations?
I am using django-simple-history to track changes to some fields on my models. My simplified model setup: class Collection(models.Model): description = models.TextField() # ... history = simple_history.HistoricalRecords() class Item(models.Model): content = models.TextField() collection = models.ForeignKey(Collection, related_name="items", on_delete=models.CASCADE) # ... history = simple_history.HistoricalRecords() Now ideally I would like to see Item changes reflected in Collection.history. For example, if a new Item is added to a collection, I would like to have a new entry in Collection.history. Is this somehow possible? -
Template not displaying Validation error (Django)
I'm trying to display the Validation Error in my template (register.html) but it's not displaying. What is wrong with this code? and one more question "how I can display email already exist in this form" I don't know how to display the "email already exist". The Codes Goes here. forms.py from django.contrib.auth.models import User from django import forms from .models import * from django.utils.translation import gettext as _ class RegisterForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput()) password = forms.CharField(widget=forms.PasswordInput()) email = forms.CharField(widget=forms.EmailInput()) class Meta: model = Customer fields =["full_name", "username", "email", "password"] def clean_username(self): uname = self.cleaned_data.get('username') if User.objects.filter(username = uname).exists(): raise forms.ValidationError(_('Customer with this username already exists'), code='invalid') return uname def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor self.fields['username'].widget.attrs['style'] = 'width:500px; height:40px;' self.fields['password'].widget.attrs['style'] = 'width:500px; height:40px;' self.fields['email'].widget.attrs['style'] = 'width:500px; height:40px;' self.fields['full_name'].widget.attrs['style'] = 'width:500px; height:40px;' I can't display the Error Message on above code Customer with this username already exists views.py from django.shortcuts import render, redirect from django.views.generic import CreateView, View, FormView from django.contrib.auth import authenticate, login, logout from django.urls import reverse_lazy from .forms import * # Create your views here. class customerRegister(CreateView): template_name = "register.html" form_class = RegisterForm success_url = reverse_lazy("main_app:base") def form_valid(self, form): username = form.cleaned_data.get("username") email … -
Python Get year to date from now
I have a drop-down in django/python3 to return metrics based on 30, 60, or 90-day activity. Want to add a year-to-date option as well but having trouble with the implementation. Here is the code so far. def get_period_from_request(request) -> Tuple[datetime, datetime]: period = request.GET.get("period") right_now = timezone.now() # trying to get ytd from now() to 1/1/???? # ytd = datetime.now().date().replace(month=1, day=1) if period == 'last_60_days': return right_now + timedelta(days=-60), right_now elif period == 'last_90_days': return right_now + timedelta(days=-90), right_now #elif period == 'year_to_date': # return ytd, right_now else: return right_now + timedelta(days=-30), right_now -
Django unable to modify a row in SQL Server with multiple primary keys
I am using Django 3.0, DjangoRestFramework 3.12 and django-mssql-backend 2.8.1 to build a webapp version of a current desktop app that stores everything in a legacy MS SQL Server database. Due to this I am limited to database modifications that don't alter the table structure already in place. I built my Django models using the built-in legacy database model-generator and then made final modifications on my own. I've been following tutorials to build an API to handle data and everyone seems to recommend using DRF. All of my views use ListAPIView, RetrieveAPIView, and RetrieveUpdateAPIView. Now, when I try to build part of the API to allow me to alter settings in one of the tables, I'm running into an error about inserting a duplicate key value. Database Table: dbo.systemDateTimeSettings - LocationID (PK, FK, int, not null) - Setting (PK, nvarchar(50), not null) - Value (datetime, null) Model: class SystemDatetimeSettings(models.Model): location_id = models.OneToOneField(Locations, models.DO_NOTHING, db_column='LocationID', primary_key=True) setting = models.CharField(db_column='Setting', max_length=50) value = models.DateTimeField(db_column='Value', blank=True, null=True) def get_api_url(self, request=None): return reverse("api:datetime-settings-update", kwargs={ 'location_id': int(self.location_id.location_id), 'setting': self.setting }, request=request) class Meta: managed = False db_table = 'SystemDateTimeSettings' unique_together = (('location_id', 'setting'),) Serializer: class SystemDatetimeSettingsSerializer(serializers.ModelSerializer): url = serializers.SerializerMethodField(read_only=True) class Meta: model = SystemDatetimeSettings fields …