Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Lock delete () function - Django
Is there an option to disable the delete function in the project object if a non-admin user tries to do this via delete function? For example: class Product(models.Model): name = models.CharField(max_lenght=200) show = models.BooleanField() logs = models.TextField() And now if we have in code of project product.delete() we block it through the model property and check if it is an admin, if it is not an admin add a reflection in the field.: class Product(models.Model): name = models.CharField(max_lenght=200) show = models.BooleanField(default=True) logs = models.TextField() def delete(self, *args, **kwargs): super().save(*args, **kwargs) if request.user.is_superuser Product.delete() else: show = False logs = 'ther user try remove this ads in time: 08.11 04.11.2022' save() -
How to programmatically create Django models and set their null attributes?
I have a spreadsheet of object types and their required attributes like this: |col 0|col 1|col 2|...|col n| type 0 | y | n | n |...| y | type 1 | y | y | y |...| y | type 2 | n | n | y |...| n | ...... | n | n | y |...| y | type n | y | n | n |...| n | How can I programmatically create these object models (and the corresponding forms), and set their null properties according to the spreadsheet? How can I then display the form objects with only required inputs? I saw this question but I think mine is different. I am not seeking to dynamically add model attributes. -
Django - pass dict from POST form
There is a from with various elements <input name='id' value='123'/> <input name='some_value' value='123'/> <!-- thing that i want--> <input name='array[key_1]' value='value_1'/> <input name='array[key_2]' value='value_2'/> <input name='array[key_3]' value='value_3'/> <input name='array[key_4]' value='value_4'/> </form> If i've been used PHP, array data will be collected in $_POST["array"] So the questions is, how to collect dict "array" in django views? -
Elastic Beanstalk fails on command 01_migrate
So basically, I transitioned from Heroku to AWS Beanstalk for my Django web application. I already had an existing database on Heroku Postgres and was able to use pg_restore to populate my AWS RDS Postgres Instance. Everything has worked fine until I made changes in Django which required me to run migrations (python manage.py migrate). So in my .ebextensions folder, I created a file called 01_django.config and put this information. option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "core.settings" PYTHONPATH: "/var/app/current:$PYTHONPATH" aws:elasticbeanstalk:container:python: WSGIPath: "core.wsgi:application" container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate --noinput" leader_only: true This gives me the error: 2022/11/04 03:32:33.664588 [INFO] Error occurred during build: Command 02_migrate failed 2022/11/04 03:32:33.666248 [ERROR] An error occurred during execution of command [app-deploy] - [PostBuildEbExtension]. Stop running the command. Error: container commands build failed. Please refer to /var/log/cfn-init.log for more details. In the error logs it tells me to look in cfn-init.log for more details, so I download the full logs from the AWS Console and open the file but it doesn't tell me more information. 2022-11-04 03:32:33,639 [ERROR] Unhandled exception during build: Command 02_migrate failed Traceback (most recent call last): File "/opt/aws/bin/cfn-init", line 176, in <module> worklog.build(metadata, configSets) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 137, in build Contractor(metadata).build(configSets, … -
django rest_framework using stored procedure
How can I use my stored procedure in django rest framework, let's say I have an add_item that insert product name and date_acquired select add_item(p_name,p_date_acquired) We have models.py # using RAW models Class Product(models.Model): name = models.CharField(blank=True, null=True) date_acquired = models.DateField(blank=True, null=True) What should I put in my serializer.py Something like this perhaps? what about my views class ClearanceItemSerialize(serializers.ModelSerializer): class Meta: model = Product fields = ['name', 'date_acquired' Please Help thank you -
Reverse for 'profile' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['profile/(?P<pk>[0-9]+)$'] n
this showing when i running server of django project i have try many thing but could not solve this -
Django Broken pipe when cluster version changed
I have the same API login code for my develop and stage versions. The staging server is with cluster 1.20 instead of 1.19 as like develop. I am not using Nginx we are using an HAProxy-based ingress controller. Django API can access the web without error using the ReactJS code but API shows 403 errors when accessing through postman. Here is the code: @csrf_protect @api_view(["POST"]) @authentication_classes((LoginAuthentication,)) @permission_classes((IsAuthenticated,)) def api_login(request): """Log in and retrieve tokens based on user name and password""" auth_header = request.META.get('HTTP_AUTHORIZATION') encoded_credentials = auth_header.split(' ')[1] # Removes "Basic " to isolate credentials decoded_credentials = base64.b64decode(encoded_credentials).decode("utf-8").split(':') username = decoded_credentials[0] password = decoded_credentials[1] user = authenticate(username=username,password=password) if user is not None: login(request,user) return _get_jwt_token(request.user) def _get_jwt_token(user): """Helper function to generate jwt tokens""" jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) exp_str = payload["exp"].isoformat() + "Z" token = jwt_encode_handler(payload) refreshToken = _get_refresh_token(user) return JsonResponse( {"token": token, "refreshToken": refreshToken, "exp": exp_str}, status=201 ) console output of develop [02/Nov/2022 10:41:06] "POST /accounts/api/login/ HTTP/1.1" 201 541 [02/Nov/2022 10:41:06] "POST /accounts/jwt_token/ HTTP/1.1" 201 541 [02/Nov/2022 10:41:06] "POST /accounts/get_csrf/ HTTP/1.1" 200 82 [02/Nov/2022 10:41:06] "POST /accounts/user_profile/ HTTP/1.1" 200 233 [02/Nov/2022 10:41:06] "POST /accounts/user_profile/ HTTP/1.1" 200 233 [02/Nov/2022 10:41:07] "POST /accounts/user_profile/ HTTP/1.1" 200 233 console output … -
Lazy page loading via Redis in Django project
There is a download page for about 5000 sql queries against a database (Postrgres). The team decided to apply the following algorithm to avoid 502 errors when multiple users load the page at the same time (using Redis): Create a task for an additional worker Connect via WebSocket to the page. (or use an AJAX request) While the request is running, the user sees the download window. When the worker completes the calculation, it will pass the result to the consumers The project uses django_rq. Are there ready-made solutions that perform this algorithm? Like a decorator? Also, if you have suggestions for optimizing such a number of requests, please suggest them. Used standard Django optimization tools to reduce the number of requests. -
How to cast django.db.models F to a String?
Note: working on expensive corporate legacy code and models that are not allowed to be changed What I'm trying to do: Combine two fields into one as a DateTime field. Model.py: from django.db import models class DateThing(models.Model): date = models.DateField() start_time = models.CharField("Start time", max_length=255) Viewset.py from datetime import datetime from django.db.models import F from django.db.models.functions import Concat from rest_framework import mixins, viewsets class ViewSet(viewsets.GenericViewSet, mixins.ListModelMixin): date_things = DateThing.objects.annotate( start=Concat( F("date"), Value(" "), datetime.strftime( datetime.strptime(str(F("start_time")), "%I:%M %p"), "%H:%M", ), Value("+00:00"), output_field=CharField(), ) ) ... Desired result: 2022-11-01 20:30:00+00:00 -
how to call a method in view.py from jinja2 template in Django
I am trying to execute a method which is views.py file a html template in django. beow is my views.py in an aplication def somemethod(**kwargs) #some stuff below is my template email.html {{somemethod(param1,param2,etc...)}} -
Django decorator throws error "object has no attribute 'session'"
I need a custom login check to be done, which looks at session attributes. However I am getting 'health_check' object has no attribute 'session'. The print inside health_check get method shows user object from session just fine. Here is the code def my_login_required(function): def wraper(request, *args, **kwargs): user = request.session.get('user') print(user) if user: return function(request, *args, **kwargs) else: return HttpResponseRedirect("/login") wraper.__doc__=function.__doc__ wraper.__name__=function.__name__ return wraper class health_check(APIView): @my_login_required def get(self, request): user = request.session.get('user') print(user) return JsonResponse({"status":"OK"}) -
Django custom authentication middleware error
Following this exact example from documentation and getting following error. I have required file in place as needed. https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#writing-an-authentication-backend 61, in load_middleware mw_instance = middleware(adapted_handler) TypeError: SettingsBackend() takes no arguments settings.py has following. MIDDLEWARE = [ ... 'myweb.middleware.example_authentication.SettingsBackend' ] -
Streamlit app inside django project at the same time
i'm kind of new to Heroku, but got a question in relation to dynos. My situation is as follows. I'm running on main application in django that runs the following dyno command "web gunicorn DJANGO_WEBPAGE.wsgi --log-file - ", and inside my main project there is a streamlit app that runs the following command "streamlit run geo_dashboard.py", but it seems i can't run both commands on the same dyno. 1.- Is there a way to accomplish this? 2.- Do they need to be on separate apps? 3.- In case of limitations do to being a free user, does the hobby plan covers it? I've tried running my procfile this way web: gunicorn DJANGO_WEBPAGE.wsgi --log-file - && web: sh setup.sh && streamlit run geo_dashboard.py Even though i get no errors, only the streamlit app appears leaving the django app shutdown. -
django bulletin board image total capacity limit or image total number limit
I'm making a bulletin board with django. I'm using the Summer Note Editor and I'm going to use aws3 as an image repository. If you post too many images for each post, I think there will be a lot of s3 charges Is there a way to limit the total capacity of each post or the total capacity of uploading summer note files? Or is there a way to limit the number of image uploads per post? I can limit the capacity of each image using the summer note setting -
Specify a default rendering method for a certain type in Jinja2
In Jinja2, how would you specify a default rendering method for a certain type? In particular, datetime? I found it quite annoying when rendering datetime values from Django. They look like 2022-11-04T00:00:00.987654+00:00. What was that T for, and why there was a plus + followed by 00:00. My users who lived on small islands for their entire life wouldn't understand. Aside from the formatting problem, Django gives UTC time objects. Always UTC, despite the TIME_ZONE in its settings module has been specified with a different value. I know I can use a filter thing like me.time_of_death|format_datetime. However putting it after every single datetime field sounds insane to me, and I don't want to be woken up in the midnight because of a datetime without that filter released on the previous day. Is it possible to make it default? -
Populate custom field in Django form
I would like users to have the ability to update their email address. I created a profile that has fields, but the email address is in the users table. I created a form that adds a custom form field and it works for update. However, I can't find a way to pre-populate this field on a REQUEST.GET. # forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('name', 'timezone') class ProfileUpdateForm(ProfileForm): email = forms.EmailField(max_length=254) class Meta(ProfileForm.Meta): fields = ProfileForm.Meta.fields + ('email',) # views.py @login_required @require_http_methods(["GET","POST"]) def profile_update_view(request): context = {} # Get the logged in users profile profile_object = Profile.objects.get(user=request.user.id) if request.method == 'GET': profile_form = ProfileUpdateForm(None, instance=profile_object) context["form"] = profile_form # how can I add User.objects.get(id=request.user.id).email to the custom field if request.method == 'POST': profile_form = ProfileUpdateForm(request.POST or None, instance=profile_object) context["form"] = profile_form if profile_form.is_valid(): try: # email address exists user = User.objects.get(email=profile_form.cleaned_data.get('email')) messages.error(request, 'Failed profile update. Email address already exists.') except: # email address available # get user object user = User.objects.get(id=request.user.id) user.email = profile_form.cleaned_data.get('email') # update user object user.save() profile_form.save() messages.success(request, 'Successful profile update.') return render(request, "profile.html", context) -
Implementing a reoccurring subscription based logic in Django
I have two models. A plan model which comprises of three Plans, and a Subscription model. A user is permitted to have only one active plan at a time. The logic is that when a user first subscribes to a plan, by default, the status will be pending. After the site admin confirms the subscription(deposit), he will toggle the active Boolean field, and automatically, the status will change to Confirmed. Now, where I have issues is with implementing what happens after the subscription has been confirmed. I will try explaining the logic as much as I can. A user is supposed to be receiving a daily profit till the plan expiries. Let me cite an example: Suppose User A subscribes to the basic plan. The basic plan has a daily percentage bonus of 10% and lasts for 7 days(duration). Now after the admin activates the subscription, the user is supposed to be receiving a daily profit of 10% of his investment for a duration of 7 days. Assuming he subscribes with $100.00, by the end of the first day, his balance should be $110.00, and so on. Then after the plan expiries, the status should automatically change to Expired, the … -
Django como passar argumntos para um receiver de um signal
Olá, segue uma explicação rapida de como passar atributos via Signal.connect() para um receiver de um siginal no django. Me deparei com esse probleminha a uns dias atrás pois precisava passar um json para ser salvo em um signal durante o evento "pre-save" do model. Como fazer? from functools import partial #Criar o objeto partial data = partial( signal_function, data=dados_pass, signal_duid="id do signal para nao ter replicação") #chamar o objeto criado dentro do connect pre_save.connect( data, sender=MeuModel, dispatch_uid="key_aditional_date", weak=False, ) #Criar a função que vai ser acionada no evento def signal_function(data, sender, instance, signal_duid, **kwargs): if signal_duid == "id do signal para nao ter replicação": instance.additional_data = {"user": data} É isso, qualquer duvida estou a disposição.Abraço. Olá, segue uma explicação rapida de como passar atributos via Signal.connect() para um receiver de um siginal no django. Me deparei com esse probleminha a uns dias atrás pois precisava passar um json para ser salvo em um signal durante o evento "pre-save" do model. Como fazer? from functools import partial #Criar o objeto partial data = partial( signal_function, data=dados_pass, signal_duid="id do signal para nao ter replicação") #chamar o objeto criado dentro do connect pre_save.connect( data, sender=MeuModel, dispatch_uid="key_aditional_date", weak=False, ) #Criar a função que … -
React & Next.js 13 OR Angular & Django
I am new to development and looking to build my first dashboard type app. I dont expect to do this in one shot and am going to iterate over time. Backend: I have a bunch of data from different environmental sensors that I want to be able to ingest into a database and correlate. My thought tis that the power of python will strive to do this best in the backend. Can a Javascript/Typescript backend perform at the same level as python backend? Frontend: Since this is a dashboard, being able to update data live is key. I like the simplicity I can see in react, but like the modularlity of Angular. Next.js 13 looks to have some more features to be able to support this idea as well now. For client vs. server side, my goal is serverside as much as possible to allow for users to be able to access the dashboard regradless of the processing of the end device. Other: Eventually I want to be able to open up the system to allow for plugins for data types as well as front end visualizations through modular "components". So not sure which would make this process easier in … -
Django Module Object is Not Callable Problem
I'm struggling to fix an error that doesn't allow me to access my /api/lead/ URL, as I keep getting an error "module object is not callable. Within my DjangoApp project, I have one other folder named api, and one other folder with the standard name of the project, which in my case is "DjangoApp". api/models.py : from django.db import models # Create your models here. class Lead(models.Model): name = models.CharField(max_length=100) email = models.EmailField() message = models.CharField(max_length=300) created_at = models.DateTimeField(auto_now_add=True) api/LeadListCreate.py : from .models import Lead from api import LeadSerializer from rest_framework import generics class LeadListCreate(generics.ListCreateAPIView): queryset = Lead.objects.all() serializer_class = LeadSerializer api/LeadSerializer.py : from rest_framework import serializers from .models import Lead class LeadSerializer(serializers.ModelSerializer): class Meta: model = Lead fields = ('id', 'name', 'email', 'message') api/urls.py : from django.urls import path from . import views urlpatterns = [ path('api/lead/', views.LeadListCreate.as_view() ), ] DjangoApp/urls.py : from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('api.urls')), ] -
Secure Websocket and https with Django [closed]
I am working with a Django development server in version 4.0.1 which uses an SSL certificate (https). The application uses websockets and there is the problem: it doesn’t work. Please note that the use of websockets works without SSL certificates. I’ve read that all you have to do is change “ws://” to “wss://” but that doesn’t seem to be enough. Do you have an idea? Thanks, MLP. -
How do I Filter a viewlist based on a selection made on a createview form? Django
I am learning how to use Python & Django. I don't have much experience, and this has been a huge learning process for me. Please forgive any ignorance in my question. I am designing a Django app and have a few relational tables created. My question involves only my first 2 models/forms/views. Here are my models ` class CustomerName(models.Model): #Fields company = models.CharField(max_length = 60, help_text = "Enter Customer Name",unique=True) def __str__(self): return self.company class ProgramName(models.Model): #Fields customer = models.ForeignKey("CustomerName",on_delete=models.CASCADE) program = models.CharField(max_length = 60, help_text = "Enter Program Name") def __str__(self): return self.program ` Here are my Views (Ive left out the customer add view since that works and I don't think its relevant) ` class ProgramAddView(CreateView, ListView): template_name = 'app/ProgramAdd.html' form_class = Programform model = ProgramName success_url = reverse_lazy('Part Number Add') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["qs_json"] = json.dumps(list(ProgramName.objects.values())) return context ` Here is the form ` class Programform(forms.ModelForm): class Meta: model = ProgramName fields = "all" class Customerform(forms.ModelForm): class Meta: model = CustomerName fields = ('company',) ` Here is the HTML app/ProgramAdd.html ` {% extends 'base.html' %} {% block content %} <h2>Program</h2> <form method="post" class = 'formarea'> <div id = 'formarea' class = 'formdiv'> {{ form.media.js … -
BooleanField Model not showing the default False value
I have a model class where the variable completed_application should default to False when creating a new user (to show that the user hasn't completed an application yet). However, by default when a new user is created it doesn't show as False in Django admin but '-' instead. models.py: class Completed(models.Model): class Meta: verbose_name_plural = 'Completed Application' user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) completed_application = models.BooleanField(default=False) admin.py: class Company(admin.StackedInline): model = Completed can_delete: False verbose_name_plural = 'Completed Application' class UserAdmin(UserAdmin): list_display = ('username', 'first_name', 'last_name', 'email', 'company', 'completed') search_fields = ('username', 'email',) inlines = [Company] list_filter = ('is_active',) fieldsets = ( (None, {'fields': ('username', 'password')}), (('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), (('Permissions'), { 'fields': ('is_active', 'is_staff', 'groups',), }), (('Important dates'), {'fields': ('last_login', 'date_joined')}), ) The red arrow in the first image above points to the Users admin panel for a newly created user. The second image shows the individual user in Django admin with the custom model added to that user. Other point to note: Checking the box and saving the user it shows True (as to be expected), but then unchecking the box and saving the user it eventually shows False and not '-'. Could someone explain what this '-' means … -
Partial update to extended user profile
I have a extension to user model in Django, adding multiple fields to the regular user profile. In order for the user to be able to change them, I have created a form that should be able to modify those fields but with no success... models.py class UserProfileModel(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) agency_name = models.CharField(max_length=255, null=True) license_number = models.CharField(max_length=10, null=True) phone = models.CharField(max_length=10, null=True) phone2 = models.CharField(max_length=10, null=True) fax = models.CharField(max_length=10, null=True) address = models.CharField(max_length=255, null=True) city = models.CharField(max_length=255, null=True) zip_code = models.CharField(max_length=10, null=True) about = models.CharField(max_length=255, null=True) # חפ pi_id = models.CharField(max_length=10, null=True) reason_pension = models.CharField(max_length=255, null=True) reason_policy = models.CharField(max_length=255, null=True) reason_gemel = models.CharField(max_length=255, null=True) reason_hishtalmot = models.CharField(max_length=255, null=True) def __str__(self): return str(self.user) class Meta: ordering = ('user',) forms.py class UserProfileChangeForm(forms.ModelForm): customer_name = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "שם לקוח", "class": "form-control" } )) labelwhite = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "", "class": "form-control" } )) smoker = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "מעשן", "class": "form-control" } )) ensurence_amount = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "ביטוח חיים", "class": "form-control" } )) ensurence_amount1 = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "00000", "class": "form-control" } )) disability_amount = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "נכות מתאונה", "class": "form-control" } )) class Meta: model = LifeEnsurenceModel fields = ('customer_name', … -
How to set a default time in Django ModelForm
I created a Django ModelForm. Here is the models.py file class Room(models. Model): available_from = models.TimeField() available_till = models.TimeField() Here is the forms.py file class RoomForm(forms.ModelForm): class TimeInput(forms.TimeInput): input_type = 'time' available_from = forms.TimeField( widget=TimeInput(), ) available_till = forms.TimeField( widget=TimeInput(), ) class Meta: model = Room fields = ['available_from','available_till'] I want to know how to set a default time to the form.