Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError, can only concatenate str (not "bool") to str
I'm learning programming, I'm following a tutorial but I added a boolean, so that the property title is not changeable on the front-end, but I get this error. def contact(request): if request.method == 'POST': property_id = request.POST['property_id'] if 'property' in request.POST: property = request.POST['property'] else: property = False name = request.POST['name'] email = request.POST['email'] message = request.POST['message'] realtor_email = request.POST['realtor_email'] contact = Contact(property=property, property_id=property_id, name=name, message=message ) contact.save() # Send Email send_mail( 'Property Inquiry' 'There has been an inquiry for' + property + 'Check it', ['m@gmail.com', 'j@gmail.com'], fail_silently=False ) I tried different methods for example ('There has been an inquiry for') == [property] Here I get a 'str' object is not callable -
Where to Set Django Choices Attribute
I see I can set the choices attribute either on the ModelField or the Form. Which is the more correct way to do this? Is there any behavioral differences between the two options? What are the pros and cons of each? -
Django Many to One relationship form
I have two models: Case and CaseNote CaseNote has many to one relationship and should connect to Case over Case ID. Models: class Case(models.Model): title = models.CharField(max_length=100) description = models.TextField() notes = models.TextField(blank=True, null=False) status_choices = [('Active', 'Active'),('Closed', 'Closed'),] status = models.CharField(max_length=100, choices=status_choices, default='Active',) John = 'John Doe' Grace = 'Grace Doe' author_choices = [(John, 'John Doe'),(Grace, 'Grace Doe'),] author = models.CharField(max_length=100,choices=author_choices,) createdDateTime = models.DateTimeField(auto_now=False, auto_now_add=True) lastModifiedDateTime = models.DateTimeField(auto_now=True, auto_now_add=False) def get_absolute_url(self): return reverse("case_details", kwargs={"id": self.id}) def __str__(self): return self.title class CaseNote(models.Model): title = models.CharField(max_length=100) note = models.TextField(blank=False) case = models.ForeignKey(Case, on_delete=models.CASCADE) createdDT = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.title Here's a form: class NoteForm(forms.ModelForm): title = forms.CharField() note = forms.CharField(widget=forms.Textarea()) class Meta: model = CaseNote fields = [ 'title', 'note', ] Here's a view: def case_create_note_view(request, id): case = get_object_or_404(Case, id=id) form = NoteForm(request.POST or None) if form.is_valid(): form.save() form = NoteForm() context = { 'form': form } return render(request, 'case/case_create_note.html', context) Could anyone explain why this view / form won't work? I guess it's probably because I need to pass the case Id inside the view somewhere, but I don't know where. Any help would be much appreciated. -
django, cannot access 2nd app (new dir) index page
I am hitting a conflict with a prior configuration and not sure how to get around the error. error: exception No module named 'p' from project urls.py: $ cat exchange/urls.py from django.contrib import admin from django.urls import path, include from pages.views import home_view, contact_view, about_view, user_view #from products.views import product_detail_view from userdash.views import userdash_detail_view, userdash_create_view from django.conf.urls import include from django.urls import path from register import views as v from pages import views from userarea import views as p urlpatterns = [ path('', views.home_view, name='home'), path('', include("django.contrib.auth.urls")), path('admin/', admin.site.urls), path("register/", v.register, name="register"), path('userdash/', userdash_detail_view), path('contact/', contact_view), path('uindex/', include("p.urls")), path('create/', userdash_create_view), path('about/', about_view), path('user/', user_view), ] I'm a django n00b that got 1 app working like I want it and was experimenting with a new / 2nd template + app and I either get this error or problem with it trying to access my default. I have narrowed the issue to my ignorance of from userarea import views as p and it's access of path('uindex/', include("p.urls")), But unable to find a work around. from app views.py $ cat userarea/views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def uindex(response): return HttpResponse("<h1>New user dashboard area</h1>") app urls.py: … -
NOT NULL constraint failed: groups_userprofile.user_id
So i have two models the default user model and a profile model that holds more information. Users can register an account and then log in. When they login it brings them to a userprofile and when they click on the tab to edit the profile it brings them to another page that allows them to enter more information. When you hit submit it gives: NOT NULL constraint failed: groups_userprofile.user_id. Here is my code: models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save ##from django.db.models.signal import post_save # Create your models here. ##adds additional info for each user class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) about_me = models.CharField(max_length=100, default='') major = models.CharField(max_length=50, default='') classes = models.CharField(max_length=500, default='') image = models.ImageField(upload_to='profile_image', blank=True) graduation_date = models.CharField(max_length=50, default='') experience = models.CharField(max_length=50, default='') contact = models.CharField(max_length=50, default='') def create_profile(sender, **kwargs): if kwargs['created']: user_profile= UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender= User) views.py def addUser(request): if request.method == 'POST': form = RegisterForm(request.POST or None) if form.is_valid(): print('valid') form.save() return redirect('home') else: print('not valid') print(form.errors) form = RegisterForm() args = {'form': form} return render(request, 'login_register/register.html', args) @csrf_protect def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST or None) if form.is_valid(): print('valid') form.save() return redirect('profile') else: print('not valid') … -
Cannot run migrate by using a existing database
I am using Django3 and Python3 with the latest version to learn Django. I want to use an existing sqlite3 database for my django project. But I have problems while I was using the migrate command. I have done very few steps to my project so far: 1. use the venv, upgrade pip, install django, 2. generate a project, 3. insert an app, and add it into INSTALLED_APPS, 4. In the settings.py, I added the existing database into the DATABASES as follows. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'testdb': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'TestDB.sqlite3'), }, } Then I use the method as here shows, to generate the models.py file. Using existing database in Django The generated models.py looks like: (where I added the max_length=25) from django.db import models class Stars(models.Model): actorname = models.CharField(db_column='ActorName', blank=True, null=True, max_length=25) realname = models.CharField(db_column='RealName', blank=True, null=True, max_length=25) class Meta: managed = False db_table = 'Stars' 6. Then I run python manage.py migrate and/or python manage.py makemigrations, here I see the following errors: (venv) PS D:\Workfolder_Web\testProject\backend\project> python .\manage.py migrate Traceback (most recent call last): File ".\manage.py", line 21, in <module> main() File ".\manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\Workfolder_Web\testProject\backend\venv\lib\site-packages\django\core\management\__init__.py", … -
Can someone toll me if it's possible to use request.POST in manager
whatever i try, i'm getting the error: 'QueryDict' object has no attribute 'POST' class ChargeManager(models.Manager): def charge_credit_card(self, amount, request, *args, **kwargs): """ Charge a credit card """ creditCard.cardNumber = self.request.POST.get('card_number') creditCard.expirationDate = self.request.POST.get('expir_date') -
Django OnetoOne Field not Populating
I have a model which is named 'client. It's defined in models in part as the following: class Client(models.Model): username = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) I've run makemigrations and migrations, but when I create a new client object and try to save it from forms I get and Integrity Error: NOT NULL constraint failed: intake_client.username_id. username_id is the field name Django automatically generates with the migration, but saving these forms results in this field containing a null value and is not being generated automatically as a dependency by Django. If I set primary key to true in the username, it works ok, but then I have problems deleting the objects because Django says the model does not have an "id" field (since it is now changed to username_id). Why is Django not generating and putting the dependency values in the username_id field automatically when the instance is saved? -
Creating two objects with one save statement Django (Don't want to)
When I click on save in the view, two instances of the Opportunity are created. The only line of code that creates anything in the database is new_opp.save. I'm new to this and can't figure out how to only make one Opportunity object in the code. Views.py forms.py urls.py InitialForm.html -
Django: TypeError in View that I cannot spot
I am making registration form in django. I have followed Set up subdomains for tenants in a Django web app? example but I get the following error. Traceback (most recent call last): File "/Users/pierre/Desktop/Django-app/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/pierre/Desktop/Django-app/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/pierre/Desktop/Django-app/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: __init__() takes 1 positional argument but 2 were given Its been hours and I cannot see where it comes from. I am hoping that a pair of fresh (and more experienced) eyes could see my mistake. Here are the files I am working with: models.py class Client(TenantMixin): name = models.CharField(max_length=100, default='') email = models.EmailField(default='') company = models.CharField(max_length=100, default='') password = models.CharField(max_length=100, default='') paid_until = models.DateField() on_trial = models.BooleanField() created_on = models.DateField(auto_now_add=True) # class Domain(DomainMixin): pass forms.py class NewClientForm(forms.ModelForm): name = forms.CharField(max_length=100) email = forms.EmailField(max_length=100) company = forms.CharField(max_length=100) password = forms.CharField(widget = forms.PasswordInput) def clean(self): email = self.cleaned_data.get('email') company = self.clean_date.get('company') email_qs = Client.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError( "this email is already being used" ) company_qs = Client.objects.filter(company=company) if company_qs.exists(): raise forms.ValidationError( 'this company name is already identified in our system' ) return email, company view.py class SignupView(View): … -
'microsecond' is an invalid keyword argument for replace()
I am using Django 2.0+ and am attempting to just plug in the existing password reset function into my website. If the email does not exist, it successfully submits. If it DOES exist, I get this error: 'microsecond' is an invalid keyword argument for replace() I never touched any of the backend code for this function so I would assume it would just work out of the box. Traceback: C:\Users\djank\documents\github\lfgm_2019\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) … ▶ Local vars C:\Users\djank\documents\github\lfgm_2019\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars C:\Users\djank\documents\github\lfgm_2019\lib\site-packages\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\djank\documents\github\lfgm_2019\lib\site-packages\django\views\generic\base.py in view return self.dispatch(request, *args, **kwargs) … ▶ Local vars C:\Users\djank\documents\github\lfgm_2019\lib\site-packages\django\utils\decorators.py in _wrapper return bound_method(*args, **kwargs) … ▶ Local vars C:\Users\djank\documents\github\lfgm_2019\lib\site-packages\django\utils\decorators.py in _wrapped_view response = view_func(request, *args, **kwargs) … ▶ Local vars C:\Users\djank\documents\github\lfgm_2019\lib\site-packages\django\contrib\auth\views.py in dispatch return super().dispatch(*args, **kwargs) … ▶ Local vars C:\Users\djank\documents\github\lfgm_2019\lib\site-packages\django\views\generic\base.py in dispatch return handler(request, *args, **kwargs) … ▶ Local vars C:\Users\djank\documents\github\lfgm_2019\lib\site-packages\django\views\generic\edit.py in post return self.form_valid(form) … ▶ Local vars C:\Users\djank\documents\github\lfgm_2019\lib\site-packages\django\contrib\auth\views.py in form_valid form.save(**opts) … ▶ Local vars C:\Users\djank\documents\github\lfgm_2019\lib\site-packages\django\contrib\auth\forms.py in save 'token': token_generator.make_token(user), … ▶ Local vars C:\Users\djank\documents\github\lfgm_2019\lib\site-packages\django\contrib\auth\tokens.py in make_token return self._make_token_with_timestamp(user, self._num_days(self._today())) … ▶ Local vars C:\Users\djank\documents\github\lfgm_2019\lib\site-packages\django\contrib\auth\tokens.py in _make_token_with_timestamp self._make_hash_value(user, timestamp), … ▶ Local … -
Django HTML iterate trough a dynamic dictionary name
I'm trying to create a website where part of the website I'm using dynamic tabs in html where each tab will show different data. Now what I'm trying to do is that in the views.py I'm creating different dictionaries for the different tabs. So far I have created the below in the views.py file. def display_rpt (request): alltrasfData={} sec = Section.objects.all() for key in sec: transactions = Transaction.objects.values('feast_year__title','feast_year','feast_group__title','section','section__short').filter(section_id=key.id).order_by('section','-feast_year','-feast_group__title').annotate(Total_income=Sum('income_amt'),Total_Expenditure=Sum('expenditure_amt')) subtotal = Transaction.objects.values('section','feast_year','feast_year__title').filter(section_id=key.id).annotate(Total_income=Sum('income_amt'),Total_Expenditure=Sum('expenditure_amt')) grandtotal = Transaction.objects.values('section').filter(section_id=key.id).annotate(Total_income=Sum('income_amt'),Total_Expenditure=Sum('expenditure_amt')) alltrasfData[f'transactions_{key.id}']=transactions alltrasfData[f'subtotal_{key.id}']=subtotal alltrasfData[f'grandtotal_{key.id}'] = grandtotal alltrasfData['sec']=sec return render(request, 'homepage/reports.html',alltrasfData) Just to give you an idea some dictionaries that there are in the alltrasfData are: 'transactions_1','transactions_2','transactions_3' Is there a way in Django html where I can iterate trough these different dictionaries with dynamic dictionary name. -
How can I switch between locale files?
I want to switch to Spanish locale file when I choose Spanish but nothing changes... I know by now how to use .translate and translate the website from the views but I want to change it in the html by java script... I'm using load i18n $('.switch-locale').click(function(e) { e.preventDefault(); $.i18n().locale = $(this).data('locale'); update_texts(); }); <html lang="en"> <body> <ul class="switch-locale"> <li><a href="" data-locale="en">English</a></li> <li><a href="" data-locale="es">Spanish</a></li> </ul> </body> </html> -
Django Rest Framework Stripe Integration
I'm currently using Django 2.2.6 along with Django Rest framework. What is the best library for integrating Stripe apis for a mobile client? Tried installing https://github.com/iktw/django-rest-framework-stripe but they seem to be no longer available. -
How to change the text position
I am new in programing industry especially in css/html stuff. Does someone of you know how to change the position of text or how to make another box/table with all that information beside the card with picture of actor? Do I have to make new div or something? Add something to css? enter image description here My css: body {background: url('/static/images/backkk.jpg'); } .navbar-inverse { background-color: #222; border-color: #080808; } .card{ display: inline-table ; justify-content: space-evenly; grid-template-columns: 300px; grid-template-rows: 330px 300px 40px; grid-template-areas: "image" "text" "stats"; border-radius: 7px; background: url('/static/images/back.jpg'); box-shadow: 7px 7px 7px rgba(252, 135, 2, 0.9); font-family: Arial, Helvetica, sans-serif; text-align: center; border:3px solid rgb(255, 189, 7); } /*height card*/ .card-text { grid-area: text; margin: 25px; } /* pilot*/ .card-text p { color: rgb(16, 207, 144); font-family: 'Times New Roman', Times, serif; font-size:17px; font-weight: 300; border:"3px solid #73AD21"; text-align: center } .card-text h2 { margin-top:20px; font-size:23px; } /* lenght of card*/ .card { transition: 0.5s ease; cursor: pointer; margin-top:-200px; right: -30%; width: 300px; height: 35rem; } and my html <!DOCTYPE html> <html> <body> <div class="card" > <div class="card-image"> <img src="{{ actor.picture }}" alt="No poster in datebase" width="289" height="345"> </div> <div class="card-text"> <h2> <a href="/actors/actor_detail/{{actor.id }}">{{ actor.name }}</a> </h2> </div> … -
Django Chrome Browser Disable Styling/Scripts On Sitemap.xml and Robots.txt
I noticed in django-csp the sitemap.xml file displays styling and scripts on chrome browsers but firefox displays "This XML file does not appear to have any style information associated with it. The document tree is shown below." Is there a way to programmatically in Django to tell chrome not to process any styling or scripts for the sitemap.xml file or even the robots.txt? CSS: /* Copyright 2014 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ div.header { border-bottom: 2px solid black; padding-bottom: 5px; margin: 10px; } div.collapsible &gt; div.hidden { display:none; } .pretty-print { margin-top: 1em; margin-left: 20px; font-family: monospace; font-size: 13px; } #webkit-xml-viewer-source-xml { display: none; } .collapsible-content { margin-left: 1em; } .comment { white-space: pre; } .button { -webkit-user-select: none; cursor: pointer; display: inline-block; margin-left: -10px; width: 10px; background-repeat: no-repeat; background-position: left top; vertical-align: bottom; } .collapse-button { background: url("data:image/svg+xml,&lt;svg xmlns='http://www.w3.org/2000/svg' fill='%23909090' width='10' height='10'&gt;&lt;path d='M0 0 L8 0 L4 7 Z'/&gt;&lt;/svg&gt;"); height: 10px; } .expand-button { background: url("data:image/svg+xml,&lt;svg xmlns='http://www.w3.org/2000/svg' fill='%23909090' width='10' height='10'&gt;&lt;path d='M0 0 L0 8 L7 4 Z'/&gt;&lt;/svg&gt;"); height: … -
get full User object on post_save signal
I am new to signals. What I want to do could be done on views pragmatically and perhaps signals is not the way to go but regardless, I am having issues with the signal. I have a User model (custom) and UserIdentities model. When a new user is created, 3 identities will be generated and saved in UserIdentities model: User(models.Model): fields... UserIdentities(models.Model): user = models.ForeignKey(User) @receiver(post_save, sender = User) def user_created(sender, instance, created, raw, **kwargs): if created: # generate three dept identities and save in UserIdentities model identities = generate_identiteies(instance) The issue I am having now is that instance is username (a single string), not an instance of User object with all attributes of the user. In the documentation, it says instance is the object that was created but here I am getting only the username of the user created but need a couple of other fields needed for identity generation -
how to remove duplicate queries in django admin add_view/change_view?
i got 2 duplicate queries in django admin add_view/change_view because of foreign key fields in my model. how to remove these duplicate queries in django admin add_view/change_view. not the list_view. -
Pass OneToOne relationships to Django Templates
I am trying to setup a OneToOne relationship in Django in order to show data from TableA and TableB for a specific record. I am having issues figuring out how to display it in my view, examples are out there but some seem a bit outdated or have solutions that I am not familiar with. I have tried with some different calls in the views file as well as in my templates file without any luck, any input would be highly appreciated! My models.py from django.db import models # Create your models here. class tableA(models.Model): created = models.DateTimeField(default=None) published = models.CharField(max_length=50, default=None) publisher = models.CharField(max_length=50, default=None) code = models.CharField(max_length=25, null=True, unique=True) class Meta: db_table = 'tableA' unique_together = (("publisher", "published"),) def __str__(self): return self.created class tableB(models.Model): tableA = models.OneToOneField(tableA, on_delete=models.CASCADE, primary_key=True, default=None) code = models.CharField(max_length=50, default=None, null=True) url = models.CharField(max_length=100, default=None, null=True) class Meta: managed = True def __str__(self): return self.tableA.code My views.py def nani(request): data = TableA.objects.all() return render(request, 'site/home.html', {'data':data}) My template {% for test in data %} <tr> <td>{{ test.published }}</td> <td>{{ test.publisher }}</td> <td>{{ test.TableB.url }}</td> </tr> {% endfor %} -
Class relationship in Django model
My project(Django Rest Framework) is blog app where logged in users can Post some texts and any logged in users can add comment to Posts. What are the changed I need to make in the Post and Comment class to establish the logic ? from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings class User(AbstractUser): #User model class Post(models.Model): postdata = models.CharField(max_length=100) owner = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) class Comment(models.Model): body = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) -
What does this html tag mean in django's example?
This is django's polls demo, and most are well documented. However, in this part: https://docs.djangoproject.com/en/3.0/intro/tutorial04/ <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'polls:detail' question.id %}">Vote again?</a> The documentation doesn't say anything about this part: vote{{ choice.votes|pluralize }} And from the generated html page, I can't see what's the role of this piece? -
Which django field should be used for a time counter?
I need a field in the model for a required work hours. For example, with default value 40 hours. Which field I should use? -
Sending pop-up notification to specific users in Django
I am working on a notification part of a Django project where 1. an user can create a project (selecting users to work with), and 2. create a meeting (the creator can edit or cancel by changing the meeting location or time), and 3. invitees can vote for a preferred time and eventually decide the meeting time where the majority agrees with. My part is to send any types of notification to those invitees when cases 1-3 happen. For example in cases 1 and 2, I wanna implement the way to give invitees pop-up notifications when the creator submits the form, and for case 3, I want invitees to be notified when each invitee votes. class Notification(models.Model): created = models.DateTimeField(auto_add_now=True) text = models.TextField() users = models.ManyToManyField(User, through='NotificationUser') class NotificationUser(models.Model): created = models.DateTimeField(auto_add_now=True) updated = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) notification = models.ForeignKey(User,on_delete=models.CASCADE) read = models.DateTimeField(null=True, blank=True) I have written models for the notification (feel free to give me advice for better models), but I can’t really think of the best way to send those invitees pop-ups (In view). Even if it’s not a pop-up notification, as long as you have a better or easier idea to implements, please help me! … -
Argument must be int or float
When I typed "Product.objects.get(id=1) on the python shell, I got this error "TypeError: argument must be int or float". What could be the cause of this error? -
Bootstrap scrollbar slipped behind content
I am working on a webpage using Bootstrap 4 and after fixing the appearance of a horizontal scrollbar on mobile devices by adding overflow-x:hidden to the html tag I noticed that the main y scrollbar looked weird and was not clickable most of the time anymore (normally it can be pulled with the left mouse button, but it does not react to clicks now. It does, however, register clicks on content that is behind the scrollbar!). It has definitely not been like this for long, but I have not the faintest idea what caused this change since I did not touch any z-index or scrollbar settings... I am using Chrome and it should display the standard, unstyled scrollbar, which does not look like this. Can anyone tell me what happened and how to fix it?!