Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IIS django static files not showinvg
i try to deploy my Django app on IIS for work but is not serving my static files. i watched this tutorial: https://www.youtube.com/watch?v=APCQ15YqqQ0. Right now my Django app looks like this, the CSS is not appearing I added a virtual directory as well and have set the physical path to the static file in the project. In my my settings.py i have STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] I have no idea what i am missing. please tell me if you need more information. -
Design DB to calculate prize based on distance of cities
I am working on a side project to calculate the prize of the service based on the city distances. In my prize table I have values like below: CATEGORY DISTANCE VALUE Category A < 100 km 10EUR Category A From 100 km to 300 km 50 EUR Category A > 300 km 100 EUR My idea is to prepare a DB structure like below: CATEGORY DISTANCE_FROM DISTANCE_TO VALUE Category A 0 100 10 Category A 100 300 50 Category A 300 x 100 Is this the right approach? I am also wondering how to later get the correct value if for example distance is 150 km? The project will be build in Django, any help appreciated. -
Django login_required doesn't work with multiple gunicorn workers
So I have a project which contains multiple micro-services, the entry point is the Django micro-service(with user login & authentication). All other Apis are wrapped with the @login_required decorator by Django. I've deployed it using ngnix, gunicorn inside a kubernetes pod. Everything works fine with 1 worker(sync) but I obviously want multiple workers, so when I increase my number of workers and threads(gthread), it doesn't let me login redirects to login/?next=/login/5/. After spending some time, I figured out the following: Since the default value of keepalive of a worker is 2s, the worker closes connection and a new worker is assigned & since they don't share common memory,my session cookie isn't carried forward. I tried increasing the keepalive time to 10s , now it lets me login but if someone tried to login when the worker is about to expire(around 10s), same, doesn't login & redirects to login/?next=/login/5/. Another direction I found was about fixing the secret key as in this post, but I just using the default standard value which I even hardcoded in settings.py, but no luck. I'll attach my gunicorn config/logs below: config: ./gunicorn.conf.py wsgi_app: None bind: ['0.0.0.0:8000'] backlog: 2048 workers: 2 worker_class: sync threads: 4 worker_connections: … -
How to gain specific field value manually in django admin fieldsets
I'm overriding admin/includes/questions/fieldset.html to change the behavior of some fields using the JavaScript. In the orignal fieldset.html by django theres a loop to display the fields, But I want to pick the value of first field for some usecase. How can I do that {% for line in fieldset %} <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% if not line.has_visible_field %} hidden{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}"> {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %} {% for field in line %} <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} {% if field.is_checkbox %} {{ field.field }}{{ field.label_tag }} {% else %} {{ field.label_tag }} {% if field.is_readonly %} <div class="readonly">{{ field.contents }}</div> {% else %} {{ field.field }} {% endif %} {% endif %} {% if field.field.help_text %} <div class="help"{% if field.field.id_for_label %} id="{{ field.field.id_for_label }}_helptext"{% endif %}> {{ field.field.help_text|safe }} </div> {% endif %} </div> … -
The form for UpdateView for editing the user profile is not displayed. Django
I'm trying to make an UpdateView to edit user profile without pk or slug using get_object() with self.request.user. But when I run my settings, the form is not shown. Here is my code: urls.py: urlpatterns = [ path('settings/', UserSettings.as_view(), name='settings'), path('<slug:profile_slug>/', ShowUserProfile.as_view(), name='profile'), ] views.py: class UserSettings(LoginRequiredMixin, DataMixin, UpdateView): template_name = 'users/user_settings.html' form_class = UpdateUserForm def get_object(self, *args, **kwargs): return self.request.user def get_success_url(self): return reverse_lazy('profile', kwargs={'profile_slug': self.request.user.userpofile.slug}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) c_def = self.get_user_context(title='Settings') forms.py: class UpdateUserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'password') widgets = {'username': forms.TextInput(attrs={'class': 'form-control form-input form__input'}), 'password': forms.TextInput(attrs={'class': 'form-control form-input form__input'})} user_settings.html: <form class="form" method="post"> {% csrf_token %} {% for item in form %} <div class="row"> <div class="col-sm-4"> <label class="form__label" for="{{item.id_for_label}}">{{item.label}}: </label> </div> <div class="col-sm-8"> {{item}} </div> </div> <div class="form__errors">{{item.errors}}</div> {% endfor %} <button class="button" type="submit">Set settings</button> </form> It doesn't even throw an error. What I need to do? -
why django displaying inconsistant migration history error while migrating?
hope you are doing well, i am beginner to the django and python, encountered the error while practicing projects from the github which is the custom user model project. i have posted a code below. feel free to ask if you have any questions. i have posted a question in this StackOverflow website to find the solution to the issue. please solve the issue. Thanks a lot for your help. temp/settings.py """ Django settings for temp project. Generated by 'django-admin startproject' using Django 4.0.6. 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/ """ from pathlib import Path # 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-&ttc6c6nmvo(t0j-@0=ybd$61t(k#yo)*-e2%*5!xm@29+rfv=' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tempapp', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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 = 'temp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
How to properly bind a Django form?
I am working on a form that picks a Sale id and submits it to the server. When i submit it to the server a bind it using form = DeleteSalesForm(request.POST) and check it form.is_bound returns False. This is my views.py def delete_sales(request): if not request.user.is_authenticated: return redirect('/login') if request.method == 'GET': form = DeleteSalesForm() print("GET") return render(request, 'inventorymanagment/delete_sales.html', {'form': form}) form = DeleteSalesForm(request.POST) print("checking if form is valid", request.POST, form.is_bound, form) if form.is_valid(): form.delete_sale() # redirect return redirect('/') else: print("sale not deleted") # why is the form invalid? print(form.errors) return render(request, 'inventorymanagment/delete_sales.html', {'form': form}) Here is the traceback: [31/Aug/2022 15:38:36] "POST /delete_sales HTTP/1.1" 200 932 checking if form is valid <QueryDict: {'csrfmiddlewaretoken': ['q3aga7bySuscQ6bb9zrh3pFUlfoIoRoGQnHvQQ8LlbiEfUl1XDSGp2fk3nCj5KJk'], 'id': ['16']}> False <tr> <th><label for="id_id">Sale:</label></th> <td> <select name="id" id="id_id"> <option value="16">id: 16, iphone 6 quantity: 50 price: 30.00 day: 2022-08-31</option> <option value="17">id: 17, Iphone 8 quantity: 70 price: 80.00 day: 2022-08-31</option> </select> </td> </tr> sale not deleted why isn't the form validating? -
Python: Update dictionary with multiple variables?
I've got this code: def update_amounts(self): container = {} a = {'a': self.a_amount} if self.a_mount or self.a_amount is None else {'': ''} container.update(a) b = {'b': self.b_amount} if self.b_amount or self.b_amount is None else {'':''} container.update(b) c = {'c': self.c_amount} if self.c_amount or self.c_amount is None else {'':''} container.update(c) return container And I wanted to know if its possible to do the dict update more efficient than calling the update function three times? Thanks in regard! -
It is shown that value error.. how to figure it out?
@csrf_exempt def login(request): if 'email' in request.session: return redirect(home) if request.method=="POST": email = request.POST["emailOrPhone"] password = request.POST["password"] user=authenticate(email=email,password=password) if user is not None: request.session['email'] = email if (User.objects.filter(email=email).exists()): request.POST.get(User.objects.get(password).only()) if password==User.objects.get(password): return JsonResponse({'statuscode':200}) else: return JsonResponse({'statuscode':400,'message':'password mismatch'}) else: return JsonResponse({'statuscode':400,'message':'not enrolled'}) else: print('invalid credentials') else: return JsonResponse({'statuscode':200}) -
Converting a static HTML website into a fully fledged Django project
I am just getting started with Django. I have a situation where I have a project consisting of a large number of static HTML Pages compiled over time. Now I am in a situation to use a framework and I have opted for it. However I can't just write the whole project in Django because the large number of pages is being a problem for me and my team. As you know maintaining each one is a tedious task and not practical at all for me. So if anyone could suggest a tool or a script to convert entire static website into a Django project will save me a lot of time. Every solution is appreciated. -
Azure B2C : Error in the callback after the edit profile when it tries to get a new token
I try to implement an azure B2C authentication in Django. Unfortunately, there is not much documentation in Django on this topic. However, I managed to write the functions and views to get an id_token and store the user's information in the session. I wanted to integrate the edit profile with the specific authority. The page is perfectly redirected to update the user information. However, after the validation of the new data, I get an error message in the callback when I try to get a new token (function _get_token_from_code). {'error': 'invalid_grant', 'error_description': 'AADB2C90088: The provided grant has not been issued for this endpoint. Actual Value : B2C_1_signupsignin_20220810 and Expected Value : B2C_1_profileediting\r\nCorrelation ID: xxxxxxxxxxx nTimestamp: 2022-08-31 14:58:54Z\r\n'} So it implies the following error in the python execution : _store_user(request, result['id_token_claims']) KeyError: 'id_token_claims' However the new information of the user are correctly saved in the azure. Since I am newbee in this authentication process ? Do we need to generate a new token for the edit profile user flow ? Where does come from this mistake ? Here is the code in djnago : load_dotenv() def initialize_context(request): context = {} # Check for any errors in the session error = request.session.pop('flash_error', … -
How to compute cumulative sum of a count field in Django
I have a model that register some kind of event and the date in which it occurs. I need to calculate: 1) the count of events for each date, and 2) the cumulative count of events over time. My model looks something like this: class Event(models.Model): date = models.DateField() ... Calculating 1) is pretty straightforward, but I'm having trouble calculating the cumulative sum. I tried something like this: query_set = Event.objects.values("date") \ .annotate(count=Count("date")) \ .annotate(cumcount=Window(Sum("count"), order_by="date")) But I'm getting this error: Cannot compute Sum('count'): 'count' is an aggregate -
for loop in html gives me the same id
When I click the span on html I cant make variable span id with id="mylink-${i}" I couldn't get this with var mylink = document.getElementById("mylink-"+id) in javascript part. and also at onclick="theFunction(i)" console gives me i is not defined error but it should be defined because of {% for i in data %} i is one of the elements of data how can ı solve this <div class="row sideBar"> {% for i in data %} <div class="row sideBar-body"> <div class="col-sm-9 col-xs-9 sideBar-main"> <div class="row"> <a href= "{% url "start_chat" i.room %}" onclick="theFunction(i)" > <div class="col-sm-8 col-xs-8 sideBar-name"> <span class="name-meta" id="mylink-${i}"> {{i.name}} </span> </div> </a> </div> </div> </div> {% endfor %} </div> const rooms = JSON.parse(document.getElementById('data').textContent) function theFunction(id) { var mylink = document.getElementById("mylink-"+id) } -
Django date events
I have this model: class Prognose(models.Model): Benutzer = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) Lehrer_Vorname = models.CharField(max_length=255, null=True, blank=True) Lehrer_Nachname = models.CharField(max_length=255, null=True, blank=True) von_Datum = models.DateField(null=True, blank=True) Status = models.CharField(max_length=20, null=True, blank=True) Stunden = models.CharField(max_length=20, null=True, blank=True) bis_Datum = models.DateField(null=True, blank=True) Erstellt_Datum = models.DateField(null=True, blank=True) def __str__(self): return '{}'.format (self.Benutzer) The idea is to schedule an event or a task from one date to another date, and filter those out Like so Employee Name, from 2022-2-2 do this to 2022-3-3 else default (something else without date) and then when I user a filter, I want that it shows either past events within given date or default in future events if date is greater then the event date. Or the current event within given date I saw a lot of examples but have no clue how to implement it into my thing my view class Ansicht(AdminStaffRequiredMixin, LoginRequiredMixin, DetailView): model = User template_name = 'SCHUK/Ansicht.html' context_object_name = 'Ansicht' my template {% for Ansicht in Ansicht.prognose_set.all %} {{Ansicht.Lehrer_Vorname}} {{Ansicht.Lehrer_Nachname}} {{Ansicht.von_Datum}} {{Ansicht.Status}} {{Ansicht.Stunden}} {{Ansicht.bis_Datum}} {{Ansicht.Erstellt_Datum}} thought about ifs and so on but there must be something more efficient -
How to send email using smtp django rest framework after google policies are updated [closed]
I used the old techniques it did'nt work because gmail disabled Less secure apps features i am trying to send an verification email with django rest framework by smtp if there are any alternatives please help This is the old method in django to send email EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_USE_TLS=True EMAIL_HOST_USER=os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD=os.environ.get('EMAIL_HOST_PASSWORD') -
POSTing large number of many-to-many relatedfields in django rest framework
I am building an inventory-like system using Django Rest Framework where I have two models (Category and Location) that I want to allow Users to add to their Filters to keep an eye of them. #models.py class Category (models.Model): code=models.CharField(max_length=10, unique=True) name=models.CharField(max_length=50) class Location (models.Model): code=models.CharField(max_length=10, unique=True) name=models.CharField(max_length=50) class Filter (models.Model): categories = models.ManyToManyField(Category) locations = models.ManyToManyField(Location) name = models.CharField(max_length=50) user = models.ForeignKey(User) I am using ModelSerializers and built-in ModelViewSets. #serializers.py class UserFilterSerializer(serializers.ModelSerializer): categories = serializers.SlugRelatedField( queryset=Category.objects.all(), many=True, slug_field='code', allow_empty=False) location = serializers.SlugRelatedField( queryset=Location.objects.all(), many=True, slug_field='code', allow_empty=False) user = serializers.HiddenField( default=serializers.CreateOnlyDefault(default=serializers.CurrentUserDefault())) class Meta: model = UserTenderSelection fields = ['id', 'categories', 'locations', 'name', 'user'] #views.py class UserFilterView(ModelViewSet): permission_classes = [IsAuthenticated] serializer_class = UserFilterSerializer pagination_class = None def get_queryset(self): return self.request.user.filter_set.prefetch_related("categories", "locations").all() I would like the users to be able to CRUD their filters using REST methods. However, rather than using ids, I needed at some point to use the codes of Category and Location when both on GET responses and POST/PUT requests. e.g. //Example GET Response: { "id": 55, "categories": [ "88-9", "72-3", ], "locations": [ "BE0", "BE1", "DE12" ], "name": "Filter1" } //Example POST request: { "categories": [ "87-9", "77-1", ], "locations": [ "SP75", "DE20" ], "name": "Filter3" } My … -
Django httpResponse open pdf then print window in navigator
I'm running a django app in which i created a view to open a pdf file in the browser for printing purpose. Until this, everything works fine. For a better UX, i'm trying to automatically open the print window (specific to each computer). However, i'm struggling to do so. Aas long as the new window open a pdf but not a html file , i cannot insert JS in my code... Any idea to do so ? Here is my code (i deleted the intermediate steps where i combine some pdfs or add blank page for recto/verso printing...) class CombinePdf (View): def post(self, request, *args, **kwargs): response = HttpResponse(content_type='application/pdf') response['Content-Transfer-Encoding'] = 'binary' file = open("my_pdf.pdf", 'rb') # generate pdf in response try: file.write(response) except Exception as e: return e #open pdf in new window return response Thanks for your help ! -
how can i use socket.io in django for private chat?
I am working in Django and I want to create a chat application so can I use socket.io to private chat? -
How to render many to many field data in Django template
I am able to render list of all courses and list of topics corresponding to the courses in different templates. I need help to view list of all courses and when each course is clicked,a new page should show the list of associated topics models.py class Topic(models.Model): topic_name = models.CharField(max_length=200, null=True) topic_file = models.FileField(upload_to = "topic_file", blank=True, null=True) def __str__(self): return self.topic_name class Course(models.Model): course_name = models.CharField(max_length=200, null=True) course_image = models.ImageField(upload_to="images", blank=True, null=True) related_topic = models.ManyToManyField(Topic) def __str__(self): return self.course_name Views.py def view_course(request): course_list = Course.objects.all() context = {'course_list':course_list} return render(request, 'upskill/view_course.html',context) def course_topic(request,pk): course_topic_list = Course.objects.get(id=pk) var = course_topic_list.related_topic.all context = {'var':var} return render(request, 'upskill/course_topic.html',context) -
My website not responding to http using Elastic beanstalk
I have my domain name on route 53 and got the acm already I set up load balancer on beanstalk Port 80 http 80 Port 443 https 80 http Yet my site won’t respond -
Infinite loop process inside Django application
I need to make a process inside my django application that just after the application starts, it will randomly take one record from Products table (which contains f.e. name, price and rating) and set it into another table named SingleProduct. The process should run inside infinite loop and replace the single product inside SingleProduct table every 15 minutes. How can I do stuff like this? What should I looking for? What do I need it for? I want to display some random product from the database on my home page every 15 minutes. -
Django Throttle on Test Server
I am working on a project and i am using django restframework throttle it works well when using the server either on local or production but when i tries testing the endpoint using testcase it returns an error This is my configurations the default rest framework setting REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle', 'rest_framework.throttling.ScopedRateThrottle', ], 'DEFAULT_THROTTLE_RATES': { """ anon is for the AnonRateThrottle base on anonymous user user is for the UserRateThrottle base on logged in user ScopedRateThrottle this is just used to set custom throttle just like the authentication, monitor below """ 'anon': '100/min', 'user': '200/min', # the throttle is the amount of time a user can access a route in a minute 'authentication': '3/min', # used on route where the user is not logged in like requesting otp 'monitor': '3/min', }, 'DEFAULT_AUTHENTICATION_CLASSES': ( # currently setting the default authentication for django rest framework to jwt 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ), 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', } -
Django - Argument of AND must be type boolean, not type character varying
I have a model called Baksgewijs with a models.BooleanField called eindbaksgewijs and I try to on the page of the baksgewijs if eindbaksgewijs is True. Here is my model: class Baksgewijs(models.Model): name = models.CharField(max_length=64) description = models.CharField(max_length=512, blank=True, default="") date = models.DateField() peloton = models.ManyToManyField(Peloton) eindbaksgewijs = models.BooleanField(default=False) def __str__(self): return self.name My view for displaying a baksgewijs looks something like this: def display_baksgewijs(request, baksgewijs_id): baksgewijs = Baksgewijs.objects.get(id=baksgewijs_id) if Baksgewijs.objects.get(id=baksgewijs_id, eindbaksgewijs=True): print("This is true") return render(request, "baksgewijs/baksgewijs_pelotons.html", { "baksgewijs" : baksgewijs }) display_baksgewijs is shown from this url: path("<int:baksgewijs_id>", views.display_baksgewijs, name="baksgewijs") But when I display a baksgewijs, I get the following error: argument of AND must be type boolean, not type character varying Why can I not check whether or not eindbaksgewijs is True in the model? -
USSD menu response with Django not working
AM building a USSD application, in Django with this API https://documenter.getpostman.com/view/7705958/UyrEhaLQ#intro. I get the responses from the API and initialize the data to be processed. But I don't get the menu (MSG) to display on the user phone successfully. The error I get is invalid(empty) response. This is the response to the user’s request. The content provider should provide a response to the request in the same format. USERID = This is the ID provided by NALO to the client MSISDN = The mobile number of the user MSG =This is a mandatory parameter that holds the message to be displayed on the user’s phone MSGTYPE = This indicates whether the session should continue or be terminated (True/false) @csrf_exempt def ussd(request): if request.method == 'GET': html = "<html><body>Nothing here baby!</body></html>" return HttpResponse(html) elif request.method == 'POST': url = "https://99c9-102-176-94-213.ngrok.io/ussd" response_data = json.loads(request.body) code_id = response_data["USERID"] serviceCode = response_data["MSISDN"] type = response_data["MSGTYPE"] session_id = response_data["SESSIONID"] text = response_data["USERDATA"] msg = "" if text == "": msg = "Welcome To TEST Dev" elif text == "1": msg = "This is Test Two" payload ={ "USERID": code_id, "MSISDN": serviceCode, "MSGTYPE": type, "USERDATA": text, "SESSIONID": session_id, "MSG": msg, } headers = { 'Content-Type': 'application/json' … -
invalid literal for int() with base 10: b'31 11:15:47.294407' on Django
I have model like this when I created an item. it gives an error like this: invalid literal for int() with base 10: b'31 11:47:21.619913' from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Book(models.Model): name = models.CharField(max_length=255) writer = models.CharField(max_length=255) explanation = models.TextField(blank=True, null=True) creation_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) publication_date = models.DateTimeField() def __str__(self): return f'{self.name} - {self.writer}' class Comment(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='comments') owner = models.CharField(max_length=255) comment = models.TextField(blank=True, null=True) publication_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) rating = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) def __str__(self): return self.rating