Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at / "Reverse for 'home' not found. 'home' is not a valid view function or pattern name."
i'm getting following error while rendering my template someone please help NoReverseMatch at / Reverse for 'home' not found. 'home' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.14 Exception Type: NoReverseMatch Exception Value: Reverse for 'home' not found. 'home' is not a valid view function or pattern name. Exception Location: D:\dev\project\ECOM\env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 673 Python Executable: D:\dev\project\ECOM\env\Scripts\python.exe Python Version: 3.8.5 Python Path: ['D:\\dev\\project\\ECOM\\ecom', 'D:\\dev\\project\\ECOM\\env\\Scripts\\python38.zip', 'c:\\users\\arjun\\appdata\\local\\programs\\python\\python38-32\\DLLs', 'c:\\users\\arjun\\appdata\\local\\programs\\python\\python38-32\\lib', 'c:\\users\\arjun\\appdata\\local\\programs\\python\\python38-32', 'D:\\dev\\project\\ECOM\\env', 'D:\\dev\\project\\ECOM\\env\\lib\\site-packages'] Server time: Tue, 22 Sep 2020 15:55:56 +0000 Error during template rendering In template D:\dev\project\ECOM\ecom\templates\store\navbar.html, error at line 6 Reverse for 'home' not found. 'home' is not a valid view function or pattern name. 1 <!-- Navbar --> 2 <nav class="navbar fixed-top navbar-expand-lg navbar-light white scrolling-navbar"> 3 <div class="container"> 4 5 <!-- Brand --> 6 <a class="navbar-brand waves-effect" href="{% url 'home' %}" target="_blank"> 7 <strong class="blue-text">MDB</strong> 8 </a> 9 10 <!-- Collapse --> 11 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" 12 aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> 13 <span class="navbar-toggler-icon"></span> 14 </button> 15 16 <!-- Links --> here is my model.py (i have added get_absolute_url function) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug … -
Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain". Strict MIME type checking i
while building a debug toolbar in Django I am getting an error in file toolbar.js ie. s.map: HTTP error: status code 404, net:: ERR_UNKNOWN_URL_SCHEME toolbar.js:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec. can anyone tell me the possible fix for that? -
how can I set instance in model when using form in django?
in model.py I have this code: class wallet(models.Model): User = models.OneToOneField(User, on_delete=models.CASCADE ,primary_key=True) coin= models.PositiveIntegerField(default= 50000) password = models.CharField(blank=True , max_length = 50) def __str__(self): return str(self.wallet) this is one-to-one relationship between User and wallet in my form.py I Have this code : class WalletForm(forms.ModelForm): User = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) class Meta: model = wallet fields = ( 'User', 'coin', 'password' ) def __init__(self , user , *args,**kwargs): super().__init__(*args,**kwargs) self.fields['User'].widget.attrs['value'] = Profile.objects.get(pk = user.id) self.fields['User'].widget.attrs['readonly'] = True self.fields['coin'].widget.attrs['value'] = 50000 self.fields['coin'].widget.attrs['readonly'] = True self.fields['password'].widget.attrs['placeholder'] = 'Wallet Password' I am trying to make wallet for every user .. the question is : how can I set User in wallet model to the already user who is logged in my site when the form submitting ... thanks -
Unresolved attribute reference 'title' for class 'ForeignKey' in django models
I got this Unresolved attribute reference 'title' for class 'ForeignKey' error when i tried to call title from Article model class in PostImage model class. Does anyone know why?? class Post(models.Model): title = models.CharField(max_length=250) description = models.TextField() image = models.FileField(blank=True) def __str__(self): return self.title class PostImage(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) images = models.FileField(upload_to = 'images/') def __str__(self): return self.post.title -
How to save a pdf response to django model?
I have a function that calls for an external url to get a pdf format of specific car, so far this is the gist of what I tried: def cars(id): headers = { 'Content-Type': 'application/pdf', 'Authorization': token } url = CAR_URL + f'/cars/{id}' response = requests.get(url, headers=headers) return File(BytesIO(response.content)) def save_car_data(id) ... Car.objects.get_or_create( ... pdf = cars(id) ) Model: class Car(models.Model): created_dttm = models.DateTimeField(auto_now_add=True) owner = models.CharField(max_length=100) pdf = models.FileField(upload_to="cars/", blank=True, null=True) but when I check the django admin it seems there is no file generated and just a button that uploads a file -
Django authentication login() returns anonymous user
I am trying to log in to a database that is not the default database, and for that I've wrote a custom authentication code but whenever I try to login the method returns an AnonymousUser. I've no idea why is it doing so because user authentication is done properly using the authenticate method. Any help would be really appreciated. MY FILES views.py def login_authentication(request): if request.method == "POST": form = New_Login_Form(request.POST) # print(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user_operating_company = request.POST['user_operating_company'] user = authenticate(request, email=email, password=password, db=user_operating_company) if user: login(request, user, user_operating_company) return redirect('test') else: form = New_Login_Form() return render(request, 'index.html', {'form': form}) backends.py from django.contrib.auth.backends import ModelBackend from .models import Account class CustomAuthenticate(ModelBackend): def authenticate(self, request, email=None, password=None, db=None): try: user = Account.objects.all().using(db).get(email=email) if user.check_password(password): return user except: return None def get_user(self, request, email, db): try: return Account.objects.using(db).get(pk=email) except: return None and in the settings.py AUTHENTICATION_BACKENDS = ('accounts.backends.CustomAuthenticate', 'django.contrib.auth.backends.ModelBackend') -
How to configure django ckeditor image upload more easier?
I am using django-ckeditor RichTextUploadingField to allow upload img via editor. But I think this UI is not suit modern web. I want to imporve it like drag and drop or simple auto upload I'm still looking through Google to figure out how to set this up. I think someone has already made this. If there is no proper setup method, I'm going to implement this via Javascript. -
Maximum update depth exceeded on django instance deletion
When trying to delete the model tenantJobCategory I'm seeing a weird error message: RecursionError: maximum recursion depth exceeded The problem only exists whenever the tenantJobCategory has an active FK relationship to a profile instance (if it doesn't have that the deletion works fine). This is the profile: class Profile(models.Model): uuid = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) tenant_job_category = models.ForeignKey('job_categories.TenantJobCategory', null=True, blank=True, on_delete=models.SET_NULL) should_auto_promote = models.BooleanField(default=False) should_manual_promote = models.BooleanField(default=False) __original_should_auto_promote = None __original_manual_promote = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__original_should_auto_promote = self.should_auto_promote <-- this seems to be the cause self.__original_manual_promote = self.should_manual_promote <-- this too def save(self, *args, **kwargs): if self.should_auto_promote != self.__original_should_auto_promote: should_auto_promote_change.send(sender=self.__class__, instance=self) if self.should_manual_promote != self.__original_manual_promote: should_manual_promote_change.send(sender=self.__class__, instance=self) super().save(*args, **kwargs) I've marked two lines that I think, are causing the error (when I delete them, it works fine, if I delete only one of them, it also works). Maybe someone ran into this problem before and knows how to fix it? Thanks! -
How to select same object twice in Django ManyToMany Field
I have two models class Food(models.Model): name = models.CharField(max_length=200 ,null=False) class Profile(models.Model): food_selected_today = models.ManyToManyField(Food,related_name = 'inventory') Now in profile model I want to have one food for example Apple more than one time in food_selected_today. If I now add same food twice it only shows one Item. How can I add one food many times here. Any kind of help would be really appreciated -
Django: l'm trying to insert movies into MySQL db if it doesn't exist else if it exist query from database
json_response = response.json() movies = json_response['data']['movies'] movie_db = Movie.objects.all() print(movie_db) if movie_db is not None: for value in movies: Movie.objects.create( title=value['title'], description = value['description_full'], image = value['medium_cover_image'], category = value['genres'], year_of_production = value['year'], movie_url = value['url'], movie_torrent_link = value['torrents'][0]['url'], rating = value['rating'], runtime = value['runtime'], ) else: messages.info(request, "Movies exists...") return render(request, 'index.html',) so l tried to use queryset and store all movies in movie_db then l wanted to use an if statement to check if the movies don't exist insert else do nothing -
Django Model Classes
I have three model classes, identity, record, and times chedule. Identity is related to record using employee_id with length of 20 chars. And times chedule is related to record thru emp_time_sched field. Running migrate, django.db.utils.DataError:value too long for type character varying(3) error. Checked the table attributes, record.emp_type_sched has 20 chars. I include max_length=3 and still same error. -
Django: Call and edit model from template
I'm using Django for a simple web app where tasks have milestones. When clicking a milestone, it should be marked completed. I'm not sure how to change the completed attribute from my template. This is my milestone model, where I define a function Milestone.complete that I'm trying to call from the template (without success). class Milestone(models.Model): name = models.CharField(max_length=200) task = models.ForeignKey(Task, on_delete=models.CASCADE) completed = models.BooleanField(default=False) def complete(self): self.completed = True My template looks like this: ... {% if task.milestone_set.exists %} <div class="card"> <div class="card-header">Milestones</div> <ul class="list-group list-group-flush"> {% for milestone in task.milestone_set.all %} <li class="list-group-item"> {{ milestone.name }} {% if not milestone.completed %} {# <a href="{{ milestone.complete }}" class="btn btn-primary">Completed</a>#} <button type="button" class="btn btn-success" onclick="{{ milestone.complete }}">Completed</button> {% endif %} </li> {% endfor %} </ul> </div> {% else %} <p>task has no milestones</p> {% endif %} ... Calling milestone.complete works neither from the a link element nor from the button. The latter gives me Uncaught ReferenceError: None is not defined in the console and nothing happens. I also thought about how to implement the same function in a view, but didn't know how. -
Django Form : after correctly submitting form I got this: "this field is required"
I've a category and I've added a form for user in each category. So I've two fields to fill and after filling them correctly I submit but the page reload, and nothing appears in my DB... only one error on Image field: This field required. I don't really know what's wrong here. class Picture(models.Model): catego = models.ForeignKey(Catego,on_delete=models.CASCADE,related_name="catego_pictures") user = models.ForeignKey(User, blank=True, null=True,on_delete=models.CASCADE,related_name='user_pictures') image = models.ImageField(upload_to='nutriscore/') pictureoption = models.CharField(max_length=20,choices=Pictureoption.choices,default=Pictureoption.HOME,) publishing_date = models.DateField(auto_now_add=True) class CreatePictureForm(forms.ModelForm): def __init__(self,*args,**kwargs): super(CreatePictureForm, self).__init__(*args,**kwargs) self.helper = FormHelper() self.helper.form_method="post" self.helper.layout = Layout( Field("image",css_class="single-input"), Field("pictureoption",css_class="single-input"), ) self.helper.add_input(Submit('submit','Upload a pic',css_class="single-input textinput textInput form-control")) class Meta: model = Picture fields = [ 'image', 'pictureoption', ] def __str__(self): return self.catego.name views.py @login_required(login_url='/cooker/login') def catego(request, slug): catego = Catego.objects.get(slug=slug) context = { 'catego': catego } # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = CreatePictureForm(request.POST) # check whether it's valid: if form.is_valid(): form.instance.catego = self.object form.instance.user = self.request.user form.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: form = CreatePictureForm() context['form'] = form # add `form` to the context return render(request, 'post_catego.html', context) -
How can I get the previous URL in Django?
My code looks like this, I hope you will understand my logic. def home(request): if request.method == 'POST': return redirect('first-round') return render(request, 'home.html') def firstRound(request): # checking current url is redirected from home or not if request.META.get('HTTP_REFERER') == '/': if request.method == 'POST': return redirect('second-round') return redirect(request, 'first-round.html') else: return redirect('/') def secondRound(request): # checking current url is redirected from first-round or not if request.META.get('HTTP_REFERER') == '/first-round/': if request.method == 'POST': return redirect('third-round') return render(request, 'second-round.html') else: return redirect('/') def thirdRound(request): # checking current url is redirected from second-round or not if request.META.get('HTTP_REFERER') == '/second-round/': if request.method == 'POST': return redirect('login') return render(request, 'third-round.html') else: return redirect('/') request.META.get('HTTP_REFERER') return full path. So I need a previous URL full path like https://www.example.com/, https://www.example.com/first-round/, https://www.example.com/second-round/ and https://www.example.com/third-round/ -
problem deployind site in python any where
I'm trying to deploy my Django project with pythonanywher.com but I can't I'm a beginner please help I do exactly like his: creating an account creating API token in bash scripts pip3.6 install --user pythonanywhere and then $ pa_autoconfigure_django.py --python=3.6 https://github.com//my-first-blog.git but I face this and I can't figure out why it doesn't work please help 30 ~ $ pip3.6 install --user pythonanywhere Looking in links: /usr/share/pip-wheels Collecting pythonanywhere Downloading https://files.pythonhosted.org/packages/15/fa/812362a3910459a7ec1da428bdf44ea3c8468b92b57459c7d4a010f65ff7/pythonanywhere-0.9.4.tar.gz Requirement already satisfied: docopt in /usr/lib/python3.6/site-packages (from pythonanywhere) (0.6.2) Requirement already satisfied: python-dateutil in /usr/lib/python3.6/site-packages (from pythonanywhere) (2.8.0) Requirement already satisfied: requests in /usr/lib/python3.6/site-packages (from pythonanywhere) (2.22.0) Collecting schema Downloading https://files.pythonhosted.org/packages/6d/ae/835f2e0d304c9533c58fe5cbcdd9124708d32e82289fcb8d6084c908ba29/schema-0.7.2-py2.py3-none-any.whl Collecting tabulate Downloading https://files.pythonhosted.org/packages/c4/f4/770ae9385990f5a19a91431163d262182d3203662ea2b5739d0fcfc080f1/tabulate-0.8.7-py3-none-any.whl Requirement already satisfied: six>=1.5 in /usr/lib/python3.6/site-packages (from python-dateutil->pythonanywhere) (1.12.0) Requirement already satisfied: idna<2.9,>=2.5 in /usr/lib/python3.6/site-packages (from requests->pythonanywhere) (2.8) Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/lib/python3.6/site-packages (from requests->pythonanywhere) (3.0.4) Requirement already satisfied: certifi>=2017.4.17 in /usr/lib/python3.6/site-packages (from requests->pythonanywhere) (2019.9.11) Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/lib/python3.6/site-packages (from requests->pythonanywhere) (1.24.3) Collecting contextlib2>=0.5.5 Downloading https://files.pythonhosted.org/packages/85/60/370352f7ef6aa96c52fb001831622f50f923c1d575427d021b8ab3311236/contextlib2-0.6.0.post1-py2.py3-none-any.whl Building wheels for collected packages: pythonanywhere Building wheel for pythonanywhere (setup.py) ... done Created wheel for pythonanywhere: filename=pythonanywhere-0.9.4-cp36-none-any.whl size=30356 sha256=7bd01dd5d2d87faa19a931bd08f74e050498422a92a38f9e0b3b12b4c9bd0510 Stored in directory: /home/bookseagull13/.cache/pip/wheels/68/35/da/800f46741a95d4c66e77c7c2e145884a7ce9d2c46af401ee29 Successfully built pythonanywhere Installing collected packages: contextlib2, schema, tabulate, pythonanywhere Successfully installed contextlib2-0.6.0.post1 pythonanywhere-0.9.4 schema-0.7.2 tabulate-0.8.7 14:31 ~ $ python3 -m … -
django.urls.exceptions.NoReverseMatch: Reverse for 'foo-list' not found. 'foo-list' is not a valid view function or pattern name
I've got the message Reverse for 'receptionop-list' not found. 'receptionop-list' is not a valid view function or pattern name. in one of my test cases when trying to do the following: reverse('receptionop-list') Note: I have also tried reverse('receptionops-list') I've got it set in my urls like this: router.register(r'receptionops', views.ReceptionOperationViewSet) What's weird for me, is the fact I've got also a router.register(r'reception', views.ReceptionViewSet) registered in the same app, and using reverse('reception-list') works perfectly. Does anyone know what's going on here? (If needed, I can provide some further information) Thanks! -
Configuring httpd.conf with python Django and mod_wsgi : how to configure so I can access to my url like www.example.com?
I'm working on new personal project that consist on developing a website with python Django framework. I'm using macOS High Sierra system and I'm trying to follow python tutorial for that. First we need to configure environment with apache httpd server and mod_wsgi module. I could display "Hello world" script with mod_wsgi application script but I get it with http://localhost url instead of http://www.example.com url... Also, I'm trying to configure it with virtual environment. The question is how do I need to do into httpd.conf file for that ? Thank you in advance for your help Tony Here is the main configuration for my virtual host : <VirtualHost *:80> ServerName www.example.com ServerAlias example.com example # Chemin a partir duquel le serveur va servir les fichiers, racine a partir de laquelle nous pourrons consulter depuis internet DocumentRoot /Users/username/Desktop/example/Site # Etapes de configuration du module mod_wsgi. # Définie le point d'entrée via le wsgi WSGIScriptAlias / /Users/username/Desktop/example/Site/wsgi-scripts/wsgi.py # Configuration du monde Daemon WSGIDaemonProcess example.com python-home=/Users/username/.local/share/virtualenvs/example-P5vj6Ml3 python-path=/Users/username/Desktop/example WSGIProcessGroup example.com <Directory /Users/username/Desktop/example/Site/wsgi-scripts> <IfVersion < 2.4> Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.4> Require all granted </IfVersion> </Directory> <Directory /Users/username/Desktop/example/Site/wsgi-scripts> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> -
How to use the email field from a django-allauth table as username for authentication?
I'm using Django 3.1.1 with Django-allauth to handle user authentication. Creating a user makes entries in these 3 tables: auth_user account_emailaddress account_emailconfirmation Since usernames are not needed in my application I inherited from the User model to accept an email address instead: from django.contrib.auth.models import AbstractUser class User(AbstractUser): """User model.""" username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() This worked like a charm. However I noticed it makes absolutely no sense to have email addresses stored in auth_user at this point, because allauth already stores them in account_emailaddress. I noticed a foreign key already exists from the field user in account_emailaddress to auth_user: class EmailAddress(models.Model): user = models.ForeignKey(allauth_app_settings.USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE) email = models.EmailField(unique=app_settings.UNIQUE_EMAIL, max_length=app_settings.EMAIL_MAX_LENGTH, verbose_name=_('e-mail address')) Is it possible to make the USERNAME_FIELD variable afield from the account_emailaddress table instead or are there different/better practices? Also, it would be nice if this change would work with the manage.py createsuperuser script, so I can still create an admin account from the console. Thanks in advance! -
Deploying React + Django on Digital Ocean or another Cloud Service
I'm planning to develop a Django web application that extended with the DRF as well as Frontend will be powered by React js. Right now my selection for the deployment of the project is the Digital Ocean platform. I'm ok with Django deployments with the Digital Ocean, but I'm confused when it comes to django+React because both the technologies have two different servers running. So I need to know how to run Django and React in the same server. Please if anyone is aware of this or if there is clear documentation mention it out Thanks. -
you cannot alter to or from M2M fields, or add or remove through= on M2M fields
models.py from django.db import models from django.conf import settings import random User = settings.AUTH_USER_MODEL class TweetLike(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) tweet = models.ForeignKey("Tweet", on_delete= models.CASCADE) timestamp = models.DateTimeField(auto_now_add= True) class Tweet(models.Model): parent = models.ForeignKey("", null = True, on_delete=models.SET_NULL) user = models.ForeignKey(User, on_delete= models.CASCADE, related_name="tweets") likes = models.IntegerField(default= 0 ) content = models.TextField(max_length=200, blank = True, null = True) image = models.FileField(upload_to='images/', blank = True, null = True) timestamp = models.DateTimeField(auto_now_add= True) class Meta: ordering = ['-id'] def serialize(self): return{ "id": self.id, "content": self.content, "likes": random.randint(0,200) } While Migrating my models i get the erro -
Form views Failed lookup for key [form] in [{'True': True, 'False': False, 'None': None}, {}, {}, {'catego': <Catego: Salade>}]
I've a form on a post category. I'd like user to post some pictures. And something wrong when I try to load the page. Do you have any idea? I'm beginning with Django. I'm using crispy form and in my template I'm simply using this {% crispy form %} with tags load. class CreatePictureForm(forms.ModelForm): def __init__(self,*args,**kwargs): super(CreatePictureForm, self).__init__(*args,**kwargs) self.helper = FormHelper() self.helper.form_method="post" self.helper.layout = Layout( Field("image",css_class="form-control",style="margin-bottom:10px"), Field("pictureoption",css_class="form-control",style="margin-bottom:10px"), ) self.helper.add_input(Submit('submit','Upload a pic',css_class="single-input textinput textInput form-control")) class Meta: model = Picture fields = [ 'image', 'pictureoption', ] Here is my views: @login_required(login_url='/cooker/login') def catego(request, slug): catego = Catego.objects.get(slug=slug) context = { 'catego': catego } # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = CreatePictureForm(request.POST) # check whether it's valid: if form.is_valid(): form.instance.catego = self.object form.instance.user = self.request.user form.save() return HttpResponseRedirect('/thanks/') else: form = CreatePictureForm() return render(request, 'post_catego.html', context, {'form': form}) @property def total_categories(self): return self.categories.count() -
Should I always use super().clean() when overriding clean() method on a modelform in Django
I have some custom validation in my model, as well as in the modelform in Django project. As I understood this explanation form official Django docs I always have to call super().clean() on modelform clean method, if I want to preserve the validation in the model, like this: class BookForm(forms.ModelForm): has_sequel = forms.BooleanField(initial=True) class Meta: model = Book fields = ['author', 'length', 'has_sequel', 'sequel'] def clean(self): super().clean() if self.cleaned_data['has_sequel'] and self.cleaned_data['sequel'] is None: raise ValidationError('You should indicate the sequel if the book has one.') However, if I don't use super().clean() it works perfectly. Now I am confused, do I need to use super().clean() or not? Note: I used code from this answer for simplicity. -
How to do i validate a password in a login form in Django
I have a login form in which i want to validate if the password is correct. And I try to do it using the clean method. In my form class i am using the clean method like so def clean(self): cd = self.cleaned_data print(self.username) # to debug actual_password = Person.objects.get(username=self.username).password if cd.get('password') != actual_password: self.add_error('password', 'That is not the correct password!') return cd This is the view for the login page: def user_login(request): if request.method == 'POST': form = PersonLoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = Person.objects.get(username=username) if user.password == password: return redirect('all-users/') print(form.errors) form = PersonLoginForm() context = { 'form': form, 'title': 'Login' } return render(request, 'index/login.html', context) Currently i am using this if statement to check if the password is correct: if user.password == password:. But i don't think that is the right way to do it so i am using the clean method. And the error i get when i go into my login page and fill in the credentials is this one: AttributeError: 'PersonLoginForm' object has no attribute 'username' This is what my full PersonLoginForm class looks like: class PersonLoginForm(forms.Form): username = forms.CharField(max_length=20, required=True) password = forms.CharField(max_length=100, required=True) def clean(self): cd = … -
Django(python) I can not display comments from the form on the html page
I am new to Django. I have not found the answer to my question anywhere. I can not display comments from the form on the html page. I am trying to display comments below a post, but an error occurs. I believe that the problem is in views, but I can't figure out what it is. views.py def get_name(request): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): form.save() return redirect('/barbers/') else: form = CommentForm() return render(request, 'main/post_detail.html', {'form': form}) post_detail.html <form action="/barbers/" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'body') models.py class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField(blank=True) date_add = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post, self.name) Error : "POST /barbers/ HTTP/1.1" 405 0 -
How to import all cities in Django_cities_light
I want to import the cities of USA and Canada in Django cities light, so I my settings.py file looks alike CITIES_LIGHT_TRANSLATION_LANGUAGES = ['en'] CITIES_LIGHT_INCLUDE_COUNTRIES = ['CA','USA'] CITIES_LIGHT_INCLUDE_CITY_TYPES = ['PPL', 'PPLA', 'PPLA2', 'PPLA3', 'PPLA4', 'PPLC', 'PPLF', 'PPLG', 'PPLL', 'PPLR', 'PPLS', 'STLMT',] After this : python manage.py migrate cities_light python manage.py manage cities_light But after all this : I just got the cities of Canada not USA I again did the step but data still not dumps , Any suggestion?