Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I add a column in pre existing model? getting this error:
Im getting this error after I run migrations= django.db.utils.OperationalError: no such column: pdfReports_files.category here is my model: I added category field later. from django.db import models class files(models.Model): pdf = models.FileField(upload_to='media') menu_name=models.TextField(default='SOME STRING') href=models.TextField(default='#') category=models.TextField(default='') objects = models.Manager() -
Customise JSON string display in Django admin
I'm working on a custom online market project. I've made a simple Order model: class Order(models.Model): cart = models.CharField(max_length=1000) user = models.ForeignKey(User, on_delete=models.CASCADE) The cart field stores the whole order in one JSON string which can look something like this: {"8": 6, "5": 1} Where the key is an ID of a product and value is it's quantity. The problem is that standard Django admin displays this as a string and it's completely not friendly for humans to read. Is there a way I can unpack this string using json.load, then filter the instances of Product objects and render it in a certain way the same way it can be done with a regluar view and a custom template, but within the admin interface? -
Django isn't recognizing crispy forms
my pip is showing that crispy forms is installed but for some reason when I run manage.py it's saying that it doesn't exist. Here is some history from my terminal that I annotated over for clarity. [ec2-user@ip-172-26-0-126 bd_website]$ pip list DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Package Version ---------------------------- -------- (elements ommitted for brevity...) Django 1.11.29 django-crispy-forms 1.9.0 <<Crispy forms is installed, right? (elements ommitted for brevity...) [ec2-user@ip-172-26-0-126 bd_website]$ pip install django-crispy-forms DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: django-crispy-forms in /home/ec2-user/.local/lib/python2.7/site-packages (1.9.0) [ec2-user@ip-172-26-0-126 bd_website]$ python --version Python 3.6.11 <<Version is compatible with Django [ec2-user@ip-172-26-0-126 bd_website]$ python manage.py runserver Watching for file changes with … -
local variable 'direct1' referenced before assignment
I am writing a simple program where I enter an employee ID number and it renders the data for that employee. Here is my code on the backend: def emp1(request): import requests import json if request.method == 'POST': quote = request.POST['quote'] # or None if quote == "10001401": employee1 = requests.get("the api url") direct1 = json.loads(employee1.content) return render(request, 'home.html', {'quote': quote, 'direct1': direct1}) Now this works. It's only when I enter another employee, that I am told that 'direct1' is referenced before assignment. I tried to make the variable (direct1) global. But I don't think I am grasping how to do that in django views. -
SAML 2.0 + Keycloak + Django
Hello I'm trying to implement Keycloak SAML 2.0 authentication with Django application. I'm using django_saml2_auth and I configured my project as I was instructed in the django_saml2_auth repo. My configuration of django_saml2_auth is: SAML2_AUTH = { 'METADATA_AUTO_CONF_URL': 'http://localhost/keycloak/auth/realms/master/protocol/saml/descriptor' } when I start the development server on localhost:8000 and go to /accounts/login I'm redirected to Keycloak and I have the following error: We are sorry... Unknown login requester Do you know how to fix that? Do you know some well documented examples of Keycloak SAML 2.0 configuration with Django? -
Form submission not working in Django 1.11 with python 2.7
Am new to Django . I have python2.7 and django 1.11 version , I was able to display a home page etc. But when trying to create a form and submitting its not redirecting to any page url.py from django.conf.urls import include from . import views from django.conf.urls import url urlpatterns = [ url("",views.home, name="home"), url("add",views.add,name="add") ] home.html {%extends 'base.html' %} {%block content %} <H1> hello world 2 {{name}} </H2> <form action="/add"> Enter 1st number : <input type="text" name = "num1"><br> Enter 2nd number : <input type="text" name = "num2"><br> <input type = "submit"> </form> views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): x = ' Hello World' return render(request,'home.html',{'name' : 'Test Name'} ) # return HttpResponse(x) def add(request): print('testing') val1 = request.GET['num1'] val2 = request.GET['num2'] res = val1 + val2 print(res) return render(request,"results.html",{'result' : res}) results.html is a test page. Once I click submit its not displaying any thing on the results page . Is there anything wrong in url.py -
how can I avoid the third pattern slug gets overwritten?
I got an overwrite from the last part of my URL similar to this. how can I improve the way I am using the slug from models to urls.py, and avoid getting overwrite my lesson module URI? models def get_absolute_url(self): return reverse('lesson-module',kwargs={ 'lesson_slug': self.lesson.slug, 'lesson_module': self.slug }) urls.py urlpatterns = [ path('', CourseListView.as_view(), name='university'), path('<slug>', CourseDetailView.as_view(), name='detail'), path('<course_slug>/<lesson_slug>', LessonDetailView.as_view(), name='lesson-detail'), path('<course_slug>/<lesson_slug>/<lesson_module>', LessonModuleDetailView.as_view(), name="lesson-module"), ] views class LessonDetailView(LoginRequiredMixin, View): def get(self, request, course_slug, lesson_slug, *args, **kwargs): class LessonModuleDetailView(LoginRequiredMixin, View): def get(self, request, course_slug, lesson_slug, lesson_module, *args, **kwargs): uris http://localhost:8000/university/ http://localhost:8000/university/javascript http://localhost:8000/university/javascript/lesson-1 http://localhost:8000/university/javascript/hello-world # this gives me , but I I want http://localhost:8000/university/javascript/lesson-1/hello-world (edited) -
Django: ImportError at/ "doesn't look like a module path
** How can I solve this problem? ** Exception Type: ImportError at /enter code here Exception Value: first_app doesn't look like a module pathenter code here Request Method: GETenter code here Request URL: http://127.0.0.1:8000/`enter code here` Django Version: 3.0.3enter code here Python Version: 3.8.5enter code here Installed Applications:enter code here ['django.contrib.admin',enter code here 'django.contrib.auth',enter code here 'django.contrib.contenttypes',enter code here 'django.contrib.sessions',enter code here 'django.contrib.messages',enter code here 'django.contrib.staticfiles',enter code here 'first_app'] Installed Middleware:enter code here ['django.middleware.security.SecurityMiddleware',enter code here 'django.contrib.sessions.middleware.SessionMiddleware',enter code here 'django.middleware.common.CommonMiddleware',enter code here 'django.middleware.csrf.CsrfViewMiddleware',enter code here 'django.contrib.auth.middleware.AuthenticationMiddleware',enter code here 'django.contrib.messages.middleware.MessageMiddleware',enter code here 'django.middleware.clickjacking.XFrameOptionsMiddleware']enter code here -
migrations for djstripe subscription payment api integration not working
bellow error i am facing while running this command python3 manage.py djstripe_sync_plans_from_stripe Error: djstripe.UsageRecord.livemode: (fields.W903) NullBooleanField is deprecated. Support for it (except in historical migrations) will be removed in Django 4.0. HINT: Use BooleanField(null=True) instead. -
how to specify a url for a default image in django
I am using this code for assinging a default image for a post if user doesn't upload any. It works fine for home page. But when I go to detailed view of this post django looks image in 'domain/post/id/media/default-book.jpg' address. This is my code {% else %} <img class="cover-img" src="media/default-book.jpg" alt=""> {% endif %} instead of address for the default image, how can i assign a url like {{ default.url }} this for the source file. -
Django form for list of values
Is it possible to somehow process a list of values using standard Django classes and without using a for loop to create a form for each value? models.py class Warehouse(models.Model): name = models.CharField(max_length=128) class Shift(models.Model): warehouse = models.ForeignKey("Warehouse", blank=False, null=False, on_delete=models.CASCADE) number = models.IntegerField() start_time = models.TimeField(blank=True, null=True) end_time = models.TimeField(blank=True, null=True) JSON data { "name":"Warehouse", "shifts":[ { "start_time":"09:00", "end_time":"18:00", "number":"1" }, { "start_time":"10:00", "end_time":"18:00", "number":"2" } ] } I'm trying formset_factory. But with list it wont working. With one object raise ['ManagementForm data is missing or has been tampered with'] What i'm trying: forms.py class ShiftForm(forms.Form): id = forms.IntegerField(required=False) number = forms.IntegerField(required=True) start = forms.TimeField(required=False) end = forms.TimeField(required=False) def save(self): ... class WarehouseForm(forms.Form): name = forms.CharField(required=True, max_length=128) def save(self): ... views.py def post(self, request): form = WarehouseForm(json.loads(request.body)) Formset = formset_factory(ShiftForm) formset = Formset(json.loads(request.body)["shifts"]) if form.is_valid() and formset.is_valid(): # here formset raise error ... return HttpResponse(status=200) else: return JsonResponse(form.errors, status=400) -
Django: Get UTC Timezone
This seems extremely simple, but I cannot find a simple explanation: How can I get the UTC timezone to pass here? I want to pass GMT / UTC specifically. from django.utils import timezone timezone.make_aware(datetime.fromtimestamp(sometimestamp), timezone=???) -
Can't "activate" virtualenv
New to running Python in virtual environments, messing with Django, and can't activate a virtual environment. Spent the last 4 hrs trying to activate a virtual env (venv) on local terminal/VS Code with no luck. Avoided "sudo pip install virtualenv" as I was trying to avoid installing as root and having different directory path, etc. "pip install virtualenv" output: Collecting virtualenv Using cached virtualenv-20.0.31-py2.py3-none-any.whl (4.9 MB) Requirement already satisfied: six<2,>=1.9.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.15.0) Requirement already satisfied: appdirs<2,>=1.4.3 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.4.4) Requirement already satisfied: filelock<4,>=3.0.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (3.0.12) Requirement already satisfied: distlib<1,>=0.3.1 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (0.3.1) Installing collected packages: virtualenv Successfully installed virtualenv-20.0.31 "virtualenv venv" output: created virtual environment CPython3.8.5.final.0-64 in 416ms creator CPython3Posix(dest=/Users/garrettpinto/Desktop/rp-portfolio/distribution/venv, clear=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/Users/garrettpinto/Library/Application Support/virtualenv) added seed packages: pip==20.2.2, setuptools==49.6.0, wheel==0.35.1 activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator "source venv/bin/activate" returns nothing "./venv/bin/activate" output: zsh: permission denied: ./venv/bin/activate "sudo ./venv/bin/activate" output: sudo: ./venv/bin/activate: command not found Thoughts? -
how can I avoid getting the last part of the url overwrite?
I am trying to do the following, but however I got an overwrite from the last part of my url similar to this. how can I improve the way I am using the slug from models to urls.py , and avoid getting overwrite my lesson module uri ? models def get_absolute_url(self): return reverse('lesson-module',kwargs={ 'lesson_slug': self.lesson.slug, 'lesson_module': self.slug }) urls.py urlpatterns = [ path('', CourseListView.as_view(), name='university'), path('<slug>', CourseDetailView.as_view(), name='detail'), path('<course_slug>/<lesson_slug>', LessonDetailView.as_view(), name='lesson-detail'), path('<course_slug>/<lesson_slug>/<lesson_module>', LessonModuleDetailView.as_view(), name="lesson-module"), ] views class LessonDetailView(LoginRequiredMixin, View): def get(self, request, course_slug, lesson_slug, *args, **kwargs): class LessonModuleDetailView(LoginRequiredMixin, View): def get(self, request, course_slug, lesson_slug, lesson_module, *args, **kwargs): uris http://localhost:8000/university/ http://localhost:8000/university/javascript http://localhost:8000/university/javascript/lesson-1 http://localhost:8000/university/javascript/hello-world # this gives me , but I I want http://localhost:8000/university/javascript/lesson-1/hello-world (edited) -
ODBC Error with Django Configuration - "Invalid value specified for connection string attribute 'encrypt' "
I have done quite a bit of searching on the error below and I have been hitting all around it, not finding where my configuration may be off. When configuring django 3.x with a Microsoft SQL Server, I get the following error when running my application. The error seems to point to some encryption parameter but in my testing, I have yet to determine which parameter. I have tried a number of different security-based settings in the "OPTIONS" but no luck. Can anyone point me in the right direction? Error: django.db.utils.OperationalError: ('08001', "[08001] [Microsoft][ODBC Driver 17 for SQL Server]Invalid value specified for connection string attribute 'encrypt' (0) (SQLDriverConnect)") Libraries installed django-mssql-backend==2.8.1 pyodbc==4.0.30 Connection String DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'testDB', 'HOST': 'testserver.test.net', 'PORT': '1433', 'USER': 'username', 'PASSWORD': 'password', 'AUTOCOMMIT': True, "OPTIONS": { 'driver': 'ODBC Driver 17 for SQL Server', 'host_is_server': True, 'connection_timeout': 30, 'collation': 'SQL_Latin1_General_CP1_CI_AS', 'extra_params': 'Trusted_Connection=yes;Encrypt=yes', } } } -
How to access this touple value in Django template to display properly?
I want to display amount of expenses for each category in this table. But I don't know how to access this queryset value which represent the amount. VIEWS.PY CODE class CategoryListView(ListView): model = Category paginate_by = 5 def get_context_data(self, *, category_object_list=None, **kwargs): categories = Category.objects.annotate(Count('expense')) queryset = categories.values_list('name', 'expense__count') return super().get_context_data( category_object_list=queryset, **kwargs) TEMPLATE.HTML CODE <table border="1"> <thead> <tr> <th>category</th> <th>expenses</th> <th>actions</th> </tr> </thead> <tbody> </tbody> {% for category in object_list %} <tr> <td> {{ category.name|default:"-" }} </td> {% for number in category_object_list %} <td>{{ number }}</td> {% endfor %} <td> <a href="{% url 'expenses:category-update' category.id %}">edit</a> <a href="{% url 'expenses:category-delete' category.id %}">delete</a> </td> {% endfor %} </tr> I ended up on this terrible result and code... Does anyone what should I do know? What to change/add? Thank you in advance for any help! -
Django, def total summary line
This statement show client on each line with his total sales, i would like to add a summary line with the sum of all sales of all clients class statement(models.Model): client = models.ForeignKey('Client', on_delete=models.CASCADE) def sales(self): invoices = self.client.invoice_set.all() sales = 0 for invoice in invoices: sales += invoice.total_invoice() return round(sales, 2) -
Django custom Auth form. How to show error messages
Another Django form question -.- So, I have this form which works just fine, but it won't show any error messages. I'm pretty new to customising forms, so my question is that, do I need to specify anything else in order for my messages to show up? Forms.py file class UserLoginForm(AuthenticationForm): error_css_class = "error" def __init__(self,*args,**kwargs): super(UserLoginForm, self).__init__(*args,**kwargs) username = forms.CharField(widget=forms.TextInput( attrs={'class': 'input','placeholder': 'Username','label':''} )) password = forms.CharField(widget=forms.PasswordInput( attrs={'class': 'input','placeholder': 'Password','label':''} )) HTML File: {%block content%} <form class="form" method="POST"> {% csrf_token %} <fieldset class="form-group text-center text-uppercase"> <h1 class="sign-in__header">Sign up</h1> {% for field in form %} <p> {{ field }} {{ field.help_text }} </p> {% endfor %} </fieldset> <div class="form-group"> <button class="submit" type="submit">Sign in</button> </div> {% for field in form %} <div>{{ field.errors}}</div> {% endfor %} </div> </form> </div> {%endblock content%} -
can't change user avatar
In my app I allow users to have a profile avatar and I allow users to change their avatar from their profile. for the user profile answer the following view: class CustomerDetailUpdateView1(LoginRequiredMixin, UpdateView): model = User form_class = CustomerDetailUpdateForm1 template_name = 'customer/customer-profile1.html' def get_object(self): # print(forms.context_data) return self.request.user def get_success_url(self): return reverse("customer:customer-update") the code of form is: class CustomerDetailUpdateForm1(ModelForm): class Meta: model = User fields = ['email', 'full_name', 'avatar', 'country', 'city', 'address', 'phone_number' ] widgets = { 'email': forms.EmailInput(attrs={'class': 'form-control'}), 'full_name': forms.TextInput(attrs={'class': 'form-control'}), 'address': forms.TextInput(attrs={'class': 'form-control'}), 'city': forms.TextInput(attrs={'class': 'form-control'}), 'country': forms.Select(attrs={'class': 'form-control'}) } in template: <div> {{ form.as_p }} </div> everything works except when the user tries to change his avatr. error does not occur BUT the avatar does not change. can someone help me with the explanation what is the problem ??? -
Django channels get the current channel
I want to save messages to my database, but I want to divide them by channels, currently I load messages from other channels from the database, I am wondering how can I get something unique about a certain channel so I could have a field in my model named channel for that? -
How to get a Field inbetween a sentence? Using django/css for a survey
I basically have a simple question: I do a survey with django and use css/bootstrap. How do I get a text after my first CharField without creating another Fieldset? Basically, I want to have something like that: "I would pay ... for this." How to get the Field inbetween a sentence? Can I somehow use Div("Text") or something? Thanks a lot! Example how it looks now and should look class SurveyPolicy(forms.Form): policy6a = forms.CharField( # required=False, label='', widget = forms.Textarea(attrs={'rows':1}) ) policy6b = forms.IntegerField( # required=False, label='', widget=forms.NumberInput() ) def __init__(self, *args, **kwargs): super(SurveyPolicy, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'survey-form' self.helper.label_class = 'col-lg-12' self.helper.field_class = 'col-lg-12' self.helper.layout = Layout( Fieldset( "<hr><h5 style='color: #2D2D2D; text-align: center; font-family: Roboto;'>I would pay ...</h5>", Div('policy6a', css_class='form-group row-ml-0 mb-0'), Div('policy6b', css_class='form-group row-md-0 mb-0'), # css_class='row', ), -
How to make full text search in PostgreSQL to search any order of words in the input search_text and also if there are words between them
I'm trying to use Django full-text search but I'm having a problem: I've followed this documentation, and it works quite well. But my problem is that I don't want the postgress to consider the order or permutation of the words I search. I mean I want the result of searching "good boy" and "boy good" to be the same. and also when I search "good boy" I want to see the "good bad boy" in the results. But none of these happen and I can't query "good bad boy" with typing "boy good" or even "good boy" (Because of the "bad" missing). I've tried to split search_text by space and then & the search queries like this in order to remove the order of words but it didn't work. I changed this code: search_query = SearchQuery( search_text ) search_rank = SearchRank(search_vectors, search_query) to this: s = SearchQuery(search_text.split(' ')[0]) for x in search_text.split(' ')[1:]: s = s & SearchQuery(x) search_query = s search_rank = SearchRank(search_vectors, search_query) -
How do I know which Django function and arguments are being called on the click of a button?
I am looking at someone else's Django project and I am able to access the website they have created using their Docker set up. So in the Django project I can see a bunch of Python scripts that have a whole lot of different functions. What I need to find out is which function (and also what arguments are used for this function) is being used on the click of a button which submits the form. How do I do this? Considering the HTML of the button gives just this and no indication of what's actually happening when the button is clicked: <div class="mt-2 ml-3 mb-3"> <button name="submit" id="id_submit" class="btn btn-primary btn-sm"> Submit for Approval </button> <button name="save" id="id_save" class="btn btn-secondary btn-sm"> Save </button><h1></h1> </div> Where do I look to find the function and its arguments? I can make a good guess at which function it is just by the name of it but I would also like to know which argument values are used. How do I do this? -
Javascript not working when using built tags in Django
I'm learning django weeks from now, but I'm being curious why the function of my table search is not working well. When I search something on table search, the first row is gone. When the time I used this tags below to get all data from database the function did not work well.Without using loop below the function works fine but I need to attach in database it didn't work. Any idea why is this happening? thanks in advance. :) {% for item in user_information %} <tr> <td>{{item.first_name}}</td> </tr> {% endfor %} Views.py def new(request): if request.session.has_key('is_logged'): user = User.objects.all() return render(request, 'dash_new.html',{'user_information':user}) return redirect('/') table {% extends 'navigation.html' %} {% block content %} <table style="width: 100%;" id="example" class="table table-hover table-striped table-bordered"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> </tr> </thead> <tbody> {% for item in user_information %} <tr> <td>{{item.first_name}}</td> <td>{{item.last_name}}</td> <td>{{item.email}}</td> <td>{{item.username}}</td> <td>{{item.date_joined}}</td> </tr> </tbody> {% endfor %} <tbody> </tfoot> </table> {% endblock %} -
why the value in ManyToManyField doesn't change and keep the same in Django framework?
i want to change the value in the field manytomany to become unbook instead of book , and to store in database but instead it just redirect without change in the value i am new in Django i don't know where the problem but i think the problem in views.py in line 13 ,not sure but i think post_id not define in anywhere but here "post_id=post_id" the right one define it like this because of tutorial i see it , so i am not sure about it here is the code views.py def booking_system(request): user = request.user if request.method == 'POST': post_id_for = request.POST.get('post_id') post_obj = Medicine.objects.get(id=post_id_for) if user in post_obj.Booked.all(): post_obj.Booked.remove(user) else: post_obj.Booked.add(user) like, created = BookingSystem.objects.get_or_create(user=user, midicine_id=post_id_for) if not created: if like.value=='Book': like.value='UnBook' else: like.value='Book' post_obj.save() like.save() return redirect('medicine_1:all_medicine') models.py class Medicine(models.Model): user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) medicine_title = models.CharField(max_length=100) Booked = models.ManyToManyField(User, default=None, blank=True, related_name='Booked') @property def num_book(self): return self.Booked.all.count() def __str__(self): return self.medicine_title BOOK_CHOICES=( ('Book','Book'), ('UnBook','UnBook'), ) class BookingSystem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) medicine = models.ForeignKey(Medicine, on_delete=models.CASCADE) value = models.CharField(choices=BOOK_CHOICES , default = 'Book', max_length = 8) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user}-{self.medicine}-{self.value} medicine.html {% if albums %} {% for album in …