Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Screenshot of web and return image as http response for download in django
I am tring to take screenshot from a website and return token screenshot. I am using this code. My code But it return the token screenshot. Like this enter image description here How can i return token screenshot as httpresponse? -
get data from ManyToMany field django
How do I use product.title in tag view ? something like this t = Tag.products.title Models.py class Tag(models.Model): title = models.CharField(max_length=120) slug = models.SlugField( blank=True) timestamp = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class products(models.Model): title = models.CharField(max_length=150) description = models.TextField() price = models.IntegerField() tag = models.ManyToManyField(Tag, blank=True) -
i am using django 4.0 and want to add templates in setting file i wrote a code TEMPLATE_DIRS =BASE_DIR/'templates'
using django 4.0 it shows error like this raise TypeError('Invalid path type: %s' % type(value).name) File "", line 783, in exec_module TypeError: Invalid path type: tuple -
How to remove fields from user creation form in django
I am creating an app in django with postgressql. So I am creating my custom user model with own fields.BUt when I go to my database their are many fields like first name , last name, id. I dont want to see those field, I only want to see the fields that I am writing in my custom model. -
Django session authentication with React
This is not a coding question, rather a general question: in Django, if I am using default authentication (session authentication in that case), what does the frontend (in my case it is react) need in this case? lets say i log in on browser (login button from frontend side), now it is gonna send username and password data to django, django going to deserialize the data and then authenticate and login, now the problem here is that i redirect to another page where only authenticated users are able to view, the problem is that i cant view it, simply because Django identify me as un-authenticated, after bit of research the answer was because each end (frontend and backend) have different ports, in order to make it work the frontend need to access cookies i assume, is there any simple example to this problem? -
we can i solve [error: open("venv/bin/python"): Invalid argument fatal: Unable to process path venv/bin/python] this problem?
I create a virtual environment and i want to push this in my github but i could not. picture is below. -
Django project not starting
I am using the command django-admin startproject api_practice to start a new django project and getting the following errors - Traceback (most recent call last): File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\Farhan\AppData\Local\Programs\Python\Python39-32\Scripts\django-admin.exe\__main__.py", line 7, in File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\management\commands\startproject.py", line 21, in handle super().handle('project', project_name, target, **options) File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\management\templates.py", line 114, in handle django.setup() File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\__init__.py", line 16, in setup from django.urls import set_script_prefix File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\urls\__init__.py", line 1, in from .base import ( File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\urls\base.py", line 8, in from .exceptions import NoReverseMatch, Resolver404 File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\urls\exceptions.py", line 1, in from django.http import Http404 File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\http\__init__.py", line 5, in from django.http.response import ( File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\http\response.py", line 16, in from django.core.serializers.json import DjangoJSONEncoder File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\serializers\__init__.py", line 23, in from django.core.serializers.base import SerializerDoesNotExist File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\core\serializers\base.py", line 7, in from django.db import models File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\db\models\__init__.py", line 3, in from django.db.models.aggregates import * # NOQA File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\db\models\aggregates.py", line 5, in from django.db.models.expressions import Case, Func, Star, When File "c:\users\farhan\appdata\local\programs\python\python39-32\lib\site-packages\django\db\models\expressions.py", line 10, in from … -
ProgrammingError at /sign-up/
i recently deplolyed my todoapp on heroku and it works just fine, at least until i try creating an account then it prompts me with this error: relation "auth_user" does not exist LINE 1: SELECT (1) AS "a" FROM "auth_user" WHERE "auth_user"."username i'm so confused ive tried so many things i.e Heroku app python manage.py makemigrations i get an error something about id not found. is there anythin i can do? my register view def register(request): if request.user.is_authenticated: return redirect('home') form = registerform() if request.method == 'POST': form = registerform(request.POST) if form.is_valid(): user = form.save(commit=False) user.username = user.username.lower() user.save() login(request, user) return redirect('home') else: messages.error(request, 'User does not exist') return render(request, 'register.html', {'form' : form}) forms.py class registerform(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] -
Best way at add date time stamp in directory of django image field
Till now i was using this function def user_compressed_path(instance, filename): profile_pic_name = 'user/{0}/compressed/profile.jpg'.format(instance.id) full_path = os.path.join(settings.MEDIA_ROOT, profile_pic_name) if os.path.exists(full_path): os.remove(full_path) return profile_pic_name def user_picture_path(instance, filename): profile_pic_name = 'user/{0}/picture/profile.jpg'.format(instance.id) full_path = os.path.join(settings.MEDIA_ROOT, profile_pic_name) if os.path.exists(full_path): os.remove(full_path) return profile_pic_name i want path something like 'user/{0}/compressed/{1}/profile.jpg'.format(instance.id, date_time_stamp) 'user/{0}/picture/{1}/profile.jpg'.format(instance.id, date_time_stamp) what should be the value of date_time_stamp -
How do I refactor my Purchase and Sales models by the method of DRY
I am making a Medical Billing Application with the Django framework but my models need refactoring so that they can work on the principle of DRY(Don't Repeat Yourself). Please help me out with this! Here are the files: models.py(Medicines Model) #------------------------Medicine models---------------------------------- gst = ( (0, '0%'), (5, '5%'), (12, '12%'), (18, '18%'), ) # Create your models here. class Medicines(models.Model): Med_HSN = models.IntegerField(default=0) Med_name = models.CharField(max_length=20) Med_Quantity = models.PositiveIntegerField(default=0) Med_Manufacturer = models.CharField(blank=True,max_length=50) Med_Expiry = models.CharField(default=1,max_length=10) Med_Batch_no = models.CharField(blank=True,max_length=15) Med_MRP = models.FloatField(blank=False) Med_Rate = models.FloatField(blank=False) Med_GST = models.IntegerField(default=0,choices=gst) date_created = models.DateField(default=timezone.now) def caluclate_value(self): value = self.Med_MRP * (self.Med_GST/100) total_value = self.Med_MRP + value return total_value def get_cost(self): return self.caluclate_value() * self.Med_Quantity def __str__(self): return self.Med_name + " | " + str(self.caluclate_value()) + " || Quantity in Stock : " + str(self.Med_Quantity) #----------------------------------End Medicines Models-------------------------------------- models.py(Sales Model) #---------------------------------Sales Models-------------------------------- from django.core.checks import messages from django.db import models from Customer.models import Customer from django.utils import timezone import math payment_status = ( ('Due', 'Due'), ('Paid|Cash', 'Paid|Cash'), ('Paid|Cheque', 'Paid|Cheque'), ('Paid|Online', 'Paid|Online'), ('Cancelled','Cancelled') ) dis = ( (0, '0%'), (5, '5%'), (10, '10%'), (15, '15%'), (20, '20%'), ) # Create your models here. class Sales(models.Model): # sales_id = models.AutoField(primary_key=True) customer = models.ForeignKey(Customer,on_delete=models.CASCADE) prescribed_doctor = models.CharField(blank=True,max_length=150) … -
django error where even though i allowed an attribute in url it isn't working
path('', views.index, name='index') above code works when url: ...8000/app path('<str:name>', views.index, name='index') but this doesn't work when url: ...8000/app/kenny gives page not found error does anyone why it is working with no attributes but not with attributes. Same for other paths also. -
how do i wrtite django fbv to class based view
I have two user types a and b i need to write the below fbv into class based Logoutview(auth.view) how do i write the below fbv to cbv views.py @login_required def logout(request): if request.user.usertype_a: logout(request) return redirect(reverse('user_a_login')) else: logout(request) return redirect(reverse('user_b_login')) -
No value returned in django powered HTML
Looked for the solution for almost 2 days without luck - any guidance is much appreciated. Given 'views.py' looks like this (all needed lib are imported properly): class HomeView(generic.TemplateView): template_name = 'polls/djIndex.html' def test(request): data = {'temperature': '53F', 'state': 'NY', 'mood': ['good', 'bad'] return render(request, 'polls/djIndex.html',{'data':data}) These are not working (no value returned) on djIndex.html: test #1: {% for key, value in data.items %} <h3>{{key}}-----: {{value}}</h3> {% endfor %} test #2: {% for key in data.items %} <p>Value of Key 1 : data["key1"]</p> {% endfor %} test #3 {% for key, value in data %} <p>Key {{ key }}, Value {{ value }}</p> {% endfor %} test #4 <h2> context2: {{data.temperature}}</h2> But these are working on djIndex.html: <h2> Temperature: {{temperature}}</h2> <h2> State: {{state}}</h2> <h2> Mood: {{mood}}</h2> Ask: How to make those non-working test #1-#4 to work on my HTML page. Am I doing something wrong in my djano config, as some of those test #1-#4 are accepted answers in some forums in different instances? -
Multiselect dropdown is not working correctly with django-ajax call?
<form method="POST" data-attributevalue-url="{% url 'vendor:ajax_load_attributes_values' %}"> <div class="d-flex ms-4"> <div class="col-lg-8"> {{ productform.attributes|as_crispy_field }} --dropdown select field <select class="form-control" multiple aria-label="size 3 select example" required name="attribute_values" id="id_attribute_values"> <option value="">----</option> </select> </div> </div> </form> <script> //attribute_values category filter $("#id_attributes").change(function () { var url = $("#productForm").attr("data-attributevalue-url"); var attributeId = $(this).val(); $.ajax({ url: url, data: { 'attributes': attributeId }, success: function (data) { console.log("success") $("#id_attribute_values").html(data); } }); </script> <script type="text/javascript" src="{% static 'multiselect/dist/js/BsMultiSelect.min.js' %}"></script> <script type="text/javascript"> $(document).ready(function() { $("#id_attribute_values").bsMultiSelect(); }); here I want to make a dropdown that can have a multiple selectable options. This will be done after the ajax call. Here I get the values return back by ajax and also I have received values, I seen those in the browser elements tab. But that values not populated inside this dropdown. How to solve this? Need help -
Can't put data into tuple in forms.py Django
I'm currently getting the data from an external API (also developed with django) and put it into a tuple and it's showing it in the HTML but when i use that info into a form and post it, it always shows that field has "none" (Views.py) def register_user(request): if request.method == "POST": if "register" in request.POST: mainForm = mainUserForm(request.POST) form = userForm(request.POST) if mainForm.is_valid() and form.is_valid(): user = User.objects.create_user(mainForm.cleaned_data['username'],mainForm.cleaned_data['email'],mainForm.cleaned_data['password']) if form.cleaned_data['userType'] == 2: user.is_superuser = True user.is_staff = True user.save() userextended = models.commonUserModel(user = user, firstName = form.cleaned_data['firstName'], lastName = form.cleaned_data['lastName'], phoneNumber = form.cleaned_data['phoneNumber'], rut = form.cleaned_data['rut'], userType = form.cleaned_data['userType'], company = form.cleaned_data['company']) userextended.save() return redirect('registerUser') else: return redirect('registerUser') context = {} context['mainForm'] = mainUserForm context['form'] = userForm() context['userExtend'] = commonUserModel.getUserExtended(request.user.id) return render(request, template_name='auth/register.html', context= context) (Models.py) class commonUserModel(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, related_name="extend") company = models.IntegerField() firstName = models.CharField(max_length=30) lastName = models.CharField(max_length=30) phoneNumber = models.CharField(max_length=20) rut = models.CharField(max_length=20, unique= True) userType = models.IntegerField(choices=CLIENT_TYPES, default=1) disabled = models.BooleanField(default = False) (Forms.py) class userForm(forms.ModelForm): def __init__(self,company_choices, *args, **kwargs): choices=[] super(userForm, self).__init__(*args, **kwargs) self.fields['testeo']=forms.ChoiceField(choices=((0, 'Normal' ), (1, 'Especial'),)) testeo= forms.ChoiceField() -
Django 3.2.10 Per-site Cache does not refresh after data changes
My middleware order goes like this, MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', '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', 'django.middleware.cache.FetchFromCacheMiddleware', 'UsersUI.middleware.MultitenantMiddleware', #This does not change anything except setting a variable called current tenant from request.user and just returns the self.get_response(request) from __call__ method ] My cache settings are CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'my_cache_table', } } CACHE_MIDDLEWARE_SECONDS = 1000000 CACHE_MIDDLEWARE_KEY_PREFIX = '' Yes, I have created the cache table as well. Even if I do a hard reload and clear the browser cache, the data does not get updated. I need to clear the entire cache table for the change to reflect in the cache. I don't know what went wrong. I am just using a per-site cache. Also, I don't know if this is relevant, I low-level cached a permission value like this from django.core.cache import cache class CheckActiveSubscription(permissions.BasePermission): message = "You don't have an active subscription. Please click here {link} to subscribe." def has_permission(self, request, view): cache_name = str(request.user.firm.firm_code)+str("permission_cache") cache_value = cache.get(cache_name) if cache_value: # not None and It is True return cache_value else: customer = request.user.firm if not request.user.is_anonymous else None if customer : print("Customer Exists") active_plan = customer.check_permission_stripe_MetaProducts if active_plan and active_plan in view.allowed_subscriptions: cache.set(cache_name, … -
Cant add math/science equation in the django-ckeditor outside django admin
Good day everyone! I'm hopping anyone has idea why its not working. Basically I used Django ckeditor as my WYSIWYG for my project. I tried it inside django admin and it is working fine. However, when I used it outside Django admin(in my template) I cant insert any equations. Its seems the textbox is disable. I cant put any value on it. It display only the placeholder equation(quadratic equation) This is the template This is my urls.py This is the models.py and forms.py This is in the base.html This is where I used the editor in my create_activity.html I tried to search for this issue but I found none.I hope anyone can help. -
Anonymous user after successful login
so i am getting AnonymousUser when printing request.user after successful login,de-serializing process is done successfully too. Here is my login view class in views.py file: class LoginView(views.APIView): def post(self, request): data = serializers.LoginSerializer(data=request.data) print(data.is_valid()) print(data.errors) print(f" HEEERE::: {data}") if self.request.method == 'POST': if data.is_valid(): auth = authenticate( username=data.validated_data['email'], password=data.validated_data['password']) print(f" email check : {data.validated_data['email']}") print(f"auth:: {auth}") if auth is not None: login(request, auth) return redirect("/ticket") else: return HttpResponse("Invalid Credentials") else: return HttpResponse("Data not being validated :O") -
Django settings.py with additional imports odd behaviour and email errors [Errno 111] / clarification on best practice
I've noticed some strange behavior with Django and hope to get a better clarification on why that is. This is in part related to questions like this one (Django Email Error) but goes into more depth wondering about best practices. Look at the following setup: In order to not "overload" my settings.py in my main app I am importing additional sub-settings files. My structure is something along the lines of: main_app -settings.py ... utils_app config -settings_email.py -settings_something_else.py ... utils -email.py ... ... 'email.py' contains the send_email() function and the main_app settings.py file imports as follows: from utils_app.config import settings_email And settings_email.py would look something like: EMAIL_HOST='some-host' EMAIL_PASS=os.environ.get('EMAIL_PASSWORD') EMAIL... ... Originally those variables were in my (default) main_app settings.py file. When that was the case sending email via the Django 'send_mail' function was fine. Once I've moved them out importing as above it stopped working unless I specifically name them when importing like so for example: from utils_app.config.settings_email import EMAIL_HOST, ... In the Django send_mail documentation I couldn't see anything regarding this issue. So the first question is: does Django indeed not know where to look for those variables other than default settings.py and they have to be named there specifically, … -
Django admin: how to display number with fixed length?
This is my model: from django.contrib.humanize.templatetags.humanize import intcomma class Flow(models.Model): amount = models.DecimalField(max_digits=10, decimal_places=2) def df_amount(self): return '{intcomma(abs(self.amount)):>12}' df_amount.admin_order_field = 'amount' df_amount.short_description = 'amount' In admin.py, @admin.register(Flow) class FlowAdmin(admin.ModelAdmin): list_display = ( 'df_amount', ) For amount=2800, print(self.df_amount()) gives $ 2,800.00 but $ 2,800.00 is displayed in the admin panel where the spaces in the middle were truncated to only one space, not as expected. So my question is how to reserve the spaces in the middle of the string in admin panel? Thank you! -
could I get a simple explanation to this code?
class CourseModuleUpdateView(TemplateResponseMixin, View): template_name = 'manage/module/formset.html' course = None def get_formset(self, data=None): return ModuleFormSet(instance=self.course, data=data) def dispatch(self, request, pk): self.course = get_object_or_404(Course, id=pk, owner=request.user) return super().dispatch(request, pk) def get(self, request, *args, **kwargs): formset = self.get_formset() return self.render_to_response({'course': self.course, 'formset': formset}) def post(self, request, *args, **kwargs): formset = self.get_formset(data=request.POST) if formset.is_valid(): formset.save() return redirect('manage_course_list') return self.render_to_response({'course': self.course,'formset': formset}) hi guys, I need help understanding this code. I'm working on a project about an e-learning platform so I needed to generate forms for related objects ie a formset for a course module but then this code did the magic but I don't what's going on in the code. I need help and answers with understanding the code. thanks -
Django Throws Permission Denied Error While Trying To Open File
I have a structure Project/ ml_model/ mlp_model scripts/ my_script manage.py open(file_path, 'r') works when I did it inside manage.py but I want to call a function that contains open(file_path, 'r) from my_scripts via a function call. like: manage.py: from my_scripts import Y y = Y() y.do_smth(file_path)` my_script: class Y: def do_smth(self, file_path): f = open(file_path, 'r') //do smth When I do that, f = open line throws "PermissionError: [Errno 13] Permission denied" error. It works fine when I open the file inside manage.py. -
how to use static file on css file with version in django
I need help with a problem i just ran into while working with django static file. so i downloaded this free html template that references it css style as below: <link rel="stylesheet" href="assets/css/vendor.bundle.css?ver=1930"> <link rel="stylesheet" href="{% static 'assets/css/vendor.bundle.css?ver=1930' %}"> ``` meanwhile in django template, i know to reference static files like css and js without the ?ver=1930 as below ``` now my problem is that if i reference as <link rel="stylesheet" href="{% static 'assets/css/vendor.bundle.css?ver=1930' %}"> ``` it doesn't load the css and if i take away the ?ver=1930 and load it like ``` it works but my css get broken. How do i fix this problem plssss. -
How to increase 1 unit when upload a image?
I have a question. I have a user model and it has profile_image and profile_image_quantity fields. Can I increase my value of profile_image_quantity when uploading a image. My user model: class User(AbstractBaseUser): username = models.CharField(max_length=30, verbose_name="Username", help_text="Be carefully while choosing username. If you want change your username you have to pay money") email = models.EmailField(help_text="Your active email adress", verbose_name="Email", unique=True) first_name = models.CharField(max_length=20, verbose_name="First Name", help_text="Your first name") last_name = models.CharField(max_length=20, verbose_name="Last Name", help_text="Your last name") birthday = models.DateField(blank=False, null=True, help_text="Your birthday") date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_staff = models.BooleanField(verbose_name="Staff", default=False) is_admin = models.BooleanField(verbose_name="Admin", default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_verified_account = models.BooleanField(default=False) is_verified_email = models.BooleanField(default=False, help_text="Your email still isn't verified") status = models.CharField(choices=status, default='Online', max_length=20, help_text="Your currently status") profile_image_quantity = models.IntegerField(default=0) profile_image = models.ImageField(upload_to=get_profile_image_path, verbose_name="Profile Image", default=default_profile_image_path, blank=True) My get_profile_image_path function: def get_profile_image_path(instance, filename): ext = filename.split('.')[-1] user = User.objects.get(id=instance.id) user.profile_image_quantity += 1 user.save() return f"User/{user.pk}/profile_images/{user.profile_image_count}.{ext}" -
Serializer is not receiving data, (data is empty OrderedDict())
please note that email is basically the username here to not get confused, in serializer.py I have debugged the data, but it seem that user is giving me None serializer.py class LoginSerializer(serializers.Serializer): def validate(self, data): email = data.get("email") print(f" email here : {email}") password = data.get("password") user = authenticate(username=email, password=password) print(f"{user} username serializer ") print(f"this is data : {data}") if user is not None: return data raise serializers.ValidationError("Incorrect Credentials") views.py class LoginView(views.APIView): def post(self, request): data = serializers.LoginSerializer(data=request.data) print(data.is_valid()) print(data.errors) print(f" HEEERE::: {data}") if self.request.method == 'POST': if data.is_valid(): auth = authenticate( username=data.validated_data['email'].value, password=data.validated_data['password'].value) print(f"auth:: {auth}") if auth is not None: login(request, auth) request.session['user_id'] = auth.id print("test") return redirect("/ticket") else: return HttpResponse("Invalid Credentials") else: return HttpResponse("Data not being validated :O") on frontend side (React): import React, { useState } from 'react'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import { login } from '../actions/auth'; import axios from 'axios'; function Login(){ const [login,setLogin] = useState({ email: '', password:'' }); const { email, password } = login; function handleChange(e){ console.log(e.target.value); setLogin({ ...login, [e.target.name]: e.target.value }); } function handleSubmit(e){ e.preventDefault(); axios.post(' http://127.0.0.1:8000/login/', login) console.log(login); } return ( <div className="container"> <form method='post' onSubmit={handleSubmit}> <h1>Login</h1> <label> Email: <input type='text' name …