Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Error: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module
I'm new to Python and Django, And I'm trying to run a Django app which uses MySQL as a database, I installed mysqlclient using pip, which it shows as Requirement already satisfied: mysqlclient in ./env/lib/python3.7/site-packages (1.4.4) But when I run the project or try to create a superuser,it throws me the following error - Aniruddhas-MacBook-Pro:python_django aniruddhanarendraraje$ ls djangocrashcourse-master env projectNameHere Aniruddhas-MacBook-Pro:python_django aniruddhanarendraraje$ source env/bin/activate (env) Aniruddhas-MacBook-Pro:python_django aniruddhanarendraraje$ pip install mysqlclient Requirement already satisfied: mysqlclient in ./env/lib/python3.7/site-packages (1.4.4) (env) Aniruddhas-MacBook-Pro:python_django aniruddhanarendraraje$ cd djangocrashcourse-master/ (env) Aniruddhas-MacBook-Pro:djangocrashcourse-master aniruddhanarendraraje$ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib Referenced from: /Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Users/aniruddhanarendraraje/Documents/work/pocs/pythonBasics/python_django/env/lib/python3.7/site-packages/django/utils/autoreload.py", … -
How to create fixture where I can add session?
I have my API and here I developed login and logout view. Now I want to write pytests and I have a problem, idk how to create fixture where I can make my user authorized and set some id in session(this is required for the logout). I create new_user via fixture(to avoid working with my db). views @csrf_exempt def login(request): if request.method == "POST": data = json.loads(request.body.decode('utf-8')) if not is_data_valid_for_login(data): return HttpResponseBadRequest() user = authenticate(email=data["email"], password=data["password"]) if user: auth_login(request, user) response = HttpResponse(status=200, content_type='application/json') request.session['id'] = user.id return response return HttpResponseBadRequest() return HttpResponseBadRequest() @csrf_exempt def logout(request): if request.method == "GET": auth_logout(request) response = HttpResponse(status=200) if 'id' in request.session: del request.session['id'] return response return HttpResponseBadRequest pytest import pytest from user.models import User PASSWORD = "testPassword" @pytest.fixture() def user(): return User.create(first_name="Name", last_name="Last", email="test@test.com", password=PASSWORD) -
Django : AttributeError: 'Manager' object has no attribute 'all_with_related_persons'
I am fairly new to django and currently working on a movie database project. However, i have a problem with the models which always comes up with the error. File "C:\Users\public\django\mymdb\django\core\views.py", line 17, in MovieDe queryset = (Movie.objects.all_with_related_persons()) AttributeError: 'Manager' object has no attribute 'all_with_related_persons' Here is the model for the core app from django.db import models from django.conf import settings # Create your models here. class PersonManager(models.Manager): def all_with_prefetch_movies(self): qs = self.get_queryset() return qs.prefetch_related( 'directed', 'writing_credits', 'role_set__movie') class Person(models.Model): first_name = models.CharField( max_length=140) last_name = models.CharField( max_length=140) born = models.DateField() died = models.DateField(null=True, blank=True) objects = PersonManager() class Meta: ordering = ( 'last_name', 'first_name') def __str__(self): if self.died: return '{}, {} ({}-{})'.format( self.last_name, self.first_name, self.born, self.died) return '{}, {} ({})'.format( self.last_name, self.first_name, self.born) class MovieManager(models.Manager): def all_with_related_persons(self): qs = self.get_queryset() qs = qs.select_related( 'director') qs = qs.prefetch_related( 'writers', 'actors') return qs class Movie(models.Model): NOT_RATED = 0 RATED_G = 1 RATED_PG = 2 RATED_R = 3 RATINGS = ( (NOT_RATED, 'NR - Not Rated'), (RATED_G, 'G - General Audiences'), (RATED_PG, 'PG - Parental Guidance ' 'Suggested'), (RATED_R, 'R - Restricted'), ) title = models.CharField( max_length=140) plot = models.TextField() year = models.PositiveIntegerField() rating = models.IntegerField( choices=RATINGS, default=NOT_RATED) runtime = \ models.PositiveIntegerField() … -
Django TypeError at //profile/: 'NoneType' object is not subscriptable
Whenever I create a user or superuser in django administration or in powershell and try to log in and click view profile it will give me an error saying 'NoneType' object is not subscriptable, but when I create a user or superuser in frontend side and try that to log in and click view profile it doesn't give me an error. Profile models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete =models.CASCADE,null=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics') update = models.DateTimeField(default = timezone.now) forms.py class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ['username','email','gender','mobile_number','first_name','middle_name','last_name'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields =['image'] views.py def profile(request): profile = Profile.objects.get_or_create(user=request.user) events = Event.objects.all().order_by('-date_posted') if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form':u_form, 'events':events, 'p_form':p_form, } return render(request,'users/profile.html',context) Registration views.py def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') form.save() messages.success(request, f'{ username } added successfully ') return redirect('announcement') else: form = RegistrationForm() return render(request, 'user_registration.html' ,{'form': form}) forms.py class RegistrationForm(UserCreationForm): email = forms.EmailField(required=False) class Meta: model = User fields = ['username','first_name','middle_name','last_name','gender','mobile_number','email','password1','password2'] … -
Getting a json from a string in Django TemplateView to make a request to django-rest API
I started from this question but was not able to solve this: I have a Django templateview with an information I want to pass to a django-rest API via HTML form. API POST request accepted: a JSON file with a string value [ {"filename" : "01-01-01-01-01-01-01.wav"} ] What I build: Views.py class SelectPredFileView(TemplateView): """ This view is used to select a file from the list of files in the server. After the selection, it will send the file to the server. The server will return the predictions. """ template_name = "select_file_predictions.html" success_url = '/predict_success/' def get_context_data(self, **kwargs): """ This function is used to render the list of file in the MEDIA_ROOT in the html template. """ context = super().get_context_data(**kwargs) media_path = settings.MEDIA_ROOT myfiles = [f for f in listdir(media_path) if isfile(join(media_path, f))] context['filename'] = myfiles return context def send_filename(self, request): filename_json = json.dumps(self.context) return render(request, "template.html", context={'filename': filename_json}) class Predict(views.APIView): def __init__(self, **kwargs): super().__init__(**kwargs) modelname = 'Emotion_Voice_Detection_Model.h5' global graph graph = tf.get_default_graph() self.loaded_model = keras.models.load_model(os.path.join(settings.MODEL_ROOT, modelname)) self.predictions = [] def post(self, request): """ This method is used to making predictions on audio files previously loaded with FileView.post """ with graph.as_default(): for entry in request.data: filename = entry.pop("filename") filepath = str(os.path.join(settings.MEDIA_ROOT, … -
How I can host .sql file on clever cloud platform on postgresql addons?
I have a database in the PostgreSQL database system. I want to host this database on clever-cloud platform. I have created a PostgreSQL instance on clever-cloud. -
Heroku stuck at Building Source for Django app
I have successfully pushed the previous versions of my Django app to Heroku. It usually shows some errors if it is not able to deploy, but this time it is stuck at this for about an hour: Counting objects: 10977, done. Delta compression using up to 8 threads. Compressing objects: 100% (7719/7719), done. Writing objects: 100% (10977/10977), 17.29 MiB | 3.00 MiB/s, done. Total 10977 (delta 3954), reused 6832 (delta 2062) remote: Compressing source files... done. remote: Building source: Here's the GitHub link to the app that I am trying to deploy: https://github.com/surajsjain/smart-aquaponics-backend Please Help -
Unable to run django on docker
I'm setting up a django server application on docker. docker runs the container well but the command to run django is not taking by docker. I've already gone through few youtube videos but none of them worked for me Dockerfile FROM python:3.6-stretch MAINTAINER *** ENV PYTHONBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /specfolder WORKDIR /specfolder COPY ./myfolder /specfolder EXPOSE 8000 CMD ["python", "manage.py runserver"] i've tried placing the command under docker-compose.yml file under commands: sh -c "python manager.py runserver" but none of them worked docker-compose.yml file version: "3" services: myapp: build: context: . ports: - "8000:8000" volumes: - ./myfolder:/specfolder requriements.txt django==2.2.4 pandas xlrd xlsxwriter as of now under kinematics i am getting the python shell Type "help", "copyright", "credits" or "license" for more information. >>> 2019-08-31T13:34:51.844192800Z Python 3.6.9 (default, Aug 14 2019, 13:02:21) [GCC 6.3.0 20170516] on linux unable to access the 127.0.0.1:8000/myapp/login in the browser. -
How to display text/image/gif as wait while the view method is rendering?
The Django App is taking some time to load. how can any test/image is displayed while page load time? -
Put in django admin form two TinyMCE side by side
If I try to put side side by side two tinyMCE fields in django admin form the second one on the right will be rendered ugly. I'd like to have something more proportionate, with the right ratio. I already tried to change the width inside tinyMCE profile. but what happened is that I had more white space instead reducing area of widget Here an example of what I did from tinymce.models import HTMLField from django.contrib import admin from django.db import models # THIS IS THE MODEL class A(models.Model): description = HTMLField( entity="entity", help_text="Description (HTML)", null=True, blank=True, ) description2 = HTMLField( entity="entity", help_text="Description 2 (HTML)", null=True, blank=True, ) # THIS IS THE ADMIN @admin.register(A) class AAdmin(admin.ModelAdmin): list_display = ('id', ) fieldsets = ( ( 'Properties', { 'fields': ( ('description', 'description2'), ), }, ), ) This is the result https://i.imgur.com/tOuVHLo.png -
Why Django can't find image on this path?
So. This is my first Django project. I am using Django Admin template to add/edit/delete content. I added option to add image to specific section. Here is the model class Project(models.Model): title = models.CharField(max_length = 100) description = models.TextField() technology = models.CharField(max_length = 20) image = models.ImageField(upload_to = "projects/images/") And it works. It creates images directory inside project directory which can be found in root directory. When I load image in template I load it with <img src="/{{project.image.url}}" alt="" class="card-img-top"> Then in HTML it creates element <img src="/projects/images/106780.jpg" alt="" class="card-img-top"> But inn console it says that it can't find image on http://127.0.0.1:8000/projects/images/106780.jpg My directory has this hierarchy portfolio | |__ blog |__ projects |__ __pycache__ |__ images |__ migrations |__ templates |__ ... |__ venv |__ db.sqlite3 |__ manage.py -
What is the CBV equivalent of passing params via kwargs and query strings in a FBV?
If I want to pass a number of variables via a URL path to a view so that I can use it to look up more than one object I have a couple of different ways to do this: 1. Passing as a key word argument in the URL path I can pass a parameter via the url path as a kwarg in both FBV and CBV: // Function based view: path('task/detail/<int:pk>/<int:abc>/', views.task_detail, name='task_detail')` // Class based view: path(`task/detail/<int:pk>/<int:abc>/`, views.TaskDetailView.as_view() Which is passed in the URL as mysite.com/task/detail/1/2/. In a FBV I can access both kwags to get separate objects via request: // Function based view: def task_detail(request, pk, abc) first_object = get_object_or_404(SecondObjectModel, id=pk) second_object = get_object_or_404(SecondObjectModel, id=abc) 2. Passing as a query string in the URL path Alternatively I can pass the parameter via a query string, which is parsed and parameters are stored as a QueryDict in request.GET, for example mysite.com/task/detail/?pk=1&&abc=2. I can then access these via both FBV and CBV as: // Function based view: def task_detail(request): first_object_id = request.GET.get('pk') second_object_id = request.GET.get('abc') first_object = get_object_or_404(SecondObjectModel, id=pk) second_object = get_object_or_404(SecondObjectModel, id=abc) What is the classed base view equivalent of each of these approaches? Why and when should … -
Retrieving results by running a query based on condition in Django
So i have following 2 tables which i am using to write a Book library in Django. class Book(models.Model): """Model representing a book (but not a specific copy of a book).""" title = models.CharField(max_length=200) author = models.CharField(max_length=200,null=True) summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book",null=True) genre = models.ManyToManyField(Genre, help_text="Select a genre for this book") shelflocation = models.CharField(max_length=10, null=True) pages = models.IntegerField(null=True) copies = models.IntegerField(null=True,default=1) and another BookInstance model where i am maintaining both the status and number of copies class BookInstance(models.Model): """Model representing a specific copy of a book (i.e. that can be borrowed from the library).""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular book across whole library") book = models.ForeignKey('Book',on_delete=models.SET_NULL,null=True) due_back = models.DateField(null=True, blank=True) borrower = models.ForeignKey('MemberList',on_delete=models.SET_NULL,null=True) LOAN_STATUS = ( ('d', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) So if a book is loaned then status will be set to 'o' in above table. I would like to display all the Books of a specific author whose books has been loaned and copies are still available. I tried adding queryset to list but it failed. Is there a way to query based on the condition in the following query if(book_instance_count < book.copies or … -
django ModelMultipleChoiceField generate multiple option from an instance
i have been given a project that has a ModelForm like this: class AddUserToPrivateCourseForm(forms.ModelForm): class Meta: model = Course fields = [ 'users', ] and users is a Foreignkey relation to user table .it works as expected it generates a select option html <select> <option value="pk1">Name</option> <option value="pk2">Name</option> </select> that are then in the template converted by select2 to dynamic search field , which the options are users to be selected By Name for the relevant course now i have to add users phone Numbers as a search property in the field. so i thought of something like the widget generates something like this <select> <option value="pk1">Name</option> <option value="pk1">Phone Number</option> <option value="pk2">Name</option> <option value="pk2">Phone Number</option> </select> is this possible or i have to come up with something completely different to solve this? -
How display form in HTML intergration DRF and django-filters
Hi I have problem with intergration DRF and django-filters. How to display filters form in my HTML like in DRF API views. I was trying use @action decorator but that no works me. Someone have a idea how solve this problem ? class AlbionViewsSets(viewsets.ModelViewSet): queryset = Albion_data.objects.all() serializer_class = Albion_data_Serializer filterset_class = Itemfilters lookup_field = "item" -
'DeferredAttribute' object is not callable django1.2.5
I'm working on a simple django project, but i face this problem that you see below so, i want a solution because i really got tired I expect the output of that code to be numberone but the actual output is this error : TypeError at /db/ 'DeferredAttribute' object is not callable Request Method: GET Request URL: http://127.0.0.1:8000/db/ Django Version: 2.1.5 Exception Type: TypeError Exception Value: 'DeferredAttribute' object is not callable Exception Location: /home/mohammed/Desktop/New life programming/python/pythonDjano/Filecorse/NewDjango/MohammedAlaa/Abdullah/views.py in db, line 16 Python Executable: /usr/bin/python3 Python Version: 3.6.8 Python Path: ['/home/mohammed/Desktop/New life ' 'programming/python/pythonDjano/Filecorse/NewDjango/MohammedAlaa', '/usr/local/lib/python3.6/dist-packages/pip-19.1.1-py3.6.egg', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/mohammed/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Sat, 31 Aug 2019 11:13:18 +0000 #views.py from django.shortcuts import render from django.http import HttpResponse from .models import Product def Home(request): return HttpResponse('Welcome, Mohammed Alaa :)') def htm(request): return render(request,'htm.html',{'hello':"hello Mohammed Abo Alaa again:)", 'days':['wed', 'fri', 'thru'] }) def others(request): return HttpResponse('Welcome, Mohammed Alaa :) form others') def db(request): dat = '' p1 = Product(namee='numberone', pricee=500,Type='m') p1.save() dat = Product.namee() return HttpResponse(dat) -
How copy folder in django custom commands
I want to copy a folder after my command calls. I create my custom command in the following path myapp/management/commands/createshop.py and my code from django.core.management.base import BaseCommand, CommandError import os, shutil class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('mobile', type=str, help='Mobile') parser.add_argument('shopname', type=str, help='Shop Name') parser.add_argument('password', type=str, help='password') def handle(self, *args, **options): src = 'E:/myproject/sample/' dest = 'E:/myproject/shops/shop-' + options['shopname'] shutil.copytree(src, dest) self.stdout.write(self.style.SUCCESS('shop "%s" created successfully' % options['shopname'])) the folder will not copied also there is no error. Am I wrong? how can I call a python command in django custom commands? -
How to import and define choice fields?
how to define and import choice field how can i define choice field in models.when i was try below im getting errorNameError: name 'GENDER_CHOICES' is not defined. from django.db import models from django.contrib.auth.models import class Userprofile(models.Model): gender = models.CharField(max_length=10,choices=GENDER_CHOICES, blank=True) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) -
Using PATCH or PUT deletes the object - DJango
I'm using Django Rest as my BE server, and have created a Chat object that holds messages and participants, and I manage to create objects as expected using the POST method and get these objects using the GET method - so far so good. But when I try to update the participants by doing a PUT or PATCH requests on the object with different participants, the object just gets deleted (another GET request does not bring that object back as a result). models.py (the messages have foreign key to the Chat object but this is not the issue so i will leave it out): class Chat(models.Model): participants = models.ManyToManyField(Profile, related_name='chats', blank=True) def __str__(self): return str(self.id) serializers.py: class ChatSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="chat_app:chat-detail", lookup_field='id') participants = serializers.HyperlinkedRelatedField(many=True, view_name="user_app:profile-detail", queryset=Profile.objects.all(), lookup_field='id', required=False) messages = MessageSerializer(many=True, required=False, read_only=True) class Meta: model = Chat fields = ('id', 'messages', 'participants', 'url') read_only = ('id', ) views.py: class ChatViewSet(BaseModelViewSet): serializer_class = ChatSerializer permission_classes = (permissions.IsAuthenticated, ) lookup_field = "id" def get_queryset(self): return self.request.user.profile.chats Any ideas? -
FileNotFoundError when opening a file on AWS S3
I use the S3 private repository to store media files. Presigned URLs are used to access files for users. Files are correctly saved and opened by the generated link. models.py class Documents(models.Model): """ uploaded documents""" author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) filedata = models.FileField(storage=PrivateMediaStorage()) filename = models.CharField(_('documents name'), max_length=64) created = models.DateTimeField(auto_now_add=True) filetype = models.ForeignKey(Doctype, on_delete=models.CASCADE, blank=True) url_link = models.URLField(default=None, blank=True, null=True) Now I need to make an endpoint on which I will give the necessary file by model id. views.py def view_pdf(request, pk): pdf = get_object_or_404(Documents, pk=pk) file_data = open(pdf.url_link, "rb").read() return HttpResponse(file_data, contenttype='application/pdf') urls.py url('pdf/(?P<pk>\d+)$', view_pdf, name='view_pdf'), When I try to open a file, I get an error FileNotFoundError at /api/v1/files/pdf/90 [Errno 2] No such file or directory: 'https://mysite.s3.amazonaws.com/media/private/fd2a6f39857a4b4799135b41b4fad313.pdf?AWSAccessKeyId=AKIAZTR5wSDFer6YOWPPL5IFOS&Signature=lBUSDRbSAkUOfXzCeA3sc6OpX3PBqo%3D&Expires=15679330600' But then I copy the link and paste it manual in browser all open fine -
class_forms on the same page
I have a class PostCreateView and I want to be able to recognize 2 form_class at the same page When I have tried it said, tupple can not be called when I write like this: form_class = PostForm, CommentView Views.PY class PostCreateView(FormView, LoginRequiredMixin, CreateView, CommentForm): form_class = PostForm model = Post # category = Category.objects.all() def post(self, request, *args, **kwargs): form = PostForm() data = Post.objects.all() Models.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ["Name", "Content"] widgets = { I expect my 2 forms appear on the page without no issue. But only one appears and renders: -
How to check unique while update on django
"I am stuck in this, i have successfully check validation of unique while user is register, but during his profile update how i check the unique email during the update" Anyone can help me on this ? -
adding extra field ('city') to UserRegisterForm Django
When new users register I want to store: fields = ['username', 'email', 'password1', 'password2', 'city'] so I extended UserRegisterForm by adding 'city' to the form. It renders fine in the template and save everything except 'city'. There is no even column 'city' in the new users profile when checking by admin page so looks like its not creating one. I found few similar posts and been following Doc but that didint help. Have tried many different ways but will post two I think mostly sensible ones. EXAMPLE 1 - *forms.py* ... from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() city = forms.CharField(required=True) class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'city'] def save(self, commit=True): user = super(UserRegisterForm, self).save(commit=False) user.city = self.cleaned_data['city'] if commit: user.save() return user - *views.py* ... from django.contrib.auth.forms import UserCreationFormfrom from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() print('VALID') username = form.cleaned_data.get('username') messages.success(request, '{} Your account has been created! You can now Log In'.format(username)) return redirect('/login/') else: form = UserRegisterForm() context = { 'form': form, } return render(request, 'users/register.html', context) @login_required def profile(request): return render(request, 'users/profile.html') - … -
The django login screen does not transition from loading to page
I changed the database to postgresql with django. And after migrete, I can't log in when I check my login screen. I also tried to log in to the management screen, but I could not log in. Both have stopped during loading. The user is created by executing createsuperuser. And the user was created when checking the database. I deleted the migrete file or restarted the server, but it doesn't work. If you enter the wrong password, "Your username and password didn't match. Please try again." There is no display of errors, etc., and the server is loading even after stopping. I also did the following command find . -path "*/migrations/*.py" -not -name "__init__.py" -delete find . -path "*/migrations/*.pyc" -delete python manage.py makemigrations python manage.py migrate -
maximum recursion depth exceeded while calling a Python object when creating child page of parent page
This is my child code page {% if post.page_set.all %} {% for child in post.page_set.all %} <div> <h5> <a href="" style="margin-left:10px;">{{child.title}}</a>&nbsp;<a href="{% url 'add_child_page' pk=child.pk %}"><i class="fa fa-plus" style="font-size:15px ;color:#2F4F4F;"></i></a> </h5> {% include "makerobosapp/child_code.html" with post=post %} </div> {% endfor %} {% endif %} And this is my homepage where i want to show child post title {% block content %} {% for post in posts %} <div class="post-content"> <h3> <a href="{% url 'post_detail' pk=post.pk %}">{{post.title}}</a>&nbsp;<a href="{% url 'add_child_page' pk=post.pk %}"><i class="fa fa-plus" style="font-size:20px ;color:#2F4F4F;"></i></a> </h3> <p>{{post.content| safe |linebreaksbr}}</p> <div class="date"> <p>published date: {{ post.published_date }}</p> </div> {% include "makerobosapp/child_code.html" with post=post %} {% endfor %} {% endblock %}