Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a dropdown navbar which is automatically updated (Django)
Hey guys how are you doing? I'm creating my portfolio and I'd like to do it using Django and now i need some help. I'm trying to create a navbar with a dropdown list that contains my projects and it is automatically update when I publish a new project. Now my project_list page already do this, and when I'm on it the navbar works as I want, but when I'm in another page it doesnt show any project. This is my model: from django.db import models from django.urls import reverse from django.contrib.auth import get_user_model from django.utils import timezone from django.contrib.auth.models import User class Publish(models.Model): user = models.ForeignKey(User,null=True, on_delete=models.CASCADE ) author = models.CharField(max_length=256, null= True) name = models.CharField(max_length=256, null = True) description = models.TextField() create_date = models.DateTimeField(default=timezone.now) def published(self): self.create_date = timezone.now() self.save() This is my views.py from django.shortcuts import render,redirect, get_object_or_404 from django.views.generic import ListView, DeleteView, CreateView, TemplateView, UpdateView, DetailView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import PublishCreateForm from publish.models import Publish from django.urls import reverse, reverse_lazy from django.views.generic.detail import SingleObjectMixin from django.utils import timezone class NavItems(object): def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context.update({ 'nav_items' : Publish.objects.all(),}) return context class ResumeView(TemplateView,NavItems): template_name = 'publish/resume.html' class PublishListView(ListView): model = Publish def get_queryset(self): … -
pip can't find django 3.x
whe I run: pip install django==3.05 I get Could not find a version that satisfies the requirement django==3.05 (from versions: 1.1.3, ... 2.2.11, 2.2.12) I need to update some references somewhere, but I am not sure how. Plz Help. -
django id foreagin key
I have client model and contact model with foreign key relation, i want to know to can I create the client and hist contact in the same time, I mean that how to get the client id which is the foreign key in client model while the creating of the client?? should I use Django signals or there is another way of doing this ?? models.py class Client_Data(models.Model): RC = models.CharField(max_length=50) Raison_social = models.CharField(max_length=254) NIF = models.CharField(max_length=50,unique=True) AI = models.CharField(max_length=50,unique=True) NIS = models.CharField(max_length=50,unique=True) Banque = models.CharField(max_length=50,unique=True) CB = models.CharField(max_length=50) adresse = models.CharField(max_length=50) slug = models.SlugField(blank=True, unique=True) active = models.BooleanField(default=True) class Contact(models.Model): client = models.ForeignKey(Client_Data,on_delete=models.CASCADE) Nom = models.CharField(max_length=50) post = models.CharField(max_length=50) Tel = models.CharField(max_length=50) email = models.EmailField(max_length=255,unique=True) contact_type = models.CharField(default='Client_contact',max_length=50) views.py def save_client_form(request, form,Contact_form, template_name): data = dict() if request.method == 'POST': if form.is_valid() and Contact_form.is_valid(): form.save() contact = Contact_form.save(commit=False) # contact.id = Contact_form.save() data['form_is_valid'] = True books = Client_Data.objects.all() data['html_book_list'] = render_to_string('Client_Section/partial_client_c.html', { 'client': books }) else: print(form.errors) print(Contact_form.errors) data['form_is_valid'] = False context = {'form': form,'contact_form':Contact_form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def client_create(request): if request.method == 'POST': form = ClientForm(request.POST) contact_form = Contact_Form(request.POST) else: form = ClientForm() contact_form = Contact_Form() return save_client_form(request, form,contact_form, 'Client_Section/partial_client.html') forms.py class ClientForm(forms.ModelForm): class … -
Chart does not display on webpage in Django app (with Chart.js)
I am new to web development and I struggling with the frontend side of a django project. I have a dashboard template that I got from bootstrap and I want to integrate a chart that I made with chart.js. The charts works fine in another project but I cannot get it to display anything when it's a part of a dashboard. I attached my index.html as well as my plot.html and a sample of the data that I am trying to plot and the error I get in Chrome console <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>SB Admin 2 - Dashboard</title> <!-- Custom fonts for this template--> <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css"> <link href="{% static 'https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i' %}" rel="stylesheet"> <!-- Custom styles for this template--> <link href="{% static 'css/sb-admin-2.min.css' %}" rel="stylesheet"> </head> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <!-- Sidebar --> <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar"> <!-- Sidebar - Brand --> <a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.html"> <div class="sidebar-brand-icon rotate-n-15"> <i class="fas fa-laugh-wink"></i> </div> <div class="sidebar-brand-text mx-3"> Inventory Management <sup></sup></div> </a> <!-- Divider --> <hr class="sidebar-divider … -
django - models.ForiegnKey to the same model, to self
Peace be upon you! Currently, I'm working on my first django project, of course as all django developers, I have stumbled upon so many bugs, my current problem is that I want to set up comments system (DB, front-end, back-end), I have searched for a solution for this but no answer is found. this is my models: from django.db import models from datetime import datetime from django.contrib.auth.models import User class Comment(models.Model): # if I am a reply, so "comment" my parent comment, so each comment will have replies_set comment = models.ForeignKey('self', on_delete=models.CASCADE, default = '', related_name='replies') user = models.ForeignKey(User, on_delete=models.CASCADE, default='') value = models.CharField(max_length=100, default='') date = models.DateField(default = datetime.now()) def __str__(self): return self.value class Reaction(models.Model): comment = models.ForeignKey(Comment, on_delete=models.CASCADE, default = '') # the user that this love belong to user = models.ForeignKey(User, on_delete=models.CASCADE, default='') # type: like:0, love:1, laugh:2, cry:3, angry:4, ... TYPES = [ (0, 'like'), (1, 'love'), (2, 'laugh'), (3, 'cry'), (4, 'angry'), ] reaction_type = models.IntegerField(choices=TYPES, default=0) def __str__(self): return self.types[self.reaction_type][1] I want to make something similar to twitter comments, to reply forever not a thing such that in StackOverflow, to have a root post or question and comments with a reply for a user … -
Django Translation Internationalization and localization: forms, models, tables
I have two questions. How can I translate in forms: a) labels b) Form ValidationErrors ? forms.py from django import forms from django.db.models import Max, Min from .models import Application, FlowRate, WaterFilterSubType, Fineness, Dirt from .models import DirtProperties, Flange class InputDataWaterForm(forms.Form): '''Application''' choices = list(Application.objects.values_list('id','application')) application = forms.ChoiceField(choices = choices, initial="1", label="Specify application:") .... def clean(self): cleaned_data = super(InputDataWaterForm, self).clean() application = cleaned_data.get('application') ... '''OTHER CONDITIONS if not flowrate ...''' if not (flowrate or pressure or dirt or dirtproperties or application or fineness or temperature or flange or atex or aufstellung or ventil): raise forms.ValidationError('PLEASE ENTER THE REQUIRED INFO') How can I translate content of a table in a database? All records eg. product names in a table must be translated. models.py from django.db import models '''FILTER PROPERTIES LIKE COLOR''' class FP_sealing(models.Model): value = models.CharField('Material Sealing', max_length=10) descr = models.CharField('Description', max_length=200, default="") def __str__(self): return("Seal: " + self.value) Thank you -
Monkey Patch Django Components
Suppose we have a django component django.views.generic.base.ContextMixin I Want to replace it with my own ContextMixin without changing any imports. How to that in django ? I have tried it many ways, reassigning the class in manage.py, in project init, etc. Has anyone done it? In django where is proper place to do system wide patching? -
Template Language for Django which does not silently fail on exception?
I like django, the ORM, the admin, the community. But I don't like the handling of exception in the template language, like documented here: invalid template variables. Is there an alternative template variable where I always get an exception if something is wrong (even in production)? I prefer exceptions to "silently ignore errors". -
How can i use django groups for specific model?
does any body can help me to use Django groups for a specific model ? for example for blog app,in Entry model, can i add a field like this to have groups like sport,news and etc ? group = models.ForeignKey(groups,on_delete=models.CASCADE) (something like this) -
(.SVG, .PNG) not loading in react component
I am trying to load SVG and PNG images in my react app. I am running a back end server on Django. I always get this error when I try to load any Image. "GET /b5cde312e6d66e389b1ca2ccfc013da0.png HTTP/1.1" 404 2195 webpack.config.js { test: /\.(jpg|png|svg)$/, loader: 'url-loader', options: { limit: 25000, }, }, { test: /\.(jpg|png|svg)$/, loader: 'file-loader', options: { name: '[path][name].[hash].[ext]', }, }, My component import React from 'react'; import '../App.css'; import Nav from '../components/Nav'; import Logo from '../logo512.png'; export default class Dev extends React.Component { render(){ return ( <div className="App"> <Nav /> <header className="App-header"> <div className="container"> <img src={Logo} alt="React Logo" /> </div> </header> </div> ) } } -
Why do I get a KeyError on a Model in Django?
I am getting a KeyError: 'conversation' on the line conv = ans.conversation in the code section: answers = Answers.objects.all() for ans in answers: conv = ans.conversation ... My model 'Answers' looks like this: class Answers(models.Model): conversation = models.ForeignKey(Conversation) ... I get the error sometimes, so if I run the code, I get the correct result a few times, but eventually within the for loop, sometimes the line conv = ans.conversation fails. Why do you think an error like this could ocurr? The entire error trace is here: Traceback (most recent call last): File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 164, in _get_ rel_obj = self.field.get_cached_value(instance) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/fields/mixins.py", line 13, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'conversation' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/webapps/municipio/municipio/reportes/views.py", line 153, in get_whats_data conv = ans.conversation File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 178, in _get_ rel_obj = self.get_object(instance) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 145, in get_object return qs.get(self.field.get_reverse_related_filter(instance)) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/query.py", line 402, in get num = len(clone) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/query.py", line 256, in _len_ self._fetch_all() File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/query.py", line 55, in _iter_ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1100, in execute_sql cursor.execute(sql, params) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 99, in execute … -
Django Rest Framework: Pagination w/ ListModelMixin
I've been following the django-rest-framework documentation examples but I'm having trouble getting pagination to work when using a `ListModelMixin and viewsets.GenericViewset This does NOT paginate: class InvitesViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): permission_classes = [IsAuthenticated] queryset = User.objects.all() serializer_class = UserSerializer def list(self, request): invited_users = self.get_queryset() # just did this as a test serializer = UserSerializer(invited_users, many=True) return Response(serializer.data) While this does: class InvitesViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): permission_classes = [IsAuthenticated] queryset = User.objects.all() serializer_class = UserSerializer How can I return a custom list response (because I need to filter on the request.user) with pagination while using ListModelMixin? -
include sub html parts in one Django template
My project contains a lot of parts like header,footer,... that every part has it's own css/js libraries like below simple project: templates/master.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> {% block css_links %}{% endblock %} <title>Test</title> </head> <body> {% block content %}{% endblock %} </body> </html> templates/part1.html: {% extends "master.html" %} {% load static %} {% block css_links %} <link rel="stylesheet" href="{% static 'css/style1.css' %}"> {% endblock %} {% block content %} <h2 class="content1">This is content1.</h2> {% endblock %} and another block like part2 with style2.css and content2 in h2 that both files included in Main.html below: templates/Main.html: {% include "part1.html" %} {% include "part2.html" %} and output is below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/css/style1.css"> <title>Test</title> </head> <body> <h2 class="content1">This is content.</h2> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/css/style2.css"> <title>Test</title> <h2 class="content2">This is content.</h2> </body> </html> as you can see,part2 head parts like css link,meta and title wasn't loaded in head.what can I do? -
AttributeError at /register 'function' object has no attribute 'META'
I am new to using Django. So when I tried to create a register form I keep getting the error: AttributeError at /register 'function' object has no attribute 'META' from groups.forms import LoginForm, RegisterForm from django.shortcuts import render,redirect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import UserCreationForm def register(response): if response.method == "POST": form = UserCreationForm(response.POST) if form.is_valid(): user = form.save() user.save() else: form = UserCreationForm() return render(request, 'register.html' , {"form":form}) This is the html code: {% load static %} {% include "includes/header.html" %} <br/><br/><br/><br/> <div class="container" align="center"> <div style="text-align: left; padding-left: 3%; width: 400px;"> <!-- Log in zone --> <form action="{% url 'register' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% if next %} <input type="hidden" name="next" value="{{ next }}" /> {% endif %} <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title" align="center">Register</h3> </div> <div class="panel-body"align="center"> <div class="form-group has-primary"> {% csrf_token %} <input type="text" id="username" name="username" placeholder="Username" class="form-control" ><br/><br/> <input type="text" name="first_name" id="first_name" placeholder="First Name" class="form-control"><br/><br/> <input type="text" id="last_name" name="last_name" placeholder="Last Name" class="form-control" ><br/><br/> <input type="text" id="email" name="email" placeholder="Email" class="form-control" ><br/><br/> <input type="password" name="password" id="password" placeholder="Password" class="form-control"><br/><br/> <button type="submit" class="btn btn-primary">Register</button><br/><br/> </div> </div> </div> </form> </div> </div> <script src="/static/graphics/js/jquery.min.js"></script> <script src="/static/graphics/js/bootstrap.min.js"></script> <script src="/static/graphics/js/respond.min.js"></script> <script src="/static/graphics/js/bodypadding.js"></script> -
Since Django update, template rendering throws "'int' object has no attribute 'encode'"
After updating django I am now getting this error in a template rendering: int object has no attribute encode. I have checked that all of the variables sent to the template are str() except for one recordset. There is no occurrence of the string encode anywhere in the template. The error-stop in debug mode unhelpfully points at a <meta> tag at the top of the template. The error appears to be occurring somewhere inside the render() call. The only possibly-significant clue is that one line in the traceback is: response = self.process_exception_by_middleware(e, request) ... This software was working normally before the upgrade. It's now still fairly backwards, parked at Django 2.2. -
Django Static files loading failed
I am trying to load static files in my django project. but it isn't loading. My static folder is in the base directory of project . Here I am giving some relevant code. Here is my project's settings.py file's static part. STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assests') Here is the html part {% load static %} <img id="undraw_shared_workspace_hwky" src="{% static 'undraw_shared_workspace_hwky.png' %}"> My project name is 'webpage' and here is the image path. webpage\static\undraw_shared_workspace_hwky.png I have tried... manage.py collectstatic to collect the static files. It worked and gave me a assests directory inside or root directory. But when I go to the website it doesn't load the image. and the console says "Failed to load resource: the server responded with a status of 404 (Not Found)" . I am in a windows machine and using Django 3.0. Now I need you help to fix this problem. Thanks in advance. -
unable to use the variable in django
i recently started my django course online nad getting some problem. i am not able to use my variable which i passed from index.html to about.html. but in about.html it is not shown up. .py file code : from django .http import HttpResponse from django.shortcuts import render def index(request): return render(request , 'index.html') def about(request): t1 = print(request.GET.get('text' , 'default')) return render(request , 'about.html' , t1) index.html file code: <!DOCTYPE html> <html> <head> <title>template</title> </head> <body> <h1> hello everyone </h1> <form action="/about" , method="get"> <textarea name="text" style="margin: 0px; width: 1245px; height: 171px;"></textarea> <input type="submit" name="OK"> </form> </body> </html> about.html file code : <!DOCTYPE html> <html> <head> <title>template</title> </head> <body> <h1>you typed {{t1}}</h1> </form> </body> </html> -
Django How do I edit a comment
how do I edit an existing comment, when a user comment on a post that user can be able to edit his/her comment. class Comments(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) commented_image = models.ForeignKey(Image,....) comment_post = models.TextField() ....... def comments(request, id): post = get_object_or_404(Image) if request.method == 'POST': form = CommentForm(request.POST) if form.is_form(): comment = form.save(commit=False) comment.user = request.user comment.commented_image = post comment.save() return redirect..... <form method="POST"> {% csrf_token %} <textarea name="comment_post" placeholder="Add comment" id="I'd comment_post"></textarea> <input type="submit" value="POST"> </form> -
django runserver issue on first start
Using Django 3.0 via Pycharm. After starting first time runserver I get the following errors. Would anyone know? The project is completely empty. So far only "startproject" and "runserver" was done. The runserver starts but as soon as I open the link to see in in the browser I get the following meesage? You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. April 02, 2020 - 21:37:53 Django version 3.0.3, using settings 'django_devel_app.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [02/Apr/2020 21:37:56] "GET / HTTP/1.1" 200 16351 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 64833) Traceback (most recent call last): File "C:\Users\BJS\anaconda3\envs\djangoproject\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\BJS\anaconda3\envs\djangoproject\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\BJS\anaconda3\envs\djangoproject\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\BJS\anaconda3\envs\djangoproject\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\BJS\anaconda3\envs\djangoproject\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\BJS\anaconda3\envs\djangoproject\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine ---------------------------------------- Not Found: /favicon.ico [02/Apr/2020 21:37:57] "GET /favicon.ico HTTP/1.1" 404 1982 ---------------------------------------- … -
Not Redirect after submission the Django Forms
hi dear all of genious Django Expert . i am newbe in django . i having an issue for my form submission . my form is not redirect after click submit . my issue is below <h1> this is views.py page <h1> from django.shortcuts import render, redirect from crud.models import Userlist from crud.forms import UserListForm # Create your views here. def addforms(request): if request.method == "POST": form = UserListForm(request.POST) if form.is_valid(): try: form.save() return redirect() except: pass else: form = UserListForm() return render(request, 'crud/index.html', {'form': form}) def show(request): user9 = Userlist.objects.all() return render(request, 'crud/show.html', {'user': user9}) def index(request): return render(request, 'crud/index.html') -
Restricting access to Django webapp with Stripe?
I'm trying to build a B2B SaaS application where the customer can sign up and invite their respective employees. What options do I have to make sure a customer does not get more access than the amount of licenses they paid for? (Eg, if they pay for 2 licenses, only 2 users should be allowed to use the system) What are some best practices? -
Django: Is there any way to copy a form in the admin to a user-facing page?
https://github.com/mikejohnsonjr/django-powerdns-manager ^ I want to copy the form for adding and editing and deleting new zones. It's a bit counter-intuitive. For example, importing any zone form (like NsRecordModelForm or ARecordModelForm) on a user-facing page will result in being able to add any record (with no styles), rather than a specific type of record. https://github.com/mikejohnsonjr/django-powerdns-manager/blob/master/src/powerdns_manager/admin.py Here is the ugly (no styles) anyzone-ModelForm form: https://i.imgur.com/F6Zcs10.png And here is the admin interface for performing CRUD operations on zones: https://i.imgur.com/5LReNsq.png Can anyone help? Thanks in advance. -
ModuleNotFoundError: No module named 'paypal'
I'm using, Python: 3.8, Django: 3.0, django-paypal: 1.0.0 I'm trying to implement a simple Payment Gateway using Django-Paypal lib. And I'm getting this error during the migration..... (project-venv) PS J:\jaimin (E)\Programming Practice\Django\Payment Gateway using Paypal\simple_ecommerce\django_project> py -3 .\manage.py migrate Traceback (most recent call last): File ".\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\jaimi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\jaimi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\jaimi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\jaimi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\jaimi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\jaimi\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'paypal' And here is my settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ecommerce_app', 'paypal.standard.ipn', ] What can I do Now?..... -
AttributeError at /update/ 'Personas' object has no attribute 'is_valid'
I have in models from django.db import models # Create your models here. class Personas(models.Model): Nombre = models.CharField(max_length=50) Apellido = models.CharField(max_length=50) Cedula = models.IntegerField() Direccion = models.CharField(max_length=30) Colegio_Electoral = models.IntegerField() Centro_De_Votacion = models.CharField(max_length=50) Sexo = models.CharField(max_length=13) Telefono = models.CharField(max_length=30) Email = models.EmailField(max_length=50) Edad = models.IntegerField() Sector = models.CharField(max_length=50) def __str__(self): return self.Nombre + " " + (self.Apellido) and views def update(request): if request.method == 'POST': form = Personas(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('formulario.html') else: form = Personas() return render(request, 'formulario.html', { 'form':form }) -
NoReverseMatch exception when creating integration test for REST API with Python Django
I've created a REST API accepting a POST request in Django. The request itself works great when calling from a React front end, there should be nothing wrong with the API itself. I want to create integration test for the API. I've written the below test, which is basically copy/paste from the Django Documentation adapted to my API: from django.urls import reverse, path from rest_framework import status from rest_framework.test import APITestCase class SendLoginEmailTest(APITestCase): def test_post_withValidData_loginEmailIsSent(self): url = reverse('send_login_email') data = {'email': 'validemail@email.com', 'token': '4d4ca980-cb0c-425d-8d2c-7e38cb33f38e'} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) I run the test using the command: python3 manage.py test The test fails with the following exception: django.urls.exceptions.NoReverseMatch: Reverse for 'send_login_email' not found. 'send_login_email' is not a valid view function or pattern name. Any ideas what I'm doing wrong?