Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bug different SQL Queries generated by Django when requested from different application
I have a question related to Django Application and Django REST Framework. I have posted GET request to same API from 3 different device, ReactNative with axios, Browser, and Postman. All these 3 devices trigger different number of queries to database. enter image description here I checked the SQL query detail, and here is the result for each devices. enter image description here Please share some insight on why is this happening, or any other details that I need to provide to find the reason or fix the issue -
Django makemigrations error: "__init__() got an unexpected keywork argument 'max_Length'
I am trying to make migrations to a new app 'users' and keep receiving the error: "TypeError: Field.init() got an unexpected keyword argument 'max_Length'" I previously encountered this error when making migrations on my last app and was able to find the issue on a stackoverflow post which I can't seem to relocate. I know that max_Length is valid because it worked last time but can't seem to remember what I did to make the migrations work. My settings.py files with the users app activated My models.py in my users app: I've spent a lot of time trying to figure out what I am missing but can't seem to get it. Python manage.py makemigrations worked last time with the projects app having the same 'max_Length' constraints. Any ideas on how I can fix this? Thanks in advance -
How can disptach method be implemented in function based views in django
I have started a new project and Trying to do this : Login Required to Checkout in Ecommerce website. If not logged in redirect page to /login/?next=/checkout/ How dispatch method can be implemented here : views.py checkout def checkout(request): form = CheckoutForm(request.POST or None) cart_id = request.session.get("cart_id", None) if cart_id: cart_obj = Cart.objects.get(id=cart_id) if form.is_valid(): form.instance.cart = cart_obj form.instance.subtotal = cart_obj.total form.instance.discount = 0 form.instance.total = cart_obj.total form.instance.order_status = "Order Received" del request.session['cart_id'] form.save() form=CheckoutForm() return redirect("/") else: cart_obj = None return render(request,"checkout.html",{'cart':cart_obj,'form':form}) login def login(request): error="" form = CustomerLoginForm(request.POST or None) if form.is_valid(): uname = form.cleaned_data.get("username") pword = form.cleaned_data.get("password") usr = authenticate(username=uname, password=pword) if usr is not None and Customer.objects.filter(user=usr).exists(): auth_login(request, usr) return redirect("/") else: error="Invalid credentials" return render(request,"login.html", {"form": form, "error": error}) -
I cannot use Django
I want to use Django. I installed it but after that I wanted to create file and I got this error. django-admin.exe startproject mysite . django-admin.exe : The term 'django-admin.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path wa s included, verify that the path is correct and try again. At line:1 char:2 django-admin.exe startproject mysite . + CategoryInfo : ObjectNotFound: (django-admin.exe:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException what is the problem? -
aws ec2 and gcp e2 instances constantly become unresponsive
I've deployed a Django app on AWS-ec2-micro instance and a React app on GCP-e2-micro instance before, but I encountered almost the exact same problem: Server will randomly become unresponsive and unreachable while doing some heavy I/O operations. It happens almost all the time if I try to install some large packages such as tesseract, but it sometimes freezes even when I'm just trying to run a react app using npm start. I've looked at the monitoring and they all have one thing in common: super high CPU usage. Especially after the server becomes unreachable, the CPU meters continue to rise. AWS-ec2 usually will reach almost 100% while GCP-e2 instance will reach beyond 100% to something like 140%. At a certain time, the CPU usage will become stabilized at about 50%, but the server is still unreachable using SSH. The server sometimes recovers itself after hours of being unreachable, but usually, it ends up having to force stop and restart the server. This will cause the public ipv4 to change which I really don't like, so I want to find out why my server is constantly unresponsive. Here is what I've installed on my server: ssh-server vscode-server And then on GCP-e2, … -
Unable to add post in Django getting TypeError: 'AnonymousUser' object is not iterable
When I am clicking on the modal button to add a new post in Django. I am getting the below traceback Traceback (most recent call last): File "D:\Django_AJAX_Latest\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Django_AJAX_Latest\src\posts\views.py", line 22, in post_list_and_create author = Profile.objects.get(user = request.user) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\query.py", line 428, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\query.py", line 974, in filter return self._filter_or_exclude(False, args, kwargs) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\query.py", line 992, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\query.py", line 999, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\sql\query.py", line 1375, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\sql\query.py", line 1396, in _add_qn _add_q child_clause, needed_inner = self.build_filter( n build_filter File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\sql\query.py", line 1302, in build_filter n check_related_objects self.check_related_objects(join_info.final_field, value, join_info.opts) File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\sql\query.py", line 1136, iner return func(self._wrapped, *args)n check_related_objects for v in value: nctional.py", line 249, in inner return func(self._wrapped, *args)s) TypeError: 'AnonymousUser' object is not iterable Below are my files: posts/views.py from django.shortcuts import render from .models import Post from django.http import JsonResponse from .forms import PostForm from profiles.models import Profile def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == … -
how to acess query set values in to html page?
def futsal_user(request): futsal_user = FutsalUser.objects.all() print(futsal_user) for users in futsal_user: users_list = users.company_details print(users_list) for company_name in users_list: print(company_name.name , ) context = {'futsal_user':futsal_user, 'users_list':users_list } return render(request,'futsalusers.html',context) -
Django Jquery get selected value
Hi I'm having issue with passing data to jquery. In my select I have added onchange method and it calls getProductData and pass this select element. In getProductData I get the element and display the selected value. I tried using few methods but the output of alert is [object Object] or undefined. forms.py PD_name = forms.ModelChoiceField( label = "Product Name", queryset = Product.objects.only('name').order_by('id'), to_field_name = 'id', empty_label = "", widget = forms.Select( attrs = { 'class': 'form-control', 'onblur': """form_validation({ 'element' : this, })""", 'onchange': """getProductData({ 'element' : this, })""" } ) ) html <td>{{ Productform.PD_name }}</td> JQuery function getProductData(element) { alert(element.value); } -
Invalid file path or buffer object type: <class 'NoneType'> python-django
I have a issue on read excel file uploaded by user,here my code if request.method == 'GET': add_file = request.FILES.get('monthly_file') df = pd.read_excel(add_file) When i give request.Files['monthly_file] it gave multidict key value error,. So im using request.FILES.get('monthly_file') to get user uploaded file. But it gives Invalid file path or buffer object type: <class 'NoneType'> value error,. How can i resolve it.. Thanks in advance,.. -
[Django][DRF] How to get UNORDERED queryset using .filter?
first of all, I'm not a native at ENG so plz be patient my ENG skills or give me some advice. I'm writing API creating a post by using drf serializer. And I've been facing a problem with "the order of tags adding to the post". post and tag models are connected through M2M field which means, let's say I add tags a, b, and c on a post. The logic I use as follows. # class Serializer # def create(instance): # instance : specific post instance tags = ['t', 'a', 'g', 's'] Tag.objects.bulk_create([Tag(name = tag) for tag in tags]) instance.add.tags(*[tag for tag in Tag.objects.filter(name__in = tags)]) run this at first. tags are added in this order TagQuerySet[Tag<'t'>, Tag<'a'>, Tag<'g'>, Tag<'s'>] And my API takes the other create request that include the tags of the existing like, tags = ['g', 'a', 's'] django add in the sorted order, not in the order I want like, # tags new created instance TagQuerySet[Tag<'a'>, Tag<'g'>, Tag<'s'>] I know the method that adding tags following my list order using for loop for tag in tags: instance.tags.add(Tag.objects.get(name=tag)) but it's not efficient. So my question is how to get queryset using .filter following my list order. … -
I am working on a project in django and thining a way to save the .json file in django which comes from javascript file
But the problem is that the json data comes from javaScript file . once we upload it on the database i want to fetch it again and use it with the javaScript is there any way to upload the json file from javascript and after fetching it send it again to javascipt file thank you -
Get the Auto Field id of the newly created record in the model, provided the description of the fields in forms.py [closed]
I'm just starting to learn django, please tell me: I need to get the id of the newly created record in the model, the problem is that I do not know how to declare it. Since the record id is Auto Field, the id is not passed to forms.py , and is created/remains in the database after the record is created. If I didn't use the functionality forms.py , I would be able to get this id, similar to the example from the documentation (https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#auto-incrementing-primary-keys): Auto-incrementing primary keys If a model has an AutoField — an auto-incrementing primary key — then that auto-incremented value will be calculated and saved as an attribute on your object the first time you call save(): b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.') b2.id # Returns None, because b2 doesn't have an ID yet. b2.save() b2.id # Returns the ID of your new object. There’s no way to tell what the value of an ID will be before you call save(), because that value is calculated by your database, not by Django. For convenience, each model has an AutoField named id by default unless you explicitly specify primary_key=True on a field in your model. See … -
why is my django filter is showing but not working?
I am using Django filters. At first, it is working properly but when I added the pagination part, it's not working anymore. Any help would be appreciated. Thank you in advanced for your help! Here's my views.py views.py def house(request): house=t_house.objects.all() house_paginator=Paginator(house,10) page_num=request.GET.get('page') page=house_paginator.get_page(page_num) houseFilter=HouseFilter(request.GET, queryset=house) house=houseFilter.qs context={ 'count':house_paginator.count, 'page':page, 'houseFilter':houseFilter } return render(request, 'accounts/house.html', context) Here's my filters.py filters.py class HouseFilter(django_filters.FilterSet): class Meta: model=t_house fields=['c_acronym'] and here's my html file house.html <div class="card card-body"> <h2>Total: {{ count }}</h2> <a class="btn btn-primary btn-sm btn-block" href="{% url 'create_house' %}">Create House</a> <div class="p-2 bg-white shadow-sm d-flex justify-content-around align-items-center rounded"> <form method="get"> {{houseFilter.form}} <button class="btn btn-primary" id="mainfont" type="submit">Search</button> </form> </div> <table id="dtBasicExample" class="table table-striped table-bordered table-sm" cellspacing="0" width="100%"> <thead> <tr> <th></th> <th>Code</th> <th>Model</th> <th>Acronym</th> </tr> </thead> {% for h in page.object_list %} <tr> <td><a class='btn btn-sm btn-info' href="{% url 'house_details' h.id %}">View</a></td> <td>{{h.c_code}}</td> <td>{{h.c_model}}</td> <td>{{h.c_acronym}}</td> <td><a class='btn btn-sm btn-info' href="{% url 'update_house' h.id %}">Update</a></td> <td><a class='btn btn-sm btn-danger' href="{% url 'delete_house' h.id %}">Remove</a></td> </tr> {% endfor %} </table> <nav aria-label="..."> <ul class="pagination justify-content-center"> <li class="page-item"> {% if page.has_previous %} <a class="page-link" href="{% url 'house' %}?page={{ page.previous_page_number }}">Previous</a> {% endif %} </li> <li class="page-item"> {% if page.has_next %} <a class="page-link" href="{% url 'house' %}?page={{ … -
(google translate) has a piece of code i don't understand the meaning of, i need an answer as detailed as possible
def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] output = ', '.join([q.question_text for q in latest_question_list]) return HttpResponse(output) -
User permission cache in Django-Webtest
My project uses a custom authentication backend for managing user permissions, leaving the authentication itself intact (to be handled by Django). The backend works fine by itself but started failing in tests, built using Django WebTest. After picking around, I discovered that the culprit is the injection by DWT of another auth backend into the first position in settings.AUTHENTICATION_BACKENDS. My backend directly extends Django’s ModelBackend while DWT’s own backend is based off RemoteUserBackend, which in the end is also an extension of ModelBackend. This bit is important, because while DWT does not define a has_perm method, it is present on its backend nevertheless. The django.contrib.auth.backends.ModelBackend’s get_all_permissions() caches the permissions on the user object in question, when performing a has_perm test: if not hasattr(user_obj, '_perm_cache'): user_obj._perm_cache = { *self.get_user_permissions(user_obj), *self.get_group_permissions(user_obj), } return user_obj._perm_cache Since DWT’s backend comes first in tests, the cache is populated and would not contain the permissions set by my backend, ultimately causing the has_perm test to fail. Ref the code snippet from within Django: def _user_has_perm(user, perm, obj): """ A backend can raise `PermissionDenied` to short-circuit permission checking. """ for backend in auth.get_backends(): if not hasattr(backend, 'has_perm'): continue try: if backend.has_perm(user, perm, obj): return True except PermissionDenied: … -
User permission cache in Django-Webtest
My project uses a custom authentication backend for managing user permissions, leaving the authentication itself intact (to be handled by Django). The backend works fine by itself but started failing in tests, built using Django WebTest. After picking around, I discovered that the culprit is the injection by DWT of another auth backend into the first position in settings.AUTHENTICATION_BACKENDS. My backend directly extends Django’s ModelBackend while DWT’s own backend is based off RemoteUserBackend, which in the end is also an extension of ModelBackend. This bit is important, because while DWT does not define a has_perm method, it is present on its backend nevertheless. The django.contrib.auth.backends.ModelBackend’s get_all_permissions() caches the permissions on the user object in question, when performing a has_perm test: if not hasattr(user_obj, '_perm_cache'): user_obj._perm_cache = { *self.get_user_permissions(user_obj), *self.get_group_permissions(user_obj), } return user_obj._perm_cache Since DWT’s backend comes first in tests, the cache is populated and would not contain the permissions set by my backend, ultimately causing the has_perm test to fail. Ref the code snippet from within Django: def _user_has_perm(user, perm, obj): """ A backend can raise `PermissionDenied` to short-circuit permission checking. """ for backend in auth.get_backends(): if not hasattr(backend, 'has_perm'): continue try: if backend.has_perm(user, perm, obj): return True except PermissionDenied: … -
Render images with Vue.js and Django
I am currently building a LMS where the admin can upload multiple images to a lesson. I am having some issues rendering these images with vue.js. In my models.py I have a Photos model which uses a foreignkey to the lesson model. In the admin I can add the images but in the html the images appear as an empty list with the photo id number e.g [4] In the console I can see the photos array with the length of photos in the lesson object but I cant seem to attach it to the frontend. Here is the vue template: <div class="column is-10"> <template v-if="$store.state.user.isAuthenticated"> <template v-if="activeLesson"> <h2>{{ activeLesson.title }}</h2> {{ activeLesson.long_description }} {{ activeLesson.photos }} <hr> The models.py: class Lesson(models.Model): DRAFT = 'draft' PUBLISHED = 'published' CHOICES_STATUS = ( (DRAFT, 'Draft'), (PUBLISHED, 'Published') ) ARTICLE = 'article' QUIZ = 'quiz' CHOICES_LESSON_TYPE = ( (ARTICLE, 'Article'), (QUIZ, 'Quiz') ) course = models.ForeignKey(Course, related_name='lessons', on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.SlugField() short_description = models.TextField(blank=True, null=True) long_description = models.TextField(blank=True, null=True) status = models.CharField(max_length=20, choices=CHOICES_STATUS, default=PUBLISHED) lesson_type = models.CharField(max_length=20, choices=CHOICES_LESSON_TYPE, default=ARTICLE) def __str__(self): return self.title class Photo(models.Model): lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name='photos') photo = models.ImageField(upload_to ='lesson_images') # resizing the image, you can … -
question on django FileField handling and clean method
I have a rather simple model: class Product(models.Model): data = models.JSONField() number = models.PositiveIntegerField() which I can update via a form: class ProductForm(forms.Form): def __init__(self, *args, **kwargs): product = kwargs.pop("product") super().__init__(*args, **kwargs) self.fields["number"] = forms.IntegerField() self.fields[product.data.keys()[0]] = forms.CharField() self.fields[product.data.keys()[1]] = forms.FileField() ... def clean(self): cleaned_data = super().clean() print(cleaned_data.get("image")) ## prints None print(self.files) ## prints: which all works fine, I put the form in the template with an enctype="multipart/form-data" attribute set and then I receive the form in my TemplateView: class ProductUpdateView(TemplateView): template_name = "update_product.html" def post(self, request, *args, **kwargs): obj = Product.objects.get(pk = kwargs["pk"]) print(request.FILES) ## prints the correct filename! ... return render(request, self.template_name, context) Why is self.files printing None, also cleaned_data.get("image") printing <MultiValueDict: {}>, but in the view, request.FILES correctly knows of <MultiValueDict: {'image': [<InMemoryUploadedFile: test.png (image/png)>]}>? -
Django react application Forbidden 403
When added permission class to view, have an error Forbidden 403 @api_view(['GET']) @permission_classes([IsAdminUser]) def getUsers(request): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data) how to fix that? -
Is there any way to re-render/rerun a custom block in HTML again on button Click?
I am trying to change the List Content in HTML in a Section. I want to change List whenever a category is changed . The content needs to be changed without page reload. Cannot call function from js as it will call the main function responsible for rendering the whole page in Views.py SO functionality should be like: 1 Category clicked 2 List of items in that category changes without loading the whole page Q2 Is there any way to re run a part of code in HTML like {% block run_it_again_ %} code {% end block%} -
psycopg2.errors.UndefinedTable: relation "authentication_author" does not exist: Django v4
I tried to start using Postgresql instead of sqlite in my Django project. I installed postgreqL ON MY Windows, creatred a new database, user and password. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'database_name', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': 'localhost', 'PORT': '5432', } } But when I try to migrate or makemigrations, I got this: File "C:\Users\s...\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "authentication_author" does not exist LINE 1: ...hentication_author"."is_doctor" FROM "authentic... here is my model: class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name="author") slug = models.CharField(max_length=50, null=True, blank=True,) is_doctor = models.BooleanField(default=False) And yes, I deleted the sqlite3 database, all the migrations folders and I created new ones with the init.py inside of them. But still get the same problem. -
objects are swapped when running tests in django
I want to apologize right away if I explained something incorrectly. I am writing this via google translate Django shows error in test after one test. The test succeeds once and then fails. If I don't even change anything, then one still passes, and the other does not. Tests def create_category(): return Category.objects.create(category_title='Category title', slug='category-title') def create_news(category, title, text='news text', pub_date=timezone.now()): return News.objects.create(category=category, image=None, title=title, text=text, pub_date=pub_date) class HomePageTestCase(TestCase): def test_no_news(self): response = self.client.get(reverse('news:home')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'News not found') self.assertQuerysetEqual(response.context['last_20_news'], []) def test_one_news(self): category = create_category() news = create_news(category, 'News title') response = self.client.get(reverse('news:home')) self.assertQuerysetEqual(response.context['last_20_news'], ['<News: News title>']) def test_multiple_news(self): category = create_category() news_1 = create_news(category, 'News title 1') news_2 = create_news(category, 'News title 2') response = self.client.get(reverse('news:home')) self.assertQuerysetEqual(response.context['last_20_news'], ['<News: News title 2>', '<News: News title 1>']) class CategoryPageTestCase(TestCase): def test_no_news_from_category(self): category = create_category() response = self.client.get(category.get_absolute_url()) self.assertEqual(response.status_code, 200) self.assertContains(response, 'News not found') self.assertQuerysetEqual(response.context['news_from_category'], []) def test_one_news_from_category(self): category = create_category() news = create_news(category, 'News title') response = self.client.get(category.get_absolute_url()) self.assertQuerysetEqual(response.context['news_from_category'], ['<News: News title>']) def test_multiple_news_from_category(self): category = create_category() news_1 = create_news(category, 'News title 1') news_2 = create_news(category, 'News title 2') response = self.client.get(category.get_absolute_url()) self.assertQuerysetEqual(response.context['news_from_category'], ['<News: News title 2>', '<News: News title 1>']) Views for which tests were created class HomePageView(ListView): … -
405 Method Not Allowed when deployed but locally no problem
I am new on this forum so please excuse me if I am writing in the wrong category or my question is not complete. We have a simple frontend based on VueJS which has been deployed on a VPS (vps1) and a backend based on Djangorestframework which has been deployed on another VPS (vps2). When we run the frontend locally ($ npm run serve) it can connect to the previously-deployed backend but when we deploy the frontend on Debian serving it using NginX, we get the following error when a user wants to login: [HTTP/1.1 405 Not Allowed 29ms] and also Status 405 Method Not Allowed Version HTTP/3 Transferred 2.22 KB (0 B size) Referrer Policystrict-origin-when-cross-origin I would be happy for any help. The method which is being used is POST. Here is the content of vue.config.js (Vue) module.exports = { devServer: { proxy: { "/accounts/": { target: "https://my-api-server-is-here.com", changeOrigin: true, secure: false, }, }, }, }; and here is the content of settings.py (Djangorestframework): CORS_ALLOW_ALL_ORIGINS = False CORS_ALLOWED_ORIGINS = [ "https://my-frontend-url.com", ] CSRF_TRUSTED_ORIGINS = [ "my-frontend-url.com", ] CORS_ALLOW_CREDENTIALS = True -
CustomUser() got an unexpected keyword argument 'profile_pic'
I am getting an error while submitting a form in my webapp. I am not sure where the problem is occurring in Custom user? U have added the profile_pic field in my models, forms and using it in my views function. But when i try to submit the data using the form, the problem occurs. Here are my codes. Forms.py class CustomUserForm(FormSettings): email = forms.EmailField(required=True) gender = forms.ChoiceField(choices=[('M', 'Male'), ('F', 'Female')]) first_name = forms.CharField(required=True) username=forms.CharField(label="Username",max_length=50,widget=forms.TextInput(attrs={"class":"form-control","autocomplete":"off"})) last_name = forms.CharField(required=True) address = forms.CharField(widget=forms.Textarea) password = forms.CharField(widget=forms.PasswordInput) profile_pic = forms.ImageField() widget = { 'password': forms.PasswordInput(), } def __init__(self, *args, **kwargs): super(CustomUserForm, self).__init__(*args, **kwargs) if kwargs.get('instance'): instance = kwargs.get('instance').admin.__dict__ self.fields['password'].required = False for field in CustomUserForm.Meta.fields: self.fields[field].initial = instance.get(field) if self.instance.pk is not None: self.fields['password'].widget.attrs['placeholder'] = "Fill this only if you wish to update password" def clean_email(self, *args, **kwargs): formEmail = self.cleaned_data['email'].lower() if self.instance.pk is None: # Insert if CustomUser.objects.filter(email=formEmail).exists(): raise forms.ValidationError( "The given email is already registered") else: # Update dbEmail = self.Meta.model.objects.get( id=self.instance.pk).admin.email.lower() if dbEmail != formEmail: # There has been changes if CustomUser.objects.filter(email=formEmail).exists(): raise forms.ValidationError("The given email is already registered") return formEmail class Meta: model = CustomUser fields = ['username','first_name','last_name','email', 'gender', 'password','address','profile_pic'] class AddStudentForm(CustomUserForm): def __init__(self, *args, **kwargs): super(AddStudentForm, self).__init__(*args, **kwargs) … -
How to make edit function work in views.py Django
I am creating an edit option for my entry. But instead of redirecting to the entry page, it is taking me to the addpage to create a new form. How do I redirect to the edit page? Also, how do I make sure that the users previous input would reflect when they click on the edit button. I used initials - is this the best way to do it since I'm not using models but rather forms.Form. VIEWS.PY class AddPageForm(forms.Form): title = forms.CharField(max_length=20) content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", "placeholder": "Tell us more!" }) def edit_page(request, title): entry = util.get_entry(title) if request.method == "POST": form = AddPageForm(request.POST, initial={ "title": title, "content": content }) if form.is_valid(): util.save_entry(title, content) return redirect('encyclopedia:entrypage', title=title) else: form = AddPageForm() return render(request, "encyclopedia/editpage.html", {"form":form}) EDIT PAGE {% block body %} <h1>Edit {{ title }}</h1> <form action="" method="post"> {% csrf_token %} {% form %} <input type="submit" value="Submit" class="btn btn-secondary"> </form> ENTRY PAGE {% block body %} {{ content|safe }} <a href="{% url 'encyclopedia:editpage' title=title %}" class="btn btn-primary">Update</a> <!-- <input="text" name="title" value="{{game.title}}" /> <input="text" name="genre" value="{{game.genre}}" /> --> {% endblock %} URLS.PY app_name = "encyclopedia" urlpatterns = [ path("add_page", views.add_page, name="addpage"), path("edit_page/<str:title>", views.edit_page, name="editpage") ]