Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best Practice: Processing complex dynamic form on single-page with Django
I'm looking for the most pythonic way to handle a complex form on a single-page. My "submit" page has a series of questions that, based on the user's input, will generate different forms/fields. A simplified example: --- Shift 1 --> Form #1 --- Yes -- What shift? -- | | --- Shift 2 --> Form #2 | Enter Date --- Did you work? ---| | | --- Yes --> Form #3 --- No -- Was this PTO? ---| --- No --> Form #4 I'm trying to figure out most efficient/pythonic way to handle the above. Possible Approaches: Lots of jquery, ajax, and function based views. This is my current setup, but I'd like to move it to CBV and ModelForms if possible because my current code is about 2000 lines (with 10+ ajax functions, 10+ view-handling urls, and too many input fields to count) within my template/models/views just to load/process this form. It is a complete nightmare to maintain. Single page with ModelForms embedded within a dynamic div. The form page calls a jquery load depending on your answers to the questions. For instance, if you answered "Today", "Yes", "Shift 1", I would call $("#form-embed").load("/forms/form1/") which contains the Form #1 … -
Desktop App connected to website with python
I recently started to program in Python. In my job they ask me to program a website with sign-in/login to perform multiple tasks (print a dashboard, export data, etc.) and a desktop app that connects to this website to retrive info from a particular module (We will upload files to this site and desktop app will compare that files to specified files in desktop). What is the best option to perform this task. Actually, i programmed a CRUD in Django with MySQL database (not deployed to production yet) and a desktop app in Tkinter, but as this grows i think this is not suitable. What will be better options for this task? Thanks in advance, as i say, im new to python programming -
Request.data django
Tengo un problema con django al modificar el request, necesito agregar un atributo, eh visto varios sitios y todos me dicen lo mismo, logro modificar el request pero al mandarlo al serializador, el request no se ve reflejado los cambios def create(self, request): data = json.dumps(request.data) data = json.loads(data) data['id_user_created'] = 1 serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return ResponseData.Response(TYPECODE.NO, TYPECODE.CREATED, MESSAGE.CREATED, MESSAGE.NULL, status.HTTP_201_CREATED) return ResponseData.Response(TYPECODE.SI, TYPECODE.BAD_REQUEST, MESSAGE.BAD_REQUEST, serializer.errors, status.HTTP_400_BAD_REQUEST) Mi serializador class UserSerializer(serializers.ModelSerializer): class Meta: model = Usuario exclude = ['created_date', 'last_login','modified_date','id_user_created','id_user_modified'] def to_representation(self, instance): return { 'id':instance.id, 'state':instance.state, 'email':instance.email, 'names':instance.names, 'identify':instance.identify } def create(self, validated_data): print(validated_data) user = Usuario(**validated_data) user.set_password(validated_data['password']) #user.id_user_created = validated_data.id_user_created user.save() return user -
permission.AllowAny not working in knoxLoginView
I tried using the knoxLoginView for login with token authentication,and it was stated on knox documentation that for the loginView to work and not throw a 401 unauthorized error i have to either add permission class "AllowAny" or override the authentication class with BasicAuthentication. I tried both neither worked, the login view still throws 401 unauthorized error.The surprising thing is i saw a youtube tutorial where a guy used the permission.AllowAny and it worked, don't know why its not working for me. here's the login view code: class LoginAPI(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginAPI, self).post(request, format=None) settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'knox', 'corsheaders', 'users', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ #'rest_framework.authentication.BasicAuthentication' , 'knox.auth.TokenAuthentication', ] } -
how to convert a QuerySet to a set in django?
I have a query, name_phonenum = person.objects.value_list('first_name','phone_num') I want to convert the queryset to a set. Any idea how can do it. -
How do I enforce 2 decimal places on API response in Django?
I am making a small API server in Django. For one of my fields, I am using a decimal field which is responsible for representing $ dollar values, so I would like to have 2 decimal places at all times. But I'm struggling to have the exact format. I'm using rest_framework and my base level response is encoded as a string with the following serializer is: price = serializers.DecimalField(max_digits=10, decimal_places=2, required=True) string representation There is an option to turn off string coercion with "COERCE_DECIMAL_TO_STRING": False in settings.py, but then I face a problem that Decimal is not JSON serializable, and have to use FloatField where I cannot specify a format and end up with only 1 decimal place: price = serializers.FloatField(required=True) float representation I searched for setting up FloatField format on the serializer but did not find any related option. I believe I also tried some other serializers like this one and did not achieve the goal, which is: How do I enforce 2 decimal places on API response in Django? -
Is it possible to return blank strings in .values() from a Django queryset?
In Django, if I have 2 models: class MyModelA(models.Model): column_1 = ... column_2 = ... column_3 = ... class MyModelB(models.Model): column_1 = ... column_2 = ... column_3 = ... column_4 = ... column_5 = ... I need to use union to combine the results in these, but they don't have the same number of columns. For the extra columns, I just need MyModelA to return blank strings. Is it possible to do something like this? MyModelA.objects.values("column_1", Value(""), Value(""), "column_2", "column_3").union( MyModelB.objects.values("column_1", "column_2", "column_3", "column_4", "column_5") ) From the docs on union Passing different models works as long as the SELECT list is the same in all QuerySets (at least the types, the names don’t matter as long as the types are in the same order) This means I'm basically trying to map: MyModelA.column_1 --> MyModelB.column_1 "" --> MyModelB.column_2 "" --> MyModelB.column_3 MyModelA.column_2 --> MyModelB.column_4 MyModelA.column_3 --> MyModelB.column_5 Using Value("") as above doesn't work however. Is there another way to do this? -
Speed up object creation
I have an API call which return an json file like 1000s of this: { "date": "2021-02-27T00:00:00+00:00", "value": 11590, "countryName": "Netherlands", "countryCode": "NL" }, { "date": "2021-02-27T00:00:00+00:00", "value": 88, "countryName": "Belgium", "countryCode": "BE" } I have some code which creates entries and links it through a foreign key: for country in response['countryPlots']: country['parent'] = parent.pk countrydata = CountrySerializer(data=country) countrydata.is_valid(raise_exception=True) countrydata.save() But it's too slow. I have to do millions of these creations. -
DRF Create: Response is not returning my template with context variables despite using built in render_to_string()
Background I want to create and render replies without the need to refresh the page. I know this can be done by submitting the form using AJAX or Fetch(), and use the returned response to append to the bottom of the comment list. I am trying to accomplish this using DRF and AJAX. I opted in to DRF HTMLRenderer + Django render_to_string() so I do not have to create a JS template literal to render the template from JSON, and it would also be a lot easier for me to make any template changes if I just let the Django templating system do it for me. Problem My response is not populating my template with context variables, despite me passing in the context to the built in render_to_string(). The chances of render_to_string() being at fault is very low, and I am honestly not sure how to resolve this. I also tried switching out the render_to_string() with render() to see if that would somehow fix the problem. However, the problem still remained. I know this because of the following two attribute errors when viewing the response from the console: 'str' object has no attribute 'is_authenticated' Reverse for 'profile_detail' with arguments '('',)' … -
NoReverseMatch at /projects/ Reverse for 'user-profile' with arguments '('',)' not found
I am just getting started with Django and I don´t know exactly where this error comes form. It´s probably related to the owner attribute. Here is my code so far. projects/modely.py class Project(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL) title = models.CharField(max_length=200) users/models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank=True, null=True) projects/views.py def projects(request): projects = Project.objects.all() context = {'projects':projects} return render(request, 'projects/projects.html', context) projects.html {% for project in projects %} <p><a class="project__author" href="{% url 'user-profile' project.owner.name %}">{{project.owner.name}}</a></p> {% endfor %} users/views.py def userProfile(request, pk): profile = Profile.objects.get(id=pk) context = {'profile':profile} return render(request, 'users/user-profile.html', context) -
Installing Markdown in Django
world!, Please how do I install markdown and import it into a django project.? i am new to programming and presently working on the Wiki project in the edX tutorial. Thank you for your help -
Django custom form attrs removes css class
I'm dealing with an RTL CharField so I impelemted the below in my admin.py: class CustomPostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'slug', 'lead', 'body', 'status', 'is_featured'] widgets = {'title': forms.TextInput(attrs={'dir': 'rtl'})} @admin.register(Post) class PostAdmin(admin.ModelAdmin): form = CustomPostForm This works fine except that when I look at the form in the Admin site the width of the RTL field is less than the next LTR field: And if I remove the whole custom form, then both fields look the same: So I inspect the code and realize that the slug field has a css class called vTextField and if I change the custom form's attrs both fields look the same: widgets = {'title': forms.TextInput(attrs={'dir': 'rtl', 'class': 'vTextField'})} So my question is, is it normal or intentional for Django to remove CSS class if attrs is used and my approach in putting the class back is correct, or I'm missing something here? -
Are you having trouble deploying your Django apps to Heroku?
I had trouble with this, too. Even after following Mozilla's guide, and a YouTube video I found on the subject as well. So I put together this handy guide incorporating both the MDN guide and the YouTube video guide, which you can find here in my GitHub repo. Hope it helps you all! -
Django Shell indexing Queryset on any position returns the exact same result - DB Lazy Evaluation
This isn't maybe as much of a question as it is a confirmation and request for more insight. When running a QuerySet request in python shell something like this: qs = MyModel.objects.all() or qs = MyModel.objects.get_queryset() or qs = MyModel.objects.filter(field='something') then followed by anything like this: qs[0] or qs[1] or qs[any_valid_int] it will always return the DB entry in position 0 of the returned QuerySet no matter what index you use. This mad me scratch my head at first. Now I understand QuerySets are generators in Django (?) and are evaluated lazy as documented here: Django Doc: Querysets Are Lazy When you do anything (in the shell) that evaluates the returned qs like for example len(qs) and then use indexing again it will suddenly return the correct DB entries with qs[any_valid_int] behaving exactly as expected. I believe this corresponds with this Django bug report question from 6 years ago as well. So am I on the right track here assuming that this has to do with lazy evaluation? And what is the best/quick way in Django shell to just get a QuerySet and directly index the one you want for testing without having to use something like len(qs) first? Is … -
how to set-up liveness and readiness probes for Celery worker pods
I want to set-up liveness and readiness probes for Celery worker pods. Since these worker pods doesn't have a specific port associated to them I am finding it difficult. Main Django app nginx server was easier to set-up. I am very new to k8s so not much familiar to the different ways to do it. -
How to Setup send email function in html form using any programing language? [closed]
The html form code given as follow how to setup this contact form to get email to my account using any language: <form action="" method="post"> <div class="fields"> <div class="field name"> <input type="text" placeholder="Name" name="name" required> </div> <div class="field email"> <input type="email" placeholder="Email" name="email" required> </div> </div> <div class="field"> <input type="text" placeholder="Subject" name="subject" required> </div> <div class="field textarea"> <textarea cols="30" rows="10" placeholder="Message.." name="message" required> </textarea> </div> <div class="button-area"> <button type="submit">Send message</button> </div> </form> <!-- html form code --> -
Django Heroku Application Erorr
I made a small site and I wanted to publish it on heroku. However, some errors arose during this time. The site gave a favicon.ico error, so I wondered if there was a problem with the django project I coded, so I opened a new clean project and the same problem arose. settings.py """ Django settings for yayinda project. Generated by 'django-admin startproject' using Django 4.0.3. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ import os from pathlib import Path import django_heroku django_heroku.settings(locals()) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-6hv!w%64=3)hj7hix=tzv^$9n4-mn0l@!=4$uax%gs)mtsr)z0' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['127.0.0.1','yayinda.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'yayinda_deneme' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'yayinda.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, … -
Single token refresh vs Long running refresh tokens (Django GraphQL JWT)
I used both "Single token refresh" mode and "Long running refresh tokens" mode. "Single token refresh" mode: GRAPHQL_JWT = { "JWT_VERIFY_EXPIRATION": True, "JWT_EXPIRATION_DELTA": timedelta(minutes=5), "JWT_REFRESH_EXPIRATION_DELTA": timedelta(days=7), } "Long running refresh tokens" mode: GRAPHQL_JWT = { "JWT_VERIFY_EXPIRATION": True, "JWT_LONG_RUNNING_REFRESH_TOKEN": True, // This code is added. "JWT_EXPIRATION_DELTA": timedelta(minutes=5), "JWT_REFRESH_EXPIRATION_DELTA": timedelta(days=7), } But I couldn't get a refresh token in "Single token refresh" mode running this graphql below: mutation { tokenAuth(username: "admin", password: "admin") { token payload refreshExpiresIn refreshToken // Here } } Then, I got this error: { "errors": [ { "message": "Cannot query field \"refreshToken\" on type \"ObtainJSONWebToken\". Did you mean \"refreshExpiresIn\"?", "locations": [ { "line": 20, "column": 5 } ] } ] } Then, I removed "refreshToken" field and ran this graphql: mutation { tokenAuth(username: "admin", password: "admin") { token payload refreshExpiresIn # refreshToken } } Then, I could get this result without error but I still couldn't get a refresh token: { "data": { "tokenAuth": { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNjQ3MDk2MTExLCJvcmlnSWF0IjoxNjQ3MDk1ODExfQ.5AY0HGqqmy3KwW1Gb_DFO99hIvJJh_AEngRH7hSe4DM", "payload": { "username": "admin", "exp": 1647096111, "origIat": 1647095811 }, "refreshExpiresIn": 1647700611 } } } Next, when I ran this graphql with "refreshToken" field in "Long running refresh tokens" mode: mutation { tokenAuth(username: "admin", password: "admin") { token payload refreshExpiresIn refreshToken // … -
How to store Url parameters value in variable using django? [closed]
Url - http://127.0.0.1:8000/result/?query=boys view.py - query = request.GET.get('query') params = { "query":{query}, "image_type":"photo" } -
How to multiply two variables together in HTML template DJANGO
I have this page that lists various info on a specific stock including orders that have been placed on that specific item. I would like to display how much money the user of this system would get from that specific order. <table class='table'> <thead> <tr> <th>ORDER ID</th> <th>NAME</th> <th>AMOUNT ORDERED</th> <th>REVENUE</th> <th>ORDERED ITEM</th> <th>ADDRESS</th> <th>CITY</th> </tr> </thead> {% for x in queryset2 %} <tr> <td>{{x.id}}</td> <td>{{x.name}}</td> <td>{{x.quantity}}</td> <td>{{x.quantity * stock.ppu}}</td> <td>{{x.order_item}}</td> <td>{{x.address}}</td> <td>{{x.city}}</td> </tr> {% endfor %} </table> I have this code so far. What would be the correct syntax to multiply these two variables together : {{x.quantity * stock.ppu}} -
here i am creating a ecommerce website using Django code .but facing error during installations of requirements [closed]
The headers or library files could not be found for zlib, a required dependency when compiling Pillow from source. Please see the install instructions at: https://pillow.readthedocs.io/en/latest/installation.html Traceback (most recent call last): File "C:\Users\MY PC\AppData\Local\Temp\pip-install-0t2cfsyb\pillow_f848d0aa6d444c8faf818219ccf20861\setup.py", line 852, in <module> setup( File "C:\Users\MY PC\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\__init__.py", line 153, in setup return distutils.core.setup(**attrs) File "C:\Users\MY PC\AppData\Local\Programs\Python\Python310\lib\distutils\core.py", line 148, in setup dist.run_commands() File "C:\Users\MY PC\AppData\Local\Programs\Python\Python310\lib\distutils\dist.py", line 966, in run_commands self.run_command(cmd) File "C:\Users\MY PC\AppData\Local\Programs\Python\Python310\lib\distutils\dist.py", line 985, in run_command cmd_obj.run() File "C:\Users\MY PC\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\command\install.py", line 61, in run return orig.install.run(self) File "C:\Users\MY PC\AppData\Local\Programs\Python\Python310\lib\distutils\command\install.py", line 568, in run self.run_command('build') File "C:\Users\MY PC\AppData\Local\Programs\Python\Python310\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "C:\Users\MY PC\AppData\Local\Programs\Python\Python310\lib\distutils\dist.py", line 985, in run_command cmd_obj.run() File "C:\Users\MY PC\AppData\Local\Programs\Python\Python310\lib\distutils\command\build.py", line 135, in run self.run_command(cmd_name) File "C:\Users\MY PC\AppData\Local\Programs\Python\Python310\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "C:\Users\MY PC\AppData\Local\Programs\Python\Python310\lib\distutils\dist.py", line 985, in run_command cmd_obj.run() File "C:\Users\MY PC\AppData\Local\Programs\Python\Python310\lib\distutils\command\build_ext.py", line 340, in run self.build_extensions() File "C:\Users\MY PC\AppData\Local\Temp\pip-install-0t2cfsyb\pillow_f848d0aa6d444c8faf818219ccf20861\setup.py", line 687, in build_extensions raise RequiredDependencyException(f) __main__.RequiredDependencyException: zlib During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\MY PC\AppData\Local\Temp\pip-install-0t2cfsyb\pillow_f848d0aa6d444c8faf818219ccf20861\setup.py", line 903, in <module> raise RequiredDependencyException(msg) __main__.RequiredDependencyException: The headers or library files could not be found for zlib, a required dependency when compiling … -
DJANGO MODELCHOICEFIELD DEFAULT FIELD SHOWS FIELD REQUIRED ERROR ON UPDATEVIEW
I am trying to let users complete their registration by updating their Profile with other data. The Profile model is linked to Django's User model via foreignkey relationship in models.py as shown below: class Profile(models.Model): user_main = models.ForeignKey(User, on_delete=models.DO_NOTHING) And my forms.py I have: class ProfileForm(ModelForm): class Meta: model = Profile fields = ('user_main', 'other_fields') widgets = { 'user_main': forms.Select(attrs={ 'id': 'user_main', 'class': 'form-control input-lg userprofile-class disabled', 'name': 'user_main', 'disabled': True }), And views.py: class UserUpdateView(LoginRequiredMixin, UpdateView): form_class = ProfileForm template_name = "registration/update_profile.html" success_url = '/theportal/home-page' def get_initial(self): #set initials and return it So, the form displays with the user_main already pre-selected and it is disabled by default so that users cannot mistakenly select another user for it. But when I click submit button, I get error This field is required. for already selected user_main and when the form returns with the error, the reloaded form comes back with all the data entered by the user but user_main is now empty as shown in the attached screenshot. How do I rectify this? -
Redirect in CreateView Django doesn't work
Hi I try to make a blog using CBV. I want after create a new post in post_form.html the CreateView will redirect to the new post_detail I just made. So I was search on gg and try both get_success_url and redirect_field_name. But it still had error Page not found . Because of that I really don't know the new post was created or not. Can someone check it for me. Views.py class PostCreateView(LoginRequiredMixin,CreateView): login_url = '/login/' form_class = forms.Post_form model = models.Post #redirect_field_name = 'mlog/post_detail.html' def get_success_url(self): return reverse('post_detail', kwargs={'pk': self.object.pk,}) urls.py path('post/<int:pk>/',views.PostDetailView.as_view(),name='post_detail'), path('post/new/',views.PostCreateView.as_view(),name='post_new'), path('post/<int:pk>/edit/',views.PostUpdateView.as_view(),name='post_edit'), path('post/<int:pk>/remove/',views.PostDeleteView.as_view(),name='post_remove'), path('dratf/',views.DraftListView.as_view(),name='post_draft_list'), -
Multiple select with same name django
Please i need help with the following: i have the following select: <select multiple class="form-control"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> i want to clone it with jquery and submit multiple select like this, in php i add a "[][]" in name, and the result is some like: [[1,1,1,], [2,2,2]], how i achieve this using django? thanks -
Cache when user open multiple tabs Redis + Django
I have a database that is updated once a month, so I use redis to save cache Everything works fine for me, I add user name after a key like this: nhan_vien=CustomUser.objects.get(id=request.user.id).username contract_number = cache.get("contract_number" + nhan_vien) my settings: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", 'TIMEOUT': 60 * 60 * 8, "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } A user cannot access cache from another users. If a user open 2 tabs, Tab1: he/she has contract_number from cache.get("contract_number" + nhan_vien). He open new tab2, then he/she has new contract_number from cache.get("contract_number" + nhan_vien) My issue when he/she save data in tab1, my website gets value from new contract_number (in tab2) to save data while the content belongs to contract_number in tab1. If I set Timeout, after this time no record contract is appear and then they cannot save data. I have 3 questions: How can I handle this issue by redis + django. How can I dont allow user opens a new tab while they access my website? If I cannot solve this by only redis + django, Is there any other solutions? I used to read in Stackoverflow https://stackoverflow.com/questions/7763115/django-passing-data-between-views how can pass data between views. Solution …