Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I test the URLS for my Class Based Views in Django?
I'm trying to test the URL resolutions for my first Django project- I have successfully tested my function-based views, however I am having trouble testing my Class Based Views. I'm getting the below error when I run the test on my CBV: AssertionError: <function UpdateHealth at 0x7f538f023e50> != <HealthHub.views.UpdateHealth object at 0x7f538d7aec10> Tests.py (CBV test in question): def test_health_hub_update_url_is_resolved(self): url = reverse('HealthHub:health_hub_update') self.assertEqual(resolve(url).func, views.UpdateHealth()) views.py (view in question): class UpdateHealth(View): '''View for the Update Health page. Uses StatUpdateForm to allow the user to update their stats.''' def get(self, request, *args, **kwargs): stats = HealthStats update_form = StatUpdateForm context = { 'stats': stats, 'update_form': update_form, 'user': stats.user, 'weight': stats.weight, 'date': stats.date, } return render(request, 'health_hub_update.html', context) def post(self, request, *args, **kwargs): update_form = StatUpdateForm(data=request.POST) if update_form.is_valid(): obj = update_form.save(commit=False) obj.user = request.user obj.save() return redirect("HealthHub:health_hub") Urls.py: path('MyHealth/update', views.UpdateHealth.as_view(), name='health_hub_update'), Any help would be much appreciated, as I seem to have hit a dead-end. -
DJANGO: How can I create a custom User with a OneToOne relationship to Person
I have a custom user model, I would like my CustomUser model to have a OneToOne relationship with the Person model; Since I want to first register persons and then create a username for them, since not all registered people need to have a username. I have tried the code shown below; but what I get is the following error: Cannot assign "1": "CustomUser.dni" must be a "Person" instance. But, the ID number is already registered in the Person table P.S. If anyone has a better suggestion for getting people to register first and then create a username for them when strictly necessary, I'd really appreciate it. models.py from .managers import CustomUserManager class Person(models.Model): dni = models.CharField('Número de DNI', max_length=8, unique=True) ... class CustomUser(AbstractBaseUser, PermissionsMixin): dni = models.OneToOneField(Person, on_delete=models.CASCADE, unique=True) email = models.EmailField('Correo electrónico', max_length=355, unique=True) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'dni' REQUIRED_FIELDS = ['email'] ... managers.py from django.contrib.auth.models import BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self, dni, email, password=None): if not dni: raise ValueError('Debe ingresar el número de DNI.') person = self.model( dni=dni, email=self.normalize_email(email), ) person.set_password(password) person.save(using=self._db) return person def create_superuser(self, dni, email, password=None): person = self.create_user( dni, password=password, … -
How oauth works for saving users data?
I am building simple booking app in django, so flow of the app is that user's can do a booking and then their bookings will be saved into the database, However as I'll be using oatuh in my app, So my question is if user has made a booking and I want to fetch all of the bookings user's has made how do I implement this using oauth? what data of user data do I store in my own database so that each time user login using oauth I can fetch specifically that user's data (bookings). -
Passing variable into custom template filter
I've got the following custom filter myfilters.py @register.filter def my_custom_filter(value, arg): some python stuff Within my template, I'm registering the filters {% load myfilters %} I'm then applying the template tag and then trying to pass in the variable a_template_value {{ form.body|my_custom_filter:{{a_template_value}}|safe }} I'm then getting the following error: my_custom_filterrequires 2 arguments, 1 provided Thanks! -
How to make nginx serve static files from multiple directories for django project?
I have a django project. It has static files in multiple applications, that I can put together by running python3 manage.py collectstatic. All files will be moved to the static folder, which is located in the root folder of my project. Additionally, I have 200GB pictues, located in another folder /var/images/user-profile-images/subfolder/image.jpg. In both cases image url is like so: /static/path-to-image. So in first case I have static folder, in second case I don't have. this is my location block: location ~ ^\/static\/(.*) { try_files /project-root-folder/static/$1 /var/images/user-profile-images/$1; } it is supposed to serve urls /static/style.css and /static/subfolder/image.jpg respectively, but doesn't work in both cases. I have double checked everything many times, searched around stackoverflow, but no answer. Seems it's also not possible to debug this, since nginx is not logging not found cases. Actually, I see django 404 error, so probably it does not even match. -
Django static css doesn't make any change and images don't appear
Django static files are not working in my application, I defined STATICFILES_DIRS, STATIC_URL, and STATIC_ROOT in settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'social_media') ] and here's base.html: {% load static %} <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type= "text/css" href="{% static 'style.css' %}"> </head> <body> {% block navbar %} {% include 'parts/navbar.html' %} {% endblock %} {% block content %} {% endblock %} </body> </html> I use this in my pages: {% extends 'base.html' %} {% load static %} {% block content %} <!--stuff--> {% endblock content %} I tried using InPrivate(incognito but MS Edge version) window and nothing changed, I also tried deleting style.css file and making it again and collecting static files again but it also didn't work. -
How can I ensure enough space is left to avoid content moving down the page if a warning message appears?
I have a server-side rendered application (Django) with a login page which provides a username and password field, submit button, instructions for forgotten password and so on. This is what I will call the "main content". Sometimes, there will an extra div above the main content with a message such as "Invalid username or password". I would like it so that if the user submits an invalid login and this message appears, the main content doesn't move. (I'm aware that this will involve leaving a white space above the main content, but there's a lot of blank space on this page anyway so it doesn't matter) I considered rendering <div class="warning-message">Invalid username or password</div> if required and some kind of placeholder <div class="placeholder"></div> otherwise, but I was struggling to style them so that the empty div would always be the same height as the warning message one. I did also consider positioning either the main content or the warning message with position:absolute, but this sometimes leads to overlapping on small screens. -
error rendering the page template when placing the site on Heroku
Good afternoon. I have a problem with a website that I posted using the Heroku platform. The error "Error during template rendering" occurred. The most interesting thing is that everything works fine on the local server. I tried to re-upload the project to Heroku, but it didn't give any results. -
Django hide password fields on user creation form
I have a custom user model and a form that allows admins to add users without having to go to the admin section. I want hide the password fields and set the password to a random generated string. Then send an email to the new user with a link to reset their password. So far I haven't been able to figure out the first part - hiding the password fields. The form.py: from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class AddCompanyEmployeeForm(UserCreationForm): class Meta: model = CustomUser fields = UserCreationForm.Meta.fields + ('email', 'full_name', 'age') the view: from django.views.generic import CreateView, ListView from django.urls.base import reverse from .forms import CustomUserCreationForm, AddCompanyEmployeeForm from .models import CustomUser class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' class AddCompanyEmployee(CreateView): model = CustomUser template_name = 'manage/add_employee.html' form_class = AddCompanyEmployeeForm #success_url = reverse_lazy('directory') def get_success_url(self): return reverse('userprofile_detail', kwargs={'pk': self.object.userprofile.pk}) I have tried a number of approaches including changing the form to class AddCompanyEmployeeForm(UserCreationForm): class Meta: model = CustomUser fields = ('email', 'full_name', 'age') So far the password fields continue to be visible regardless of what I try. Any suggestions? -
Someone help me in this error TypeError at /contact 'method' object is not subscriptable
Views.py # Create your views here. def home(request): return render(request, 'home.html') def about(request): return render(request, 'about.html') def project(request): return render(request, 'project.html') def contact(request): if request.method=='POST': name=request.POST.get['name'] email=request.POST.get['email'] phone=request.POST.get['phone'] concern=request.POST.get['concern'] print(name,email,phone,'concern') obj=Contact(name='name', email='email',phone='phone',concern='concern') obj.save() return render(request, 'contact.html') I am trying to connect my contact form with database but after post method it doesn't allow me. -
I am trying to render docx file in my django project, using the data from JSON field, but it couldn't find the docx file in my system
This is my views.py from pathlib import Path from django.conf import settings from rest_framework import viewsets from rest_framework import mixins from rest_framework.decorators import action from django.http import HttpResponse from . import models from . import serializers from docxtpl import DocxTemplate import pypandoc class TemplateViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet, ): queryset = models.Template.objects.all() serializer_class = serializers.TemplateSerializer def get_serializer_class(self): return { 'list': serializers.TemplateSerializer, 'retrieve': serializers.TemplateSerializer, 'generate_document': serializers.DocumentGenerateSerializer, }.get(self.action, serializers.TemplateSerializer) @action(detail=True, url_name='generate-document', methods=['POST', 'GET']) def generate_document(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) context_data = serializer.data['context'] document_extension = serializer.data['extension'] instance = self.get_object() versions = instance.versions.all() documents = versions.get(id=instance.id) document = DocxTemplate(open('src/media/{}'.format(documents.upload.name.split('.')[0] + '.docx'))) # document = documents.upload document.render(context_data) if document_extension == 'docx': response = HttpResponse(document, content_type='application/vnd.openxmlformats-officedocument' '.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename="{}"'.format(document.name.split('.')[0] + '.docx') return response else: pypandoc.convert_file(document, 'pdf', outputfile=document) response = HttpResponse(document, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="{}"'.format(document.name.split('.')[0] + '.pdf') return response This is my forms.py, where I am getting JSON field from django import forms from django.contrib.auth import get_user_model from .models import Template, Version User = get_user_model() class TemplateCreationForm(forms.ModelForm): class Meta: model = Template fields = ('name',) def save(self, commit=True): self.instance.user = self.request.user return super().save(commit) class VersionCreationForm(forms.ModelForm): class Meta: model = Version fields = ('template', 'upload', 'start_from', 'end_to') Template is being created through my … -
Api for Shoping App (Flutter) with Python
I need to make an Api to use for a shopping app built with Flutter and i want to use Python to as i already have decent exprince in and i heard that it could be done using Python and Django as a database I never tried to do so before -
Why shows this error when adding the file "Object of type InMemoryUploadedFile is not JSON serializable"?
My target is to build a form that besides charfields will have a file field and all data of the fields will be stored in the database. The form does store the charfield's data, but after adding a new field as filefield It not working when I submit, and shows the below error😥. Why is not store the filefield's data? views.py: def employeeListView(request): if request.method == 'POST': serializer = EmployeeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return redirect("/") def InsertAndInfo(request): if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') file = request.FILES['filedf'] #if 'filedf' in request.FILES else None data = { 'name':name, 'email':email, 'phone':phone, 'file':file } headers = {'Content-Type': 'application/json'} requests.post('http://127.0.0.1:8000/api/employees/',json=data,headers=headers) return redirect("/api/") employeeInfoApiLink = requests.get('http://127.0.0.1:8000/api/AllElmployeeInfo/').json() context = { "employeeInfo":employeeInfoApiLink } return render(request, 'InsertAndInfo.html',context) models.py: class Employee(models.Model): name = models.CharField(max_length=30) email = models.EmailField(max_length=30) phone = models.CharField(max_length=30, null=True) file = models.FileField(upload_to="file/",null=True) serializer.py: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = "__all__" form.html: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="text" class="form-control" name="name" id="name"> <input type="email" name="email" class="form-control" id="email" aria-describedby="emailHelp"> <input type="text" name="phone" class="form-control" id="phone"> <input type="file" name="filedf" class="form-control" id="file"> <button type="submit" class="btn btn-primary">Submit</button> </form> -
Django Channels on azure
I can't connect to the websocket in my azure app. To be concise my issue is exactly same as this question. I saw its answer too and it says that custom port 6379 is not allowed. Is there any way for this to work. How can I add the port 6379 to my web app. Or if not Are there any alternatives? -
Getting the average rating from a book in a bookstore api
Written in python. I am having an issue that the average won't work on my code. I don't know if I can use annotate or aggregate. I want it so I can choose what book I want and show the average once I choose it. class AverageRatingViewSet(generics.ListAPIView): serializer_class = BookratingsSerializer def get_queryset(self): queryset = Bookratings.objects.all() try: user_input = self.request.query_params.get('rating') except AttributeError as abc: return Bookratings.objects.none() if user_input is not None: **** ***queryset = queryset.filter(bookid=user_input).aggregate(Books_average=Avg('rating')*)**** ** return queryset I started messing around with the queryset.filter but I keep getting error on the local host -
Trigger python script with Django user input
I am trying to trigger a pyfirmata script that will load onto an arduino device when a user checks a checkbox on a django view. I am trying to implement some comparison code in my view that will check if user submitted check box is true then trigger pyfirm.py. Background: Py firmata will drive the arduino pins directly without needing an arduino IDE. Should I hard code my pyfirmata in my view or can I trigger a full script some how? Iam using a raspberry pi as a single board computer that is connected to arduino as a device driver. I am considering the pi device as a user. Any tips on this? I have my check box working and i am printing the POST results to the terminal. just need to check if box is true and trigger script some how. Haven't had any luck triggering a script. I see a couple questions related to this but i am curious for pyfirmata specific directions on this. -
Loading choices from utils.py results in unexpected error: TypeError: 'CharField' object is not iterable in Django
I have a models.py file in Django, and it was working perfectly. I have an extensive model named Media, and since it contains quite some columns with elaborate choices in nested tuples, I decided to move these nested tuples to an utils.py file located in the same app. I found that it is working for all columns in my Media model, except for one. It is shown below: #This was how it was initially and working: #Umbrella UMBRELLA = ( ("DH", "DH"), ("SE", "SE"), ("PA", "PA"), ("PF", "PF") ) class Media(models.Model): umbrella = models.CharField(max_length=20, choices=UMBRELLA, default='Undefined', null=True, blank=True) second_umbrella = models.CharField(max_length=20, choices=UMBRELLA, default='Undefined', null=True, blank=True) #Problematic? Changed it to: utils.py: #Umbrella def UMBRELLA(): UMBRELLA = ( ("DH", "DH"), ("SE", "SE"), ("PA", "PA"), ("PF", "PF")) return(UMBRELLA) models.py: from database.utils import * umbrella=UMBRELLA() class Media(models.Model): umbrella = models.CharField(max_length=20, choices=umbrella, default='Undefined', null=True, blank=True) #This one is not problematic second_umbrella = models.CharField(max_length=20, choices=umbrella, default='Undefined', null=True, blank=True) #This one is problematic The strange thing here is that if I only change (first) umbrella choiches to umbrella from utils.py it works fine. However, if i change choices from second_umbrella to umbrella from utils.py it crashes?? I meticulously checked the db.sqlite3 with django admin, but the choices … -
Django AttributeError: 'list' object has no attribute 'sort_values'
I'm getting AttributeError: 'list' object has no attribute 'sort_values' in below code, task.py: from __future__ import absolute_import,unicode_literals from celery import shared_task from time import sleep import eda import os @shared_task def aync_task(amz_columns_dict, download_path, file_name, data): sleep(10) eda_object = eda.eda(col_dict=amz_columns_dict) save_path = download_path name_of_file = file_name file_path = os.path.join(save_path, name_of_file+".html") eda_object.create_report(data=data, filename=file_path) return 'task complete' views.py : def eda_flow(request): path = '/Unilever/satyajit/us_amz.csv' mode = 'rb' df = pd.read_csv("/home/satyajit/Desktop/opensource/data/us_amz.csv", low_memory=False) df = df.head(100) json_records = df.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) context = {'data': data, 'message': 'data loaded successfully.'} if request.method == 'POST': id_col = request.POST.get('id_col') file_name = request.POST.get('file_name') download_path = request.POST.get('download_path') amz_columns_dict = {'id_col': id_col} try: if os.path.exists(download_path): status = aync_task.delay(amz_columns_dict, download_path, file_name, data) return render(request,'home/index.html', {'message': 'Save Complete'}) else: return render(request,'home/index.html', {'message': 'download path is not exist'}) except Exception as e: print('error is---->', e) return render(request,'home/index.html', {'message': 'Error while generating EDA'}) return render(request, "home/tables-simple.html", context) The error of this code on below as screenshot: I've also tried to search similar question here (similar question) but that does not helpful to me. Any help would be much appreciated. thanks in advance. -
How to modify a Django date with SQL code?
I have a Django model with a number of minutes. These minutes must be added to a date. The date being before 0 B.C., I want to work with SQL code. I don't know if I'm writing it the right way, I don't have a desired result. How could I improve it? datetri = models.FloatField(db_column='DateTri', blank=True, null=True) @property def event_sql(self): query = '''DECLARE @StartTime DATETIME = '-500, 1, 1' SELECT DATEADD(MINUTE(@StartTime), @datetri)''' with connection.cursor() as cursor: cursor.execute(query) return event_sql -
Every form validation in formset
Some troubles with validation. I'm using this construction in my template: <form method="POST"> {% csrf_token %} {{ formset.media.js }} {% for form in formset %} <p>{{ form }}</p> {% endfor %} <button type="submit" class="btn btn-primary">Send</button> And this validation in views: def flow_type(request): patternFormset = modelformset_factory(CashFlowPattern, fields='__all__') if request.method == 'POST': formset = patternFormset(request.POST) if formset.is_valid(): formset.save() formset = patternFormset() template = 'cash_table/index.html' context = { # 'form': form, 'formset': formset } return render(request, template, context) I get form at page but nothing happens after submit. But if I use another template construction it works: <form method="POST"> {% csrf_token %} {{ formset.media.js }} {{ formset }} <button type="submit" class="btn btn-primary">Send</button> </form> But then I get all fields of new form at the same line. -
django rest freamwork comment
I have two questions about creating messages about products. My first question is why do I have to provide the user and product fields in Insomnia. Because in the creation function, I specified how the user and the product should be stored in the database. My second question is why should I use valve because if I don't use it, it gives me the following error: Field 'rate' expected a number but got <BoundField value=5 errors=None>. class CommentProduct(APIView): serializer_class = CommentSerializer def post(self, request, *args, **kwargs): product = Product.objects.get(id=kwargs['pk']) serializer = self.serializer_class(data=request.POST) if serializer.is_valid(): Comment.objects.create(user_id=request.user.id, product_id=product.id, comment=serializer['comment'].value, rate=serializer['rate']) return Response(serializer.data) return Response(serializer.errors) -
How to fetch object in create method?
Need help on fetching the value in my view method. Hello! I'm trying to fetch the value of my requesterid. I want to create a condition that if requesterid is equal to a certain value, it will allow the create method. I don't know how I will access the variable. Can someone help me on this? I have this in my code so far, but it says that "Error": "'Request' object has no attribute 'requesterid'" Here's my views.py class RequestListCreateView(ListCreateAPIView): queryset = requestTable.objects.all() serializer_class = RequestCreateSerializer def create(self, request, *args, **kwargs): if request.requesterid.userroleid == 3: write_serializer = RequestCreateSerializer(data=request.data) write_serializer.is_valid(raise_exception=True) instance = self.perform_create(write_serializer) headers = self.get_success_headers(write_serializer.data) return Response({"Request ID": write_serializer.instance.requestid, "Parts ID": [p.partsid for p in write_serializer.instance.parts.all()]},headers=headers) raise ValidationError("Sorry! Your role has no permission to create a request.") Here's my models.py class userTable(models.Model): userid = models.UUIDField(primary_key=True, default = uuid.uuid4, editable=False) username = models.CharField(max_length=50, null=False, unique=True) userroleid = models.ForeignKey(roleTable, on_delete=models.CASCADE) class roleTable(models.Model): roleid = models.IntegerField(null=False, primary_key=True) role = models.CharField(max_length=255, null=False) class requestTable(models.Model): rid = models.AutoField(primary_key=True) requesterid = models.ForeignKey(userTable, on_delete=models.CASCADE) (...) -
Django - how to update multiple rows using a checkbox
I want to update a boolean to 'True' in bulk for all the rows in a table. I want to update the age of which the people have a qualified age using a form checkbox for multiple rows The code is Class Age(models.Model) Name = models.CharField(max_length=100) age = models.IntegerField() qualified_age = models.BooleanField(default='False) Views.py def Home(request): context = [] list = Age.objects.all() if request.method == 'POST': list_data = request.POST.getlist('instance') for data in list_data: Age.objects.filter(id=data).update(qualified_age=True) return redirect(Home) context{ list:'list', } return render(request, 'index.html', context) Index.html <tr> <th> Change Bool Value </th> <th> Names </th> <th> Ages </th> </tr> <form method='post', action=' '> {% for data in List %} <tr> <td> <input type="checkbox", value=" {{data.id}} ", name="instance"> </td> <td> {{data.Name}} </td> <td> {{data.age}}</td> </tr> {% endfor %} </input type="submit", value="Update"> </form> I want to update all the rows all at once but it's not working... Could anyone please assist...¿ -
Is is possible to use ThreadPoolExecutor inside django views?
I have a view that has to cooperate with another service and thus make a bunch of requests to that third-party service. In my project I use Django==1.1.16 and python 3.6 Is is possible to use ThreadPoolExecutor from concurrent.futures inside a django view to concurrently make a bunch of requests to another service and take advantage of this I/O operation inside my view? Any tips or advices? Celery is not an option in that case. Out simple infrastructure do not support that. -
POST json object but QueryDict is empty
I want to post an obj to Django server, but the QueryDict is always empty. Client side: function makeRequest (method, url, data, datatype) { function msg (err, datums) { if (err) { throw err; } console.log(datums); } var xhr = new XMLHttpRequest(); xhr.open(method, url,true); // X-CSRFToken xhr.setRequestHeader('X-CSRFToken', csrftoken); xhr.setRequestHeader("Content-Type", datatype); xhr.onload = function () { msg(null, xhr.response); }; xhr.onerror = function () { msg(xhr.response); }; xhr.send(data); } var params = { "range":"Sheet1!A4:C4", "majorDimension": "ROWS", "values": [ ["Hello World","123", "456"] ], } makeRequest('POST', "http://127.0.0.1:8000/update_student/1/",JSON.stringify(params) , 'application/json'); Server side: def update_student(request,pk): if request.method =="POST": print("update_student entered") breakpoint() return HttpResponse("a post method", status=200) else: return HttpResponse("This should be a POST method", status=400) I checked the payload when the post is sent, it's not empty.