Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix special characters with python?
I have this problem with the special characters "ANTÔNIO GONÇALVES". How can I fix? I've tried using 'coding utf-8' but it didn't work. -
Django list_display highest value ManyToMany Field
I want to know how I can display the "highest value" from my ManyToMany Field in the admin. This is my models.py file: class Personal(models.Model): lastname = models.CharField(max_length = 100) firstname = models.CharField(max_length = 100) degree = models.ManyToManyField('Degree') def __str__(self): return self.lastname class Degree(models.Model): name_degree = models.CharField(verbose_name = 'Degree', max_length = 200, blank = False) rank = models.PositiveIntegerField(default = 0) def __str__(self): return self.name_degree In my backend, I have created different types of Degree's, all with a "ranking". In my case, the highest degree you can have is "Doctoral Degree", with a rank of "6". So if a User is creating himself in "Personal" he will have the option to select all the Degree's he has achieved. But for my Personal list, I just to want to see the highest one, e.g. if the User selects "Bachelor's Degree" and "Master's Degree", the Personal list should only contain "Master's Degree", because 5 > 4. Someone with an idea on how my admin.py file should look like? class PersonalAdmin(admin.ModelAdmin): list_display = ('lastname', 'firstname', ) # 'degree' Big thanks in advance! -
django-tz-detect save timezone to user model
I want to automatically save a user's timezone to their profile after it has been detected by the django-tz-detect package. Use case: I have a simple app that allows users to sign up and reserve time slots. Features: As little overhead as possible for users. Simply sign up with a name and email address, then click a button to reserve a time slot. Admin user can send email reminders to users when their time slots are approaching. Problem: The email sent to users is not formatted by their local time zone, as django-tz-detect is only concerned with the current timezone of that session. How can I format times in the user's local timezone in the reminder email? -
How can I add a bank transfer service to my django app
I am working on a stock trading app in django. I need to be able to give users the ability to transfer money from their current account into their brokerage account. What is the conventional way of doing this? For example, how does a platform like Robinhood transfer money from user's current account to their trading account? I am aware of payment services such as stripe, but this seems more tailored for ecommerce. -
failed to solve with frontend dockerfile.V0
I am pretty new to Docker and trying to build docker image with plain python django but i have this error message [+] Building 3.0s (3/3) FINISHED => [internal] load build definition from Dockerfile 0.7s => => transferring dockerfile: 224B 0.0s => [internal] load .dockerignore 0.9s => => transferring context: 2B 0.0s => ERROR [internal] load metadata for docker.io/library/python:3.9 1.7s ------ > [internal] load metadata for docker.io/library/python:3.9: ------ failed to solve with frontend dockerfile.v0: failed to create LLB definition: unexpected status code [manifests 3.9]: 403 Forbidden Dockerfile FROM python:3.9 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system COPY . /code/ -
Django images not uploading
I am working on a blog project where I am able to upload profile picture for each logged in user. Those uploaded profile photos are saving my django files. But for uploading a blog with images its not loading or saving, keeps warning "This field is required". Views.py class CreateBlog(LoginRequiredMixin, CreateView): model = Blog template_name = 'App_Blog/create_blog.html' fields = ('blog_title', 'blog_content', 'blog_image',) def form_valid(self, form): blog_obj = form.save(commit=False) blog_obj.author = self.request.user title = blog_obj.blog_title blog_obj.slug = title.replace(" ", "-") + "-" + str(uuid.uuid4()) blog_obj.save() return HttpResponseRedirect(reverse('index')) Models.py class Blog(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='post_author') blog_title = models.CharField(max_length=264, verbose_name="Put a Title") slug = models.SlugField(max_length=264, unique=True) blog_content = models.TextField(verbose_name="What is on your mind?") blog_image = models.ImageField( upload_to='blog_images', verbose_name="Image") publish_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) def __str__(self): return self.blog_title Settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_DIR = os.path.join(BASE_DIR, 'media') # MEDIA MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' Create_blog.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title_block %} Write a Blog {% endblock title_block %} {% block body_block %} <h2>Start Writing:</h2> <form method="POST"> {{ form | crispy }} {% csrf_token %} <br> <button type="submit" class="btn btn-success btn-sm">Publish</button> </form> {% endblock body_block %} -
[Django Rest Framework]: How to additional phone_number field on Registration page?
I successfully created apis which can generate token on user login and register, also have a api page where i can display all the registered users (admin privileges required). But im not able to add a additional field like phone number on my register page. I need a phone number field as well on the registration page. Currently it has firstName, lastName, email and password. Models.py from django.db import models from django.contrib.auth.models import User from phonenumber_field.modelfields import PhoneNumberField class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_profile') phone_number = PhoneNumberField(blank=True, null=True) def __str__(self): return str(self.user) Serializers.py from rest_framework import serializers from django.contrib.auth.models import User from rest_framework_simplejwt.tokens import RefreshToken from .models import Profile class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' class UserSerializer(serializers.ModelSerializer): firstName = serializers.SerializerMethodField(read_only=True) lastName = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', 'username', 'email', 'firstName', 'lastName'] def get_firstName(self, obj): firstName = obj.first_name return firstName def get_lastName(self, obj): lastName = obj.last_name return lastName class UserSerializerWithToken(UserSerializer): token = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', 'username', 'email', 'firstName', 'lastName', 'token'] def get_token(self, obj): token = RefreshToken.for_user(obj) return str(token.access_token) Views.py from django.shortcuts import render from django.contrib.auth.models import User from .models import Profile from rest_framework.decorators import api_view, permission_classes … -
Dynamic Templates in Django Views
I am wondering whether it is possible to insert template names dynamically into Django views from urls.py. That is, suppose I have an app whose entire purpose is to serve as a container for various static landing pages. The plan is to create this app and have various entries in its urls.py correspond to paths to various landing pages. Each page would have a separate .html correspond to it. The question is whether one could get away with writing only one (class-based or other) view for all of these templates or would there need to be a view for each page? Django version 2.1-2.2 P.S. If there is an alternative, laconic way of accomplishing something similar, I am all ears. -
How to count clicks of a link and store in database(Django)?
How do I edit this code to count the times the "Link" was clicked and add this to the database model "T_shirt" in a new column? HTML <ul class="products"> {% for v in owner_obj %} <div class="container"> <a href={{ v.Link }} target="_blank" rel="noopener noreferrer"> <img src={{ v.Images }} width="150" height="150"> </a> <figcaption> {{ v.Titles }} </figcaption> <figcaption> <b>{{ v.Prices }} </b></figcaption> </div> {% endfor %} </ul> Models.py class T_shirt(models.Model): Images = models.ImageField() Titles = models.CharField(max_length=250, primary_key=True) Prices = models.CharField(max_length=250) Link = models.CharField(max_length=250) -
DRF + React.js Best Security Practise
Hello everyone i'm building a web-app with Django rest framework and react js. Back-end and front end are completely decoupled its pretty basic.React project created with npm create-react-app and DRF API is pretty standard i will use it to provide the info that front-end needs .So its both my resource and auth(which holds the users info and issues tokens etc.)server what is the best practice in 2021. bonus question I'm trying to implement Authorization code with PKCE and OIDC with django-oauth-toolkit.A high level of steps to do would be nice . for example i register an application on the admin interface and to get code http://127.0.0.1:8000/o/authorize/?response_type=code&client_id=<client_id>&redirect_uri=<redirect_uri> and i get an url with the grant code but only i'm logged in as admin user. (what good is that? I think i'm missing something here.) Also any help or information regarding the subject is much appreciated -
Setting a default value for an instance in django views
I am tracking histories on my models using simple history and this works fine.Problem is , some changes made to the models are done by the application and so do not have a history_user, thus return null. The result I get form the api in this case is as below. I am trying return the id of the history_user for those that have one and set the ones that are null to a specific id, say 1.But am struggling a bit. I have added a function get_history_user to return 1 in case the value is null .But the code just runs and returns the initial result with no errors.Can this work as it is? What am I doing wrong? { "invoice_history": [ { "history_id": 452, "history_user": 8, "history_type": "+", "history_date": "2021-04-28T13:22:16.045294+03:00", "id": 919 }, { "history_id": 451, "history_user": null, "history_type": "+", "history_date": "2021-04-28T13:22:15.572174+03:00", "id": 918 }, { "history_id": 450, "history_user": null, "history_type": "+", "history_date": "2021-04-28T13:22:13.477117+03:00", "id": 917 } ]} Views.py class AllHistoryView(APIView): def get(self, request, format=None): all_invhist = Invoice.history.all() serializers = InvoiceHistorySerializer(all_invhist, many=True) try: result = {} res = serializers.data result = res invoice_history = result[0:3] def get_history_user(invoice_history): history_user = invoice_history["history_user"] if isinstance(history_user, (float, int)): return history_user return 1 # … -
How to solve Django forms inline radio button bullet point problem
I'm try to use Django forms with radio buttons but if I like to use it as inline class I have bullet points in the row. How could I hide them? This is the result: models.py class Attitud(models.Model): def __str__(self): return str(self.user_name) class question(models.IntegerChoices): Nem_jellemző = 0 Néha_jellemző = 1 Nagyon_jellemző = 2 user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) att_v001 = models.IntegerField(verbose_name="Kérdés 1", default='', null=True, blank=False, choices=question.choices) forms.py class AttitudForm(forms.ModelForm): class Meta: model = Attitud fields = ['att_v001'] widgets = { 'att_v001': forms.RadioSelect(attrs={'class': 'form-check-inline ml-5'}) } html {% extends 'stressz/base.html' %} {% block body%} <div class="container w-75"> <div class="display-4">Helló {{ user.get_short_name}}! </div> <p class="text-justify">Kérlek, hogy az alábbi kérdések esetében válaszd ki, hogy melyek a rád leginkább jellemző kijelentések. </p> </div> <form method = "POST"> <div class="container w-75 bg-light rounded-3 pt-3"> <div class="form-group"> {% csrf_token %} {{ form.as_p }}<br> </div> <button class="btn btn-large btn-primary" type="submit">Mentés</button> {% comment %} {{ form.att_v001|crispy }} {% endcomment %} {% endblock %} -
Prevent Authenticated Users from accessing the inbuilt login form in djagno
I'm using Django's default login form from within a custom template.However,once a user logs in using this form,they can still go back to the login form.Now,I'm aware of a method to prevent something like this from happening: decorators. However,these decorators wont work on the way I'm rendering the login view.Have a look at the urls.py : from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns=[ path('',auth_views.LoginView.as_view(template_name='main/login.html')), path('home',views.home,name='home') ] Normally,decorators are imported within views.py and called right above the view function.This can't be done here. I dont know whether it will help,but here's the form part of 'main/login.html': <form method="POST" class=""> {% csrf_token %} <div class="form-group"> {{ form.username.label }}: {{ form.username }} </div> <div class="form-group"> {{ form.password.label }}: {{ form.password }} </div> <div class="form-group"> <input type="submit" class="login-input btn btn-warning" value="Login!" /> </div> </form> Thank you very much! -
Django FormViews displays dropdown menu instead of char- and textfield
I'm new to Django and I'm trying to use the FormViews but when I display the view it looks fine except the fields with a ForeignKey (companyAddress and companyContactInformation). Instead of creating a Char- and Textfields for each variable it just makes a dropdown field. I've looked into formsets, inline_formsets and model_formsets but can't seem to figure it out. from django.db import models from django.forms import ModelForm class address(models.Model): streetName = models.CharField(max_length = 45) houseNumber = models.CharField(max_length = 25) postalCode = models.CharField(max_length = 4) region = models.CharField(max_length = 45) def __str__(self): return '{} {} {} {}'.format(self.streetName, self.houseNumber, self.postalCode, self.region) class contactInformation(models.Model): phoneNumber = models.CharField(max_length = 11) email = models.CharField(max_length = 100) mainContact = models.CharField(max_length = 50) def __str__(self): return '{} {} {}'.format(self.phoneNumber, self.email, self.mainContact) class company(models.Model): companyName = models.CharField(max_length = 145) companyAddress = models.ForeignKey(address, on_delete = models.CASCADE) description = models.TextField() companyContactInformation = models.ForeignKey(contactInformation, on_delete = models.CASCADE) websiteURL = models.CharField(max_length = 100) relationToDjango = models.TextField() def __str__(self): return '{} {} {} {} {} {}'.format(self.companyName, self.companyAddress, self.description, self.companyContactInformation, self.websiteURL, self.relationToDjango) class addressForm(ModelForm): class Meta: model = address fields = '__all__' class contactInformationForm(ModelForm): class Meta: model = contactInformation fields = '__all__' class companyForm(ModelForm): class Meta: model = company fields = ['companyName', 'companyAddress', 'description', … -
can anybody help me to run this django github project in window?
I used these steps to run this projects: downloaded and extracted and opened with vscode created virtual env using virtualenv test after django installation pip install -r requirements.txt 4)after successfully installation of requirements showing not found two modules celery and dotenv The link of Github-project is given below: https://github.com/MicroPyramid/opensource-job-portal -
Celery Beat sending tasks on startup (before the scheduled time)
I have a celery beat schedule: CELERY_BEAT_SCHEDULE = { "test-task": { "task": "myapp.tasks.test_task", "schedule": crontab(hour=20), # Should execute at 8pm UTC! } } And when I execute the beat instance, with celery --app myapp beat --loglevel DEBUG The celery beat instance automatically sends the task to the broker: [2021-05-03 14:12:04,022: INFO/MainProcess] Scheduler: Sending due task test-task (myapp.tasks.test_task) Is there a way to prevent it? The task should only be executed at 8pm and never before that time. -
Critical Section across multiple EC 2 Instances
I have a code hosted on two different EC2 servers, and it might happen that the given code can be executed simultaneously on two different machines for certain set of variables. It will be ok for me if if they execute one by one. For .e.g my current sequence at two machines(A, B) runs like this, where CS gets executed simultaneously on both machines, depending on two conditions (say condition1, condition2) if condition1 and condition2 A1 B1 A2 B2 "CS" "CS" A3 B3 But what I am trying to do is something like: if condition1 and condition2 A1 B1 A2 B2 "CS" A3 "CS" B3 My code is hosted on Django. What can I do to prevent simultaneous execution. -
Django chart.js multi axis line chart
Hi Guys I have inspired from this Fiddle example to try to create a similar multi axis line chart in my django project. I have in my views : class dashboard(TemplateView): template_name = 'users/dashboard.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['qs'] = DummyData.objects.all() data = DummyData.objects.all() years=[] for i in range(data.count()) : if data[i].year not in years : years.append(data[i].year) context['years'] = years return context in in my dashboard.html : {% extends 'users/base.html' %} {% load static %} {% block content %} <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- semantic UI --> <link rel="stylesheet" type='text/css' href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.14/semantic.min.css"> <!--Chart js--> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" integrity="sha256-Uv9BNBucvCPipKQ2NS9wYpJmi8DTOEfTA/nH2aoJALw=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css" integrity="sha256-aa0xaJgmK/X74WM224KMQeNQC2xYKwlAt08oZqjeF0E=" crossorigin="anonymous" /> <!-- jQuery --> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $(document).ready(function (){ var ctx = document.getElementById('myChart'); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for year in years %} '{{year}}', {% endfor %}], datasets: [{% for item in qs %} { label: '{{item.site}}', yAxisID: '{{item.site}}', data: [100, 96, 84, 76, 69] , {% endfor %} ] }, options: { scales: { yAxes: [{ id: 'A', type: 'linear', position: 'left', }, { id: 'B', type: 'linear', position: 'right', ticks: { max: 1, min: 0 } }] } } … -
django - template does not exists at /
I'm starting a new Django project, but straight away I can't set up the correct templates directory path. this are my settings.py: import os TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... ], }, }, ] I have a very simple view in the project folder: def dashboard(request): context = { } template_name = 'dashboard.html' return render dahsboard.html is located in BASE_DIR/templates/dashboard.html. Pretty straight forward, but still I get the Error: "TemplateDoesNotExist at / dashboard.html" -
my python path for new env does not run the code , while mu main python path run it as normal
while I am testing some mediapipe functions and modules on my windows PC I noted that when I run any thing on my main python path its fine but , if I run it on the new env path some functions does not work this error -->(FileNotFoundError: The path does not exist.) appears ''' when I comment this on my env path I works fine but if I uncomment those two lines FileNotfoundError #appears import mediapipe as mp mp_holistic = mp.solutions.holistic holistic = mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) print("any_thing") print(mp_holistic) print(holistic) ''' enter image description here enter image description here -
Set value of a form class field
# forms.py class AvatarForm(forms.ModelForm): class Meta: model = Profile fields = ('avatar', 'user', 'banner', 'bio') def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(AvatarForm, self).__init__(*args, **kwargs) self.fields['avatar'].widget.attrs = { 'class': 'd-none', 'accept': 'image/*', } self.fields['user'].widget.attrs = { 'class': 'd-none', } self.fields['banner'].widget.attrs = { 'class': 'd-none', } self.fields['bio'].widget.attrs = { 'class': 'd-none', } # set the value here, something like this self.fields['user'] = self.user self.fields['bio'] = str(Profile.objects.filter(user=self.user).first().bio) self.fields['banner'] = str(Profile.objects.filter(user=self.user).first().banner) # views.py def main(request, username): form = AvatarForm(request.POST or None, request.FILES or None) if request.is_ajax(): if form.is_valid(): form.save() ... // js file var formData = new FormData(); formData.append('croppedImage', blob); $('.cropper-container').remove(); $.ajax($`/{${'#auth_username'}}/`, { method: "POST", data: formData, processData: false, contentType: false, success: function () { $('.avatar-container-wrapper').load(location.href + ' .avatar-container'); }, error: function () { } }); The only thing I want to upload is the avatar field, rest other fields must have a default value that I want to set in the forms.py file itself. How to achieve this.. The other fields are part of the Model but the only field I want to change is avatar. Any help is appreciated. Thank you! -
Patching Django FileSystemStorage location does not take effect [putest]
I have a simple model as such: #models.py from django.core.files.storage import FileSystemStorage LOCATION = 'old_location' class FileArchive(models.Model): file = models.FileField(storage=FileSystemStorage(location=LOCATION)) I have a view through which I populate the mentioned model and call .save(). My aim is to have a functional test to try to upload a file and assert that the file exists on the provided (patched) LOCATION. The problem is no matter how I patch the LOCATION, which is located in my models.py, the test still uses the hard-coded location in my model. Here are the ways I tried to patch LOCATION. Some of the ways I tried to patch the LOCATION attribute: from . import models def test_uploaded_file_is_stored(monkeypatch): monkeypatch.setattr(models, 'LOCATION', 'new_location') ... Another way: def test_uploaded_file_is_stored(mocker): mocker.patch.object(modesl, 'LOCATION', 'new_location') ... Another way: from unittest.mock import patch def test_uploaded_file_is_stored(mocker): with patch('filestorage.models', 'LOCATION', 'new_location') ... I'm guessing I am patching the wrong place. Any ideas? -
is there a method to run javascript only after loading page url?
html : <li><a href="{% url 'list_article' %}"> article</a></li> i want to execute javascriptcode only after the href i.e after going on list_article url : var rules = $('#builder').queryBuilder('getRules'); liste_rules=[{"id":"source","field":"source","type":"string","input":"text","operator":"contains","value":"google"}] liste_rules={"condition":"AND","rules": liste_rules}; $('#builder').queryBuilder('setRules', liste_rules); $('#FormQueryBuilder').submit(); -
Django Channels 3.0 - different middleware for different websocket routes
I am currently experiencing a conundrum. I am attempting to implement a inter-device communication/signalling system. I am attempting to tackle this via WebSockets (Django Channels and Consumers), as real-time event handling is important for my use case. I would like to be able to apply authentication middleware to only certain WebSocket protocol URLs (specific Consumers), allowing others (like registration and login via JWT) to occur without asking for authentication. The documentation covers a root-level ProtocolTypeRouter and encourages developers to wrap an ASGI application (like a URLRouter) in an authentication middleware stack. However, the end result is that all of the "websocket" protocol requests are forwarded to this middleware. What I would like to do, is somehow split the handling of websocket protocol requests based on their URL. Ideally, to give ProtocolTypeRouter two URLRouters, one wrapped with the middleware and one not. Like so: device_handling_service/urls.py from channels.routing import URLRouter from django.urls import re_path from .consumers import IoTRegisterConsumer,\ IoTLoginConsumer,\ IoTPollConsumer websocket_needs_auth = URLRouter([ re_path(r"^$", IoTPollConsumer.as_asgi()) ]) websocket_no_auth = URLRouter([ re_path(r"^register/$", IoTRegisterConsumer.as_asgi()), re_path(r"^login/$", IoTLoginConsumer.as_asgi()), ]) asgi.py import os from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import device_handling_service.urls from .middleware import JWTAuthMiddlewareStack os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'IoTHub.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter([ JWTAuthMiddlewareStack(device_handling_service.urls.websocket_needs_auth), … -
IntegrityError: null value in column "is_approved" violates not-null constraint
Firstly , i was told to add a field to my model to help the admin approve, disapprove or pend products before they can be seen on the website. So, i added class Product(models.Model): ...there are some fields here... is_approved = models.BooleanField(default=False) to my product model, did the routine migrations, edited the serializer, views,urls,tested it and pushed to microsoft azure. 2nd, i had another instruction to change the same field to approval_status STATUS = [ ('0', 'Pending Approval'), ('1', 'Approved'), ('2', 'Rejected') ] class Product(models.Model): ...there are some filed here... approval_status = models.CharField( choices=STATUS, default='0', max_length=2 ) after deploying, i have this error IntegrityError at /marketplace/create_product/ null value in column "is_approved" violates not-null constraint DETAIL: Failing row contains (620, , , 2.00, FTF, 0, PR, , , , 113, 2021-05-03 11:38:28.57937+00, null, 0). i am suspecting the server database couldn't replace the is_approved field with approval_status, but rather included it, and hence trying to return that value. i have am expecting 13 fields but 14 are been returned Kindly help me with ideas to solve the error. my model class Product(models.Model): owner = models.ForeignKey( 'Accounts.BusinessInfo', on_delete=models.CASCADE ) name = models.CharField( max_length=100, blank=True, ) description = models.TextField( blank=True ) price = …