Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How does the Django setting of letting it know about your app really work?
I've been learning django for a few weeks , but i still cant fully understand how some of the settings really work,like the most basic one that when i create a new app called 'base' inside my django project then i should let django know about my app so i write like as most of the people do 'INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base.apps.BaseConfig', ]' but if i write just only my app name 'base' , it still works , so can someone tell me what is the difference between this two? 'INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base', ]' -
I need to get the value of the field that we enter in the form and immediately take action on it
I need to get the value of the field that we enter in the form (in this case, these are the days of reservation) and immediately calculate the cost of the reservation based on it And the problem is that I don’t understand how to get the value of these very fields (so this is not QuerySet request, and not accessing the database) This is my views: def booking(request): error = '' if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): booking = form.save(commit=False) booking.user = request.user booking.sum = #create sum function form.save() return redirect('account') else: error = 'Форма не корректна' form = BookingForm() context = { 'form': form, 'error': error } return render(request, 'bookings/booking.html', context) And this is models: class Booking(models.Model): startdate = models.DateField('Startgdate') finishdate = models.DateField('Finishdate') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) sum = models.PositiveIntegerField('Sum') fullname = models.CharField('Full name', max_length=50) pnumber = models.PositiveBigIntegerField('Phone number') def __str__(self): return self.fullname class Meta: verbose_name = 'Booking' verbose_name_plural = 'Bookings' thanks in advance -
How to return a folder in django views for using it in nginx proxy_pass?
I have 1 main server, where django and html with css, js located. While I am also have proxy server, that contains only nginx file that proxy_pass to django main server(by domain name) and receive site html code and another static. Here is my nginx file: server { server_name 11.111.111.111; index index.html location / { proxy_pass http://example.com/api/v1/render/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Photo $scheme; } } And after this I have 404 error. What I am need to do in django view /api/v1/render to return a folder with index.html, css and js scripts, that would be shown on 11.111.111.111 url? It also hasn't traces, that proxy_pass really works, because main server don't receive any requests. Thanks for help. -
how to use ccextractor with python?
I'm working on a django application to generate subtitles for videos. I'm required to use only ccextractor for this. I have figured out a way to use it using wsl: code However, it returns errors when I run it in other systems, since not everyone has ubuntu configured. Looking for a way to do this without using wsl. Any help is appreciated. -
Django admin file upload button not clickable
I was building an app and had the image upload section working previously, however, 2 weeks on in the project for some reason the upload file button in Django admin is no longer doing anything when clicked. I can't work out what is blocking it as it's in the admin, Any suggestions? This is for any of the apps in the project. This is the admin.py from django.contrib import admin from desire import models admin.site.register(models.Desire) admin.site.register(models.RelatedProduct) from django.contrib import admin from django.contrib.auth.admin import UserAdmin from account.models import Account class AccountAdmin(UserAdmin): list_display = ('email','username','date_joined', 'last_login', 'is_admin','is_staff') search_fields = ('email','username',) readonly_fields=('id', 'date_joined', 'last_login') filter_horizontal = () list_filter = () fieldsets = () admin.site.register(Account, AccountAdmin) settings BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ # my APPs 'personal', 'account', 'ckeditor', 'ckeditor_uploader', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'bootstrap4', 'fontawesome', 'cropperjs', 'django.contrib.humanize', ] AUTH_USER_MODEL = 'account.Account' # TODO: ADD THIS LINE. AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.AllowAllUsersModelBackend', 'account.backends.CaseInsensitiveModelBackend', ) 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', ] DATA_UPLOAD_MAX_MEMORY_SIZE = 10485760 STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'media'), ] STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn') MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn') TEMP = os.path.join(BASE_DIR, 'media_cdn/temp') BASE_URL = "http://127.0.0.1:8000" -
Inline form validation based on Parentform - Django Admin
Below is my admin form Class RequestedAreaInilne(admin.StackedInline): model = RequestedArea fields = ("area", "building") class BuildingAdmin(admin.ModelAdmin): fields = ("special_access", "user_id", etc ....) inlines = (RequestedAreaInline,) While saving the BuildingAdmin form I need to validate inline form (ie RequestedAreaInilne). Validation should happen based on the value from the BuildingAdmin form field . To add more information , special_access of the BuildingAdmin is boolean field(True or False). If the user selection is True , I want to check if they have entered value for RequestedAreaInline. If it is not entered I need show them a message that "You should enter data for this" I tried doing the validation in save_formset(). But I am not getting inline field. How can I validate the inline formset based on parent form -
How SQL query Case and When works in django ORM?
I have a SQL query and when writing in Django ORM it returns an error. But the SQL query works perfectly on MySQL Command Line Client. Would anyone please explain the error or working of CASE and When in Django ORM? SQL query:- SELECT CASE WHEN LENGTH(au.first_name) < 1 THEN au.username ELSE concat(au.first_name,' ',au.last_name) END AS fullname FROM rewards_usercard ru RIGHT JOIN auth_user au ON ru.user_id = au.id; Django Models code:- queryset = UserCard.objects.annotate( full_name = models.Case( models.When(condition=models.Q( models.lookups.LessThan(models.functions.Length('user__first_name'),1) ), then='user__username'), default = models.functions.Concat('user__first_name', models.Value(' '), 'user__last_name'), output_field=models.CharField() ) ) Error:- cannot unpack non-iterable LessThan object -
Overriding create() method in the model manager doesn't do anything
I have a model employee, and while creating an instance I want to automatically set their email to "<first_name>.<last_name>@company.com". So, I wrote a manager to do the pre-processing: class EmployeeManager(models.Manager): def create(self, **kwargs): name = kwargs['first_name'] surname = kwargs['last_name'] kwargs['email'] = f'{name}.{surname}@company.com' return super(EmployeeManager, self).create(**kwargs) class Employee(models.Model): first_name = models.CharField(null=False, blank=False, default="employee", max_length=255) last_name = models.CharField(null=False, blank=False, default="employee", max_length=255) position = models.CharField(null=False, blank=False, default="SDE", max_length=255) email = models.EmailField(null=False, default="employee@company.com", unique=True) phone = models.CharField(null=False, blank=False, default='1234567890', max_length=10, validators=[MinLengthValidator]) slack_id = models.UUIDField(null=False, blank=True, default = uuid.uuid4) active = models.BooleanField(default=True) objects = EmployeeManager() def __str__(self) -> str: return self.email However, when I am creating an instance of this model using the admin interphase, the email is set to the default value (employee@company.com) and not what I am feeding it in the new create() method. Why is this happening? -
I this able to convert into dict of key:value pairs
current data [{'product_id': 446, 'available_stock': 959}, {'product_id': 447, 'available_stock': 1004}, {'product_id': 445, 'available_stock': 1021}, {'product_id': 396, 'available_stock': 6}] required output: {446:959, 447:1004, 445:1021,396:6} -
The view Manager.views.add_student_view didn't return an HttpResponse object. It returned None instead
I am trying my first Django project and practicing ORM. I am just trying to create a model form using Django's Model form framework. Somehow my form is not rendering and it is rendering as None. Can someone help? Here is the github link to my project: https://github.com/henselwilson/LibManager/tree/master Error Screenshot -
Cloudinary Private type for django
Cloudinary is working fine with Django but not sure how to change all the file types to private? Apparently i can define type but where do I do that? The default file storage is defined in setting DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' Thank you in advance. -
Django - how do i force a user to change password on their first login using the last_login field of django.contrib.auth
Im using the django.contrib.auth. The code below is the working login function in my views.py #function based def user_login(request): if request.method == "POST": username = request.POST['login-username'] password = request.POST['login-password'] user = authenticate(request, username = username, password = password) if user is not None: login(request, user) return redirect('dashboard') else: return render(request, 'authenticate/login.html', {}) else: return render(request, 'authenticate/login.html', {}) Below is my attempt to check whether if the last_login is NULL. If so, redirect the user to the change-password page. It logs the newly created user (with NULL in the last_login field) but it does not redirect to the change-password page. I have tried changing the placement of the if statement. How do i correctly do this? def user_login(request): if request.method == "POST": username = request.POST['login-username'] password = request.POST['login-password'] user = authenticate(request, username = username, password = password) if user is not None: if user.last_login == NULL: login(request, user) return redirect('change-password') else: login(request, user) return redirect('dashboard') else: return render(request, 'authenticate/login.html', {}) else: return render(request, 'authenticate/login.html', {}) -
Heroku Deployment Error: ModuleNotFoundError: No module named 'msilib'
Can someone please tell me how to resolve this error so I can deploy my app on Heroku? Here's my requirements.txt file: asgiref==3.5.2 dj-database-url==1.0.0 Django==4.1.1 django-extensions==3.2.1 django-on-heroku==1.1.2 gunicorn==20.1.0 psycopg2==2.9.4 psycopg2-binary==2.9.4 python-decouple==3.6 python-dotenv==0.21.0 sqlparse==0.4.2 tzdata==2022.2 whitenoise==6.2.0 When I run the instructions 'heroku run python manage.py migrate' at the command line I get the following error: from msilib.schema import AdminExecuteSequence ModuleNotFoundError: No module named 'msilib' -
nvim pyright issue with django BigAutoField
I am using nvim with pyright and I have this error, I use Coc picture -
I need to test this in django
this is my code, and already done testing others but this one, I do not know yet -
django 4.1.1 redirect is not working if request.method=='POST'
I have tried to implement redirect in django 4.1.1 views. Please find the following code. redirect is working def customer_registration(request): return redirect('customer_login') redirect not working def customer_registration(request): print("ASFADFAd") if request.method == 'POST': return redirect('customer_login') return render(request, 'registration/registration.html') Can anyone help what is the problem, I have already gone through the internet none of the solutions working. Please help me. -
Searching for JSON in Django
I was able to import my data.json into Django after some time. Right now when a request is sent, the view.py function spits out the whole data.json file. I want to create a view.py function that only returns the results of a search request that was submitted and not the whole data.json. If I search for apple, I want the definition for apple to be returned from within data.json. I don't even know what I need to do. Do I convert the data.json file into SQL or python dictionary? Do I convert data.json into a model? The data.json files doesn't specify keys or values. views.py def searchbar(request): if request.method == 'GET': file_path = os.path.join(os.environ.get('HOME'), 'data.json') with open(file_path, 'r') as f: context = {"file_path": f} return render(request, 'movies/searchbar.html', context) searchbar.html {%block content%} {% for i in file_path %} {{i}} {%empty%} There is nothing here {%endfor%} {%endblock content%} home.html <form action ="{% url 'searchbar' %}"method="get"> <input type="text" name="search"/> <button type="submit"> Search</button> </form> data.json contents in searchbar.html when search is pressed: -
Is there a way to disable django models and auth?
I newie in Django but I really like it and I have to work with raw SQL and I want to disable all django apps and use only with rest framework. I tried it but it doesnt work and I want to know if there is any way to disable Django models and auth and that things. -
Django forms not returning result or errors
I am trying to use a Django form for a login page, but the form is returning False whenever I call form.is_valid(). I tried to print the errors in the console and in the HTML file but there's nothing displaying. I tried to get data from the form with form["email"].value() and it's returning None, even when I input data into the email field. Here's views.py: def postlogin(request): form = BootstrapAuthenticationForm(request.POST) # This prints out None into the console print(form["email"].value()) if form.is_valid(): # This code never runs! Even when there are no errors in the form fields! return render(request, "app/home.html") # If form is invalid, return to login page # This always runs, meaning form.is_valid() keeps being false! return render(request,"app/login.html", {"form":form}) Here's my forms.py: from django import forms from django.contrib.auth.forms import AuthenticationForm from django.utils.translation import ugettext_lazy as _ class BootstrapAuthenticationForm(AuthenticationForm): """Authentication form which uses boostrap CSS.""" email = forms.CharField(max_length=254,label=('Email'), widget=forms.TextInput({ 'class': 'form-control', 'placeholder': 'Email'})) password = forms.CharField(label=("Password"), widget=forms.PasswordInput({ 'class': 'form-control', 'placeholder':'Password'})) Here's my login.html: {% extends "app/layout.html" %} {% block content %} <h2>{{ title }}</h2> <div class="row"> <div class="col-md-8"> <section id="loginForm"> <form action="/postlogin/" method="post" class="form-horizontal"> {% csrf_token %} <h4>Use a local account to log in.</h4> <hr /> <div class="form-group"> <label for="id_username" … -
Why Django Messages Won't Work for logout but it work for my sing up?
I wrote this code: my view: from django.contrib.auth.views import LoginView, LogoutView class CustomLogout(LogoutView): def post(self, request, *args, **kwargs): messages.success(request, 'Logout was successfully') return super(CustomLogout, self).get(request, *args, **kwargs) This is my url: urlpatterns = [ ... path('logout/', CustomLogout.as_view(template_name='core/index.html'), name='logout'), ] and I have this in my template: {% if messages %} <div class="alert alert-dismissible" role="alert"> {% for message in messages %} <div class="alert alert-{{ message.tags }}">{{ message }} </div> {% endfor %} </div> {% endif %} I write something like this for SignUp and it works well and show the messages but in this case for logout it won't show any message in template... -
Markdown is not showing up on my Django/HTML web page
I already converted the Markdown page, but it is not showing. Here is how my page looks like when I try to enter to any markdown content: VIEWS: from django.shortcuts import render from markdown2 import Markdown from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entry(request, entry): markdowner = Markdown() entrypage = util.get_entry(entry) if entrypage is None: return render(request, "encyclopedia/NonExisting.html", { "entrytitle": entry }) else: return render(request, "encyclopedia/entry.html", { "entry": markdowner.convert(entrypage), "entrytitle": entry } ) URLS: from xml.etree.ElementInclude import include from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:entry>/", views.entry, name="entry") ] and that Edit button in the image does not work either. -
TypeError: __init__() takes 1 positional argument but 2 were given new one
I am develop a simple authentication application in django but I get this error: TypeError: init() takes 1 positional argument but 2 were given my view from .forms import RegisterForm, LoginForm from django.contrib.auth.views import LoginView from django.shortcuts import render, redirect from django.contrib import messages from django.views import View from .forms import RegisterForm def home(request): return render(request, 'users/home.html') class RegisterView(View): form_class = RegisterForm initial = {'key': 'value'} template_name = 'users/register.html' def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated: return redirect(to='/') return super(RegisterView, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}') return redirect(to='/') return render(request, self.template_name, {'form': form}) class CustomLoginView(LoginView): form_class = LoginForm def form_valid(self, form): remember_me = form.cleaned_data.get('remember_me') if not remember_me: self.request.session.set_expiry(0) self.request.session.modified = True return super(CustomLoginView, self).form_valid(form) application urls urlpatterns = [ path('', home, name='users-home'), path('register/', RegisterView.as_view(), name='users-register'), # This is what we added path('login/', CustomLoginView.as_view(redirect_authenticated_user=True, template_name='users/login.html', authentication_form=LoginForm), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), ] my form from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, AuthenticationForm class RegisterForm(UserCreationForm): first_name = forms.CharField(max_length=100, required=True, widget=forms.TextInput(attrs={'placeholder': 'First Name', 'class': 'form-control', })) last_name = forms.CharField(max_length=100, required=True, … -
Suitescript that attempts to set an amount for sales order items causes "unexpected error"
I have this code that, in theory, changes the amount on the sublist of a sales order in Netsuite, but for one reason or another it tells me that an unexpected error happened. Nothing I've looked at has been particularly helpful Edit: To be clear, the error happens when I go to saved mass updates and execute it, not when saving it /** *@NApiVersion 2.1 *@NScriptType MassUpdateScript */ define(['N/record'], (record) => { function each(params) { let rec = record.load({ type: params.type, id: params.id }); var quant = rec.getValue('custrecordeconomcap'); rec.setCurrentSublistValue({ sublistId: 'item', filedId: 'quantity', value: quant }); rec.save(); } return { each: each }; }); -
I got error while attempting to serialize product's images
AttributeError: Got AttributeError when attempting to get a value for field picture on serializer ProductSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Product instance. Original exception text was: 'Product' object has no attribute 'picture'. class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = Picture fields = ['picture'] class ProductSerializer(serializers.ModelSerializer): category = serializers.ReadOnlyField(source='category.name') discount = serializers.ReadOnlyField(source='discount.name') picture = ProductImageSerializer(many=True) class Meta: model = Product fields = ['_id', 'category', 'discount', 'name_geo', 'picture', 'brand', 'size', 'technicalRequirements', 'instructionForUse', 'safetyStandard', 'youtubeUrl', 'price', 'createdAt', 'user'] class Picture(models.Model): picture = models.ImageField(null=True, blank=True, default='/placeholder.png') product = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self): return str(self.picture) -
Query to calculate user balances
In my project there are coins that users can buy, use to perform certain actions and convert to real money. A user can only convert coins earned (by receiving gifts for example) into real money, not those bought from the site directly. Therefore, two balances are calculated internally: coins bought and coins earned (the total balance is the sum of these two). The following model contains coin transactions (it's simplified): class CoinTransaction(models.Model): class TransactionTypes(Enum): purchase_of_coins = ('pu', 'Purchase of Coins') # Will have a positive amount conversion_into_money = ('co', 'Conversion Into Money') # Will have a negative amount earning = ('ea', 'Earning') # Will have a positive amount expense = ('ex', 'Expense') # Will have a negative amount @classmethod def get_value(cls, member): return cls[member].value[0] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='coin_transactions') amount = models.IntegerField() transaction_type = models.CharField(max_length=2, choices=[x.value for x in TransactionTypes]) The earned coin balance is increased by all income except coin purchases, while the bought coin balance is increased only by coin purchases. Coins from conversion_into_money transactions are subtracted from the earned coin balance, while all other expenses are first subtracted from the bought coin balance if greater than 0. Note that the two balances cannot go below 0. To …