Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to raise an exception in Django Rest Framework when getting a foreign key constraint violation
I have the following models: class Person(CustomModel): name = models.CharField(max_length=100, verbose_name=_("Nombre")) rolle = models.CharField(max_length=20, choices=ROLLE_CHOICES, verbose_name=_("Rol")) ascription_content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, null=True, blank=True, limit_choices_to={'model__in': ('state', 'location', 'store')}, help_text=_("Referencia foranea al modelo 'ContentType'")) ascription_object_id = models.PositiveIntegerField(null=True, blank=True, help_text=_("ID del registro en el modelo refenciado en el campo 'ascription_content_type'")) ascription = GenericForeignKey('ascription_content_type', 'ascription_object_id') class Sale(CustomModel): store = models.ForeignKey(inventory_models.Store, on_delete=models.PROTECT, related_name='sales', verbose_name=_("Tienda")) person = models.ForeignKey(Person, on_delete=models.PROTECT, related_name='sales', verbose_name=_("Vendedor")) timestamp = models.DateTimeField(auto_now=True, verbose_name=_("Fecha y Hora")) And I have the following method in a DRF ViewSet: def perform_sale(self): self.sale = models.Sale() self.sale.store_id = self.store self.sale.person_id = self.sales_person try: self.sale.save() except Exception as e: raise CustomValidation(e, 'sale', status.HTTP_400_BAD_REQUEST) The problem is that when I send a POST whit wrong data that causes a foreign key constraint violation, I am unable to raise an exception with a try-except clause. I can see the exception in the console, but I cannot catch it: -
Django: read parameters from POST request
I am adding recurring payment system using a payment gateway (cashfree payment gateway) to the website that I am developing. After the payment is processed then payment gateway redirects to my wesbite url with some parameters with POST request as given here. I am unable to read these parameters. This is my first web development project and I am little bit confused here. It was mentioned that it was POST request but in my backend request.method gives GET method. I am using below code @csrf_exempt @login_required def cashfree_response(request): if request.method == "POST": print('inside post method') if request.method == "GET": print('inside get method') sub_ref = request.GET['cf_subReferenceId'] How do I read cf_subReferenceId value and other parameters passed by the payment gateway? -
Django foreignkey in html and how to use the distinct method
How to display the enrolled subjects of the students in the html? class SubjectSectionTeacher(models.Model): Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True) Courses= models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,null=True,blank=True) Sections= models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE,null=True) Subjects= models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE,null=True) Employee_Users= models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE,null=True) class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,null=True) my views.py studentenrolledsubject= StudentsEnrolledSubject.objects.filter(Subject_Section_Teacher__in = teacher.values_list('id')).distinct().order_by('id') return render(request, 'Homepage/index.html', {"studentenrolledsubject":studentenrolledsubject} html {% for student in studentenrolledsubject %} <td>{{student.Students_Enrollment_Records}}</td> <td>{{student.Subject_Section_Teacher__Subjects}}</td> {% endfor %} btw i use distinct method because in my database StudentsEnrolledSubject i have the same student name (Students_Enrollment_Records) but different subject (Subject_Section_Teacher) just like this, result in html this is from the SubjectSectionTeacher is it possible to distinct it? -
Display a list of apps at root django
I'm trying to display a list of installed apps (ex: ['admin', 'polls']) at the root of my site. I have an app setup with templates, but I'm unable to figure out how to automatically retrieve a list of apps. -
context variables in DRF generic view
I'm trying to build some frontend stuff in DRF - react. someAPI should run a query against db using current logged user id as parameter. After some hours trying here and there, following code works, but Im not sure is the right way to do it as involves using mixins and function overriding. Question is, How can I achieve same result using generic DRF views? class someAPI(mixins.ListModelMixin, generics.GenericAPIView): serializer_class = someSerializer def get(self, request, *args, **kwargs): customRole = get_object_or_404(Role, user=request.user) self.queryset = ClassDependingOnRole.objects.filter(role=customRole.id) return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) -
How can I filter out instances of a subclass?
I am attempting to display all Event objects, but only one specific instance if it is also a RecurringEvent. models.py from slugify import slugify from django.db import models from django.shortcuts import render from home.models import TimestampedModel, NewsItem from locations.models import Location from .managers import EventManager, RecurringEventManager, RepeatInfoManager class Event(NewsItem): name = models.CharField(max_length=255) slug = models.SlugField(default='', max_length=255, null=True, blank=True) description = models.TextField(null=True, blank=True) all_day = models.BooleanField(default=False) date_start = models.DateTimeField() date_end = models.DateTimeField(null=True, blank=True) location = models.ForeignKey(Location, null=True, blank=True, on_delete=models.CASCADE) objects = EventManager() def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) class RecurringEvent(Event): info = models.ForeignKey('RepeatInfo', on_delete=models.CASCADE, default=None) objects = RecurringEventManager() class RepeatInfo(TimestampedModel): FREQUENCY_UNITS_CHOICES = [ (0, 'No Repeat'), (1, 'Day(s)'), (2, 'Week(s)'), (3, 'Month(s)'), (4, 'Year(s)'), ] ENDS_CHOICES = [ (0, 'Ends after maximum duration (1 year)'), (1, 'Ends on date'), (2, 'Ends after number of occurences'), ] weekly = models.BooleanField(default=True) frequency = models.PositiveSmallIntegerField(default=1) frequency_units = models.PositiveSmallIntegerField(default=0, choices=FREQUENCY_UNITS_CHOICES) ends = models.PositiveSmallIntegerField(default=0, choices=ENDS_CHOICES) ends_on = models.DateTimeField(null=True, blank=True, default=None) ends_after = models.PositiveSmallIntegerField(default=0) objects = RepeatInfoManager() I've tried the following: events = [] _events = Event.objects.filter(date_start__gte=datetime.utcnow()) recurring_events_info = [] for event in _events: if isinstance(event, RecurringEvent): if event.info not in recurring_events_info: recurring_event = RecurringEvent.objects.filter(date_start__gte=datetime.utcnow(), info=event.info).order_by('-date_start').first() events.append(recurring_event) recurring_events_info.append(event.info) else: events.append(event) but the isinstance(event, RecurringEvent) … -
ValueError didn't return an HttpResponse object. It returned None instead
I'm trying to print out a user login page but, I'm getting an error. The tutorial I'm watching is using django 2.1 i'm using latest django 3.0.3 I'm missing something here but, I'm not sure what it is help would be appreciated. Exception Type: ValueError Exception Value:The view accounts.views.signup didn't return an HttpResponse object. It returned None instead from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib import auth def signup(request): if request.method =='POST': #The user wants to sign up if request.POST['password1'] == request.POST['password2']: try: user = User.objects.get(username=request.POST['username']) return render(request, 'accounts/signup.html', {'error':'Username Curtely preocupied '}) except User.DoseNotExist: User.objects.create_user(request.POST['username'], password=request.POST['password1']) auth.login(request,user) return redirect('home') else: #User has info and wants an account now! return render(request, 'accounts/signup.html') def login(request): return render(request, 'accounts/login.html') def logout(request): return render(request, 'accounts/signup.html') -
S3 permission problems from Django CMS
I have a Django CMS running on an Elastic Beanstalk instance. The media is stored in an S3 bucket. The CMS can access the media files if the bucket is public, but the CMS can't access it, even with valid credentials, if the bucket is not public. I would like to have the bucket be private and still be able to access the files through the CMS. I followed the directions here: https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html to configure the instance to use the S3 bucket for the media. The goal is to have S3 public access blocked (as the tutorial seems to be showing) and the bucket files only accessible through the CMS. The CMS is in the same account as the bucket. I can ssh to the CMS instance and use command line tools to access the bucket (presumably because the EB instance account has a user that that is in a group with the AmazonS3FullAccess policy). The CMS is only able to access the files in the media bucket if I (1) make the bucket public and (2) select the high level subdirectories in the bucket and click "Actions / Make Public". Unless those two actions are taken, CMS access to … -
Send File via Fetch to Django REST Endpoint?
I'm trying to upload a file via Fetch, to a Django REST endpoint. Fetch code: function handleFileUpload(files) { let formData = new FormData() formData.append('file', files[0]) fetch(receiveSpreadsheetEndpoint, { method: 'POST', body: formData, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, }, }) .then(response => response.json()) .then(data => { console.log(data) }) .catch(error => { console.error(error) }) } Django REST endpoint: class ReceiveFileData(APIView): permission_classes = (IsAuthenticated,) parser_classes = (JSONParser, FormParser, MultiPartParser) def post(self, request): my_file = request.stream.read data = {} <== a breakpoint is set here return Response(data, status=status.HTTP_200_OK) After my_file = request.stream.read, my_file contains b''. What am I leaving out? -
Django writing to multiple related Django models from the same form
How to write to multiple related Django models from the same form? I have a table of countries, each country has many foods associated with it, and each food has many ingredients. The user should be able to select a food from a pre-popluated list and import this into the MyFavFoods model, they should optionally be able to import the ingredients associated with each food into a separate model MyFavIngredients. The first part works fine, i.e. the user can select one or more foods and have this imported into the MyFavFoods model. The problem is that I cannot then write the list of ingredients for that food to the user ingredient model. class myview(generic.TemplateView): template_name = 'myapp/basic.html' success_url = reverse_lazy('home') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['pk1'] = self.kwargs['pk1'] return context def get(self,request,pk1): form=myform() return render(request,self.template_name,{"form":form}) def post(self,request,pk1): form =myform(request.POST) if form.is_valid(): food_list= form.cleaned_data['foods'] bring_ingredients= form.cleaned_data['bring_ingredients'] for i in food_list: myob= MyFavFoods(Country=Country.objects.get(pk=i)) if bring_ingredients== '1': print("This works fine") print("When this executes I want to write to the MyFavIngredients model which is related by a foreign key to the MyFavFoods model row that is just being created") else: print("don't import the ingredients") myob.save() context = {'form':form} return redirect('home') -
Creating templates in Django of Multiple Models with ForeignKey field
I have two models like these: class NominaEnc(models.Model): G1 = "PERSONAL" G2 = "SUPERVISOR" G3 ="AUXILIAR" GRUPO_CHOICES = ( (G1, 'PERSONAL'), (G2, 'SUPERVISOR'), (G3, 'AUXILIAR'), ) fecha_nomina= models.DateField() planta =models.ForeignKey(PlantaNomina,to_field='descripcion_planta',on_delete=models.CASCADE) area=models.ForeignKey(AreaNomina, on_delete=models.CASCADE, to_field='descripcion_area') linea =models.ForeignKey(lineaNomina, on_delete=models.CASCADE, to_field='descripcion_linea') grupo=models.CharField(choices=GRUPO_CHOICES, max_length=30, blank=True, null =True) supervisor=models.ForeignKey(SupervisorNomina, on_delete=models.CASCADE, to_field='nombre_supervisor') semana = models.IntegerField(default=1 ) plantilla = models.IntegerField(default=0) def __str__(self): return'{} {} {} {} {}'.format(self.semana, self.area, self.linea, self.grupo, self.supervisor) class Meta: verbose_name_plural ="Encabezados Nomina" verbose_name = "Encabezado Nomina" class NominaDet(models.Model): nomina = models.ForeignKey(NominaEnc, related_name='detalles' ,on_delete=models.CASCADE) concepto=models.ForeignKey(ConceptoNomina, on_delete=models.CASCADE, to_field='concepto') cantidad =models.FloatField(default=0.0) def __str__(self): return "{} {}".format(self.nomina,self.concepto) class Meta: verbose_name_plural ="Detalles Nomina" verbose_name = "Detalle Nomina" the Views I have are: class NominaList( generic.ListView): model=NominaEnc template_name='nomina/nomina_list.html' context_object_name='nomina' class NominaCompletaList(generic.ListView): template_name='nomina/nomina_completa.html' context_object_name='nomina' queryset = NominaEnc.objects.all() def get_context_data(self, **kwargs): context = super(NominaCompletaList, self).get_context_data(**kwargs) context['detalles'] = NominaDet.objects.all() context['encabezado'] = self.queryset return context and the url are: urlpatterns = [ path('nomina/', NominaList.as_view(), name="nomina_list"), path('nomina_completa/', NominaCompletaList.as_view(), name="nomina_completa") ] In NominaList View I just list the fields of NominaEnc, and in NominaCompleta View I am trying to show NominaEnc (header) and NominaDet (details of each NominaEnc record). however I dont know how to create the template for NominaCompleta View. Any help to do the template (html) and call all fields of booth models will … -
How to run more than one Django project on VPS windows server
I have a django project deployed on IIS windows server but I want to deploy other django project in the same VPS. HOW Can I do that? -
can not export variable from admin.py to overriden template in django
good night, i have overriden a template in django (change_list.html) to show chart.js charts in django admin page following the tutorial in this tutorial,bute when i get to the part when have to replace the hard coded data with the variable chart_data from teh admin.py file and pas it to the overriden template change_list.html,nothing happens and the table shows with all values in 1. what could be happening, i have not found any information about how variables are passed from admin.py to the overriden template html files. Here is the code class ReporteActividadUsuariosAdmin(admin.ModelAdmin): list_display = ['nombre','apellidos','carnet','cliente','cantidad_de_prestamos'] ordering = ['-cantidad_de_prestamos'] def changelist_view(self, request, extra_context=None): chart_data = ( ReporteActividadUsuarios.objects.annotate(Count("cantidad_de_prestamos")) .values("nombre","apellidos") .annotate(y=Count("cantidad_de_prestamos")) #.group_by("cantidad_de_prestamos") #.order_by("-carnet") ) # Serialize and attach the chart data to the template context as_json = json.dumps(list(chart_data), cls=DjangoJSONEncoder) extra_context = extra_context or {"chart_data": as_json} # Call the superclass changelist_view to render the page return super().changelist_view(request, extra_context=extra_context) def has_add_permission(self, request): return False and the overriden template file change_list.html is as follows: {% extends "admin/change_list.html" %} {% load static %} {% block content %} {% block extrahead %} {{ block.super }} <link rel="stylesheet" href="{% static '/asset/css/Chart.min.css' %}" /> <script src="{% static '/asset/js/admin/Chart.bundle.min.js' %}"></script> <script> document.addEventListener('DOMContentLoaded', () => { const ctx = document.getElementById('myChart').getContext('2d'); const … -
Django with Apache2
I am trying to configure Django with Apache2 and I have been following some tutorials but not sure if they are up to date. sudo a2ensite test gives me the following error: ERROR: Site test does not exist! If I start apache2 and django server with python3 manage.py runserver the site is not online. My config: sites-available/000-default.conf <VirtualHost *:80> LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so AddHandler wsgi-script .py DocumentRoot /home/djangos/test WSGIScriptAlias / /home/djangos/test/test/wsgi.py WSGIPythonHome /home/djangos WSGIpythonPath /home/djangos/test WSGIDaemonProcess 94.254.0.98 processes=2 threads=15 display-name=%{GROUP} python-home=/home/djangos/lib/python3.6 WSGIProcessGroup 94.254.0.98 <Directory /home/djangos/test/> AllowOverride all Require all granted Options FollowSymlinks </Directory> <Directory /home/djangos/test/> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static/ /home/djangos/test/site/static/ <Directory /home/djangos/test/static/> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> Any suggestions would be MUCH appreciated! -
Passing large arrays between Python backend and Javascript frontend
Here's a silly question for you that I can't figure out anywhere. I have a Python module that runs relatively compute-heavy tasks in the background and generates 2D and 3D meshes. I would like to use VTK.js (a 3D Javascript library) or similar to render these in the web browser, and something analogous to Matplotlib to render 2D rasters and vectors in the browser. Additionally, I would like to have sliders, tabs, and panes to adjust various meshing parameters, with buttons to signal a start to the meshing process. In other words, The user needs to supply Python backend code with various input parameters (Javascript->Python) The backend needs to compute and return large matrices and arrays for rendering (Python->Javascript) All of this is trivial in something like wxPython, but I can't find a good answer for a web-based frontend. -
How to submit only one option in HTML dropdown filter?
I have a few HTML form dropdowns which send GET data to the view and return the correct ordering. I figure I am writing it wrong and could simplify it since there are many forms. Currently: <ul class="dropdown-menu" role="menu"> <li> <form action="{% url 'activity' %}" class="small-form" method="get"> <input name="ordering" type="hidden" value="-points"> <input class="btn btn-link link-white btn-sm" type="submit" value="Points"> </form> </li> <li> <form action="{% url 'activity' %}" class="small-form" method="get"> <input name="ordering" type="hidden" value="-last_login"> <input class="btn btn-link link-white btn-sm" type="submit" value="Last Login"> </form> </li> <li> <form action="{% url 'activity' %}" class="small-form" method="get"> <input name="ordering" type="hidden" value="first_name"> <input class="btn btn-link link-white btn-sm" type="submit" value="First name"> </form> </li> <li> <form action="{% url 'activity' %}" class="small-form" method="get"> <input name="ordering" type="hidden" value="last_name"> <input class="btn btn-link link-white btn-sm" type="submit" value="Last name"> </form> </li> </ul> I tried putting it all in one form: <ul class="dropdown-menu" role="menu"> <form action="{% url 'activity' %}" class="small-form"> <li> <input name="ordering" type="hidden" value="-points"> <input class="btn btn-link link-white btn-sm" type="submit" value="Points"> </li> <li> <input name="ordering" type="hidden" value="-last_login"> <input class="btn btn-link link-white btn-sm" type="submit" value="Last Login"> </li> <li> <input name="ordering" type="hidden" value="first_name"> <input class="btn btn-link link-white btn-sm" type="submit" value="First name"> </li> <li> <input name="ordering" type="hidden" value="last_name"> <input class="btn btn-link link-white btn-sm" type="submit" value="Last name"> </li> </form> … -
Django multiple datetime fields validation and regulations
Hello I have a model with couple of dates, which are dependable to one another class MyModel(models.Model): d1_from = models.DateTimeField(null=False... d1_to ... # # d5_to the comparisson is: d1_from <= d1_to <= d2_from <= d2_to ..... <=d5_to My question When I write the clean function to validate the model, realized that to the end user it will be very difficult to work with this. How can I make date ranges to make my logic simple and easier for the end user of the admin panel. I am using a django Jet for the admin interfce and yes I need all of these days for parametrization -
Django does not output results to the table
I'm trying to pass values from the database to tables to the Django server. In the First case, all data is displayed perfectly. But the second table remains empty for some reason I don't understand. What could be the reason? Views.py from django.shortcuts import render import sqlite3 as lite import os def csv_simple_read(request): path = os.path.dirname(__file__) file = lite.connect("D:/clear/VM1/chat.db") cure = file.cursor() cure.execute( "SELECT chat_identifier, datetime(date/1000000000 + 978307200,'unixepoch','localtime'), case when [error]=0 then 'Send' when [error]=1 then 'Not Send' end FROM chat INNER JOIN message ON chat.ROWID = message.ROWID ORDER BY date DESC") rows = cure.fetchall() resultlist = [] for row in rows: salam = (list([row[d:d + 1] for d in range(0, len(row), 1)])) resultdict = {} resultdict['name'] = salam[0] resultdict['date'] = salam[1] resultdict['status'] = salam[2] resultlist.append(resultdict) return render(request, "blog/index.html", {'results': resultlist}) #?????????? def csv_simple_read2(request2): path = os.path.dirname(__file__) file2 = lite.connect("D:/clear2/VM2/chat.db") cure2 = file2.cursor() cure2.execute( "SELECT chat_identifier, datetime(date/1000000000 + 978307200,'unixepoch','localtime'), case when [error]=0 then 'Send' when [error]=1 then 'Not Send' end FROM chat INNER JOIN message ON chat.ROWID = message.ROWID ORDER BY date DESC") rows2 = cure2.fetchall() resultlist2 = [] for row in rows2: salam2 = (list([row[d:d + 1] for d in range(0, len(row), 1)])) resultdict2 = {} resultdict2['name2'] = salam2[0] … -
Python, Django - Accessing Environment Variables in settings.py
Within my project, I want to send an email with python/Django. In order to do this, I need to specify multiple settings, and one of them is the password for my email. I want to retreive this from an environment variable. When I reference the environment variable in settings.py, I get a message implying the value is wrong and not my actual password. I ensured that the environment variable is set to my actual password within bash_profile, and when I hardcoded my password in the settings file, the email is sent successfully. This implies the issue is occurring when trying to retrieve the password as an environment variable. SETTINGS.py: import os # me trying to retrieve password EMAIL_HOST_PASSWORD = os.environ.get('email_password') Anybody know the issue? Thank you. -
Django circular imports causes AttributeError: module 'x' has no attribute 'x'
I'm trying to import two Serializers like below: # project/accounts/serializers/user.py from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): team = ... # I need TeamSerializer here # ----------------------------------- # project/teams/serializers/team.py from rest_framework import serializers class TeamSerializer(serializers.ModelSerializer): leader = ... # I need UserSerializer here All of the serializers in every apps are in a serializers folder and the folder contains an init file. Inside the init files, I've imported Serializer like below: # project/teams/serializers/__init__.py from .team import TeamSerializer # project/accounts/serializers/__init__.py from .user import UserSerializer I've already tried many ways like import teams.serializers and call teams.serializers.TeamSerializers() instead from teams.serializers import TeamSerializer. It only works when it's not circular, however, I need them both in each other. When I import them in both files, there is an error like below: AttributeError: module 'accounts' has no attribute 'serializers' Once I comment out one of them, the error is gone. Is there a clean way to do that? Thanks in advance. -
Is it possible to define a non-managed model at runtime using Django?
Lets say I want to define the following model: class Customer(models.Model): age = models.IntegerField() class Meta: managed = False db_table = 'Customer' I know I can use type in Python to define classes. For example, the following class: class Test(object): def __init__(self, x): self.x = x def printX(self): print self.x Can be defined using: def __init__(self, x): self.x = x def printX(self): print self.x Test = type('Test', (object,), {'__init__': __init__, 'printX': printX}) Now, Django models are basically classes, so theoretically this should be possible. However, I have a few questions: How do I define the inheritance from models.Model? How do I define the age field? How do I define the Meta and the attributes within it? Is there a way to do this? Thanks for any help. -
Is it possible to query a table using Django's ORM without creating a class for it in models?
The question is pretty self-explanatory. I have a database where I know there is a table called Customer, but this is not present in the models.py. Therefore, I can't simply do the following: customers = Customer.objects.filter(age__gte=25) Is it possible to write this query and get the data without creating a class for it in models.py and migrating the whole project? -
Can Django TemplateResponseMixin By Itself Render A Template?
Is it possible to render a view in my browser by subclassing ONLY a TemplateResponseMixin (by itself)? This is a curiosity question more than anything. I am no stranger to ccbv.co.uk. I am already aware of the following: content_type, response_class, template_engine, template_name - template_name being an important attribute to TemplateResponseMixin get_template_names - seems to just return the template_name value in a list render_to_response - takes context as an argument, sets the content_type attribute to None (unless defined), and returns a TemplateResponse by default using response_class attribute object. TemplateResponse is a subclass of SimpleTemplateResponse that knows about the current HttpRequest Example that throws an error: views.py class JaradView(TemplateResponseMixin): template_name = 'courses/course/jarad.html' urls.py from django.urls import path from . import views urlpatterns = [ path('greeting/hey/', views.JaradView, name='say_hey') ] jarad.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Hey Jarad!</h1> <h2>Why are you talking to yourself?</h2> </body> </html> What Happens? This trainwreck: Traceback (most recent call last): File "C:\Users\Jarad\Documents\PyCharm\educa\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Jarad\Documents\PyCharm\educa\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Jarad\Documents\PyCharm\educa\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /course/greeting/hey/ Exception Value: JaradView() takes no arguments So, arguments are … -
unexpected error change_password_form templates is for admin
hello or good evening we check the applications of the projects I discovered an error but it is the first time that I even see this template and taken from another existing project and the other works very well this one sends the form but with the administration templates and not with the project template urls.py from django.contrib.auth.views import ...,PasswordChangeView,... path('password_change/', PasswordChangeView.as_view( success_url='done/'), name="password_change"), templates/registration/password_change_form.html {% extends "base.html" %} {% block content %} <div class="container"> <div class="row justify-content-center align-items-center" style="height:80vh;"> <div class="col-auto border p-3"> {% if form.errors %} <p class="bg-danger p-2">Incorrect password</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p class="bg-warning p-1">Your account doesn't have access.</p> {% else %} <p class="bg-secondary">Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'accounts:password_change' %}"> {% csrf_token %} {{ form.as_p}} <input class="mt-3" type="submit" value="Change Password" /> <input type="hidden" name="next" value="{{ next }}" /> </form> </div> </div> </div> {% endblock %} -
Adding ManyToManyField query in django view
This is my view.I want to add a manytomanyfield through text rather than checkbox so that I can create new and get old ones. I want user to just split each language with space class CreateBooksView(LoginRequiredMixin,CreateView): login_url = "/books/login" form_class = CreateBooksForm template_name = "books/create.html" success_url = reverse_lazy('home') def form_valid(self,form): tag_list=[] books = form.save(commit=False) books.author = self.request.user ''' Here many to many query so that I can get or create with text rather than choosing .. ''' books.save() return super(CreateBooksView,self).form_valid(form) def form_invalid(self,form): print (form.errors) return super(CreateBooksView,self).form_invalid(form) This is my models.So the ManytoManyField that I want to get filtered is language. class Language(models.Model): name= models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): name=models.CharField(max_length=200) about =models.TextField() image = models.ImageField(upload_to=upload_image) language = models.ManyToManyField(Language,related_name='book') author = models.ForeignKey(User,on_delete=models.PROTECT,related_name='bauthor') def __str__(self): return self.name class Meta: ordering = ('-pk',)