Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django ConnectionAbortedError [WinError 10053]
So im facing a weird issue while making a request to my api. It works fine using something like postman. I get my response no issue but if I make a request from my frontend(on a seperate domain) the connection gets closed for some reason. Here is my code I make ajax request using axios axios.get(mydomain/api/oauth) .then(response => { console.log(response) }).catch(error => { console.log(error.response.data) }) which hits my backend method that should return a response like so def oauth(request): auth_client = AuthClient( settings.CLIENT_ID, settings.CLIENT_SECRET, settings.REDIRECT_URI, settings.ENVIRONMENT ) url = auth_client.get_authorization_url([Scopes.ACCOUNTING]) request.session['state'] = auth_client.state_token return HttpResponse(url) But at this point I get this alarm ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine And like I said if I make this same request through postman I get my response. So I don't know what I am missing. I have applied cors thinking maybe its because my frontend is on seperate domain from backend but no luck. Plus the alarm is kind of vague... anybody face similar issue? -
Ajax in Django To Populate Form Field
I am trying to learn to use ajax and could use some help. I want to click a button and have that populate a django form field, Exporter. Here is what I have. I know my script is not sufficient, but I am novice and would hope to use this as a functioning example for myself. So upon click of button #populate, the Exporter form field should populate with 'Me'. Thanks! views.py def Ajax(request): if request.is_ajax(): exporter = 'Me' data = json.dumps(exporter) return HttpResponse(data, content_type='application/json') proforma.html <button id="populate"> Populate </button> ... <table class="table2" width=100%> <tr class="bigrow"> <td rowspan = 2 >Exporter: {{form.Exporter}}</td> <td colspan = 2 >Pages:</td> </tr> </table> ... $("#populate").click(function() { $.ajax({ url: "/ajax/more", success: function(data) { $("#exporter").load(); } } }); }); </script> forms.py class ProformaForm(forms.ModelForm): class Meta: model = Proforma fields = [ 'Name', 'Shipment', 'Exporter'] widgets={ 'Exporter': forms.TextInput(attrs={'id': 'exporter'}), } -
How to make forms dynamic in Django
This question is more theoretical than practical. So, this is a Django project about tracking workouts. I have several models in this project. 1) Workout. It contains fields user and date. 2) Exercise. It contains fields workout (which connects to the model above), name, sets, repetitions, and weight. My idea is as follows: You have an HTML table for each of the workouts, which contains each exercise in a new row. You can add and delete exercises "on the fly" by adding or deleting rows and the data inside <td> tags is editable in the table itself. My question is: 1) How to implement the models (or forms) into an HTML table and make the data editable. 2) How to save models automatically. Kind of like auto-save in Google Docs or something like that. This includes the addition or deletion of exercises and the information about them. I understand that this is a lot to ask, so replies about any part of the project are welcome. I also suspect that a REST API will be needed for this. I have not explored what that is in-depth and how that might help me solve my problem. So, if that is the … -
Displaying ModelAdmin fields in the same line issue
I delved in Django Documentation(https://docs.djangoproject.com/en/3.0/ref/contrib/admin/) and I found out I can display fields name in the same line by wrapping with tuple. So this is how I did: class MovieAdmin(admin.ModelAdmin): fields = (('title','length'),'release_year') admin.site.register(Movie, MovieAdmin) But my admin site shows only removed horizontal line between fields names, not displaying two names in the same line. Here's my screenshot: enter image description here Using Django 3.0.3, Python 3.8. Thanks. -
Deploy MAX (Model Asset Exchange) to Heroku
I want to deploy MAX model that is cloned from IBM's git repository to my heroku account. Can I deploy above git repository to my heroku account? And if so, is the way I will have to do same at the way of deploying original django or rails applications? -
I am not able to access my admin in Django
I have Ubuntu VM with Apache Server on which i am running my application. I have inserted some login and registration file using Filezilla. But my registration, Login and admin page is not working. It is giving me Exception Type: OperationalError Exception Value: attempt to write a readonly database I tried the following after doing some Stackoveflow. chown root db.sqlite3. Unfortunately, I still get the same error when trying to access above page. Any help would be greatly appreciated! Probably something to do with changing user permission which i have no idea where to start in diagnosing what permission issue is going on. -
django passwordless cannot create account
I got an unusual issue that I've stumbled upon when implementing django-rest-framework-passwordless. After integrating the module in my Django app when I make the first API request it gets processed, the user gets created and everything works flawlessly, but when attempting to create another account it crashes. IntegrityError at /passwordless/auth/email/ UNIQUE constraint failed: auth_user.username Request Method: POST Request URL: http://127.0.0.1:8000/passwordless/auth/email/ Django Version: 2.2.10 Python Executable: /home/terkea/django_react_template/src/venv/bin/python Python Version: 3.6.9 Python Path: ['/home/terkea/django_react_template/src', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/terkea/django_react_template/src/venv/lib/python3.6/site-packages'] Server time: Tue, 14 Apr 2020 02:04:41 +0000 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'corsheaders', 'rest_auth', 'rest_framework.authtoken', 'drfpasswordless', 'rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'api'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', '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'] As it says in the django.allauth docs I've disabled the username and made the email mandatory but for some reason, it doesn't wanna pick up on those changes. ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' -
Heroku admin page needs to be styled
I built a website using Django/bootstrap and launched with Heroku. The site looks great, but my admin page looks horrible. No styling. How can I apply styling to my https//mywebsite.herokuapp.com/admin/ page?? Thanks, Tad -
storing files in models.py from views.py
I am trying to fill a Django model field with a pdf that is altered by the user's input in views.py. My Models.py is structured like so: class Model(models.Model): file01 = models.FileField(upload_to=upload_location, null=True, blank=True) My Forms.py is structured like so: class Form(forms.ModelForm): class Meta: model = Apply fields = ['file01'] My Views.py is structured like so: def View(request): string = 'hello world' file01 = form.cleaned_data.get('file01') canvas = canvas.Canvas(BytesIO(), pagesize=letter) canvas.drawString(10, 100, string) canvas.save() BytesIO().seek(0) new_pdf = PdfFileReader(BytesIO()) existing_pdf = PdfFileReader(open("media/01.pdf", "rb")) page = existing_pdf.getPage(0) page.mergePage(new_pdf.getPage(0)) PdfFileWriter().addPage(page) PdfFileWriter().write(open("newfile01.pdf", "wb")) #Here is where I hit a wall VVV file01 = 'newfile01.pdf' form.save() return redirect('home') the string is successfully printing on the document but it is being output to src directory. I am struggling to find an example of a situation like this in the Django docs (storing of altered files in models.py). Any help would be greatly appreciated, including links to related Django documentation. -
Django Robots.txt Change Content-Type Header
Firefox error: The character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature.+ Using https://django-robots.readthedocs.io/en/latest/ It should probably be: content="text/html; charset=utf-8" or "text/plain; charset=UTF8" not 'text/plain' Current code: url(r'^robots\.txt/', include('robots.urls')), Alternatives? path('robots.txt', TemplateView.as_view(template_name="robots.txt", content_type='text/plain')), url(r'^robots.txt', lambda x: HttpResponse("User-Agent: *\nDisallow:", content_type="text/plain"), name="robots_file"), How do you combine include('robots.urls') with the alternatives or is it not possible? curl -s -D - 127.0.0.1:8000/robots.txt/ HTTP/1.1 200 OK Date: Tue, 14 Apr 2020 01:05:52 GMT Server: WSGIServer/0.2 CPython/3.7.3 Content-Type: text/plain -
Creating and editing objects with different features Django
I'm new to web developing with Django. I'm creating a website where I have multiple objects with different features: Character: Name, description, morality, strength. Item: Name, description, owner. Adventure: Name, description, characters, places, duration. Some of this features are the same for the objects (like name and description) but some aren't. Users will be able to create and edit each one of these objects. I would like to not have to program code to create and edit each one individually and just have to do it once for an object that can be any of these and that will only have the features corresponding to that object, but I don't know how. I tried making an object with a type which would be "Character" or "Item" depending on what it was and then picking the features using an if Object.name == "Character" but that didn't work. What should I do? Another problem that I have is that for my Adventures I can only choose one character and I would like to be able to choose an undefined amount of characters. Since I'm still learning I'm not sure how to do that exactly. -
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.