Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to validate field data when we abstracting djoser serializer?
I'm using django and djoser for backend authentication and react on frontend side. I want to put a condition on email in serializer that if email already exists send them error msg that "email already taken" otherwise register. serializer class UserCreateSerializer(UserCreateSerializer): class Mera(UserCreateSerializer.Meta): model = User fields = ("id","username","email","password") def validate_email(self, validated_data): email = validated_data["email"] if User.objects.filter(email=email).exist(): msg = "email already taken" raise msg return email djoser settings in settings.py DJOSER = { ..., "SERIALIZERS" : { "user_create":"accounts.serializers.UserCreateSerializer", "user":"accounts.serializers.UserCreateSerializer", "user_delete":"djoser.serializers.UserDeleteSerializer", }, } accounts/models.py from django.db import models from django.contrib import auth # Create your models here. class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) Many many thanks in reading and answering this question.. -
Best practice to validate multiple foreign keys while saving a ModelForm
I have a model that has two foreign keys: class Book(models.Model): name = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=CASCADE) created_by = models.ForeignKey(User, blank=True, null=True, on_delete=CASCADE) I have a modelform for it: class BookForm(modelForm): class Meta: model = Book exclude = ('author', 'created_by',) In my business logic, I want to save a new author and a book with it in the same view, and the created_by could be null in some cases. So, before saving an instance of a BookForm, I will create an author first. So, suppose that I have created an author, then I will do the below to save a book: f = BookForm(post_data) if form.is_valid(): instance = f.save(commit=False) instance.author = author instance.created_by = user instance.save() What I did so far is working fine, but the foreign key fields are not part of the validation. As you can see from the model class, author field is mandatory, but created_by field is optional. So, if I want to add some validations for them, I have to add them explicitly by customizing the is_valid() method, or by adding some if conditions before instance.author = author. The bigger picture is that I have a model with much more foreign keys; some of … -
Django - running server in local network
I want to run simple Django server that I would like to be accessible via local network using devices (RPi) ip, on port 8000. I use command: python3 manage.py runserver --noreload <device_ip>:8000 I go to browser on my PC connected to the same local network, go to <device_ip>:8000 and it works. The problem is, when I click on button which triggers HttpRedirect('x') in my views.py, the redirection url is locahost:8000/x instead of <device_ip>:8000/x. Am I missing something? Is it even possible to do it the way I'm trying? -
Django How te get particular field of model's instance using variable in view
I'm new in django. I try to change fields values in one instance of my model. In for loop i is variable which is equal to name of field which i want to change but when I try to get field of instance by coding name_of_instance.i i is not interpreted as my variable but just 'i'. Is there any way to get field of instance using variable. Something like name_of_instance[i] or something like that. Thanks for help. def dodajsklJson (request): if request.is_ajax(): dodanySkladnik=request.POST.get("skladnik") roboczareceptura.objects.create(skladnik=dodanySkladnik,) ostatniskl = roboczareceptura.objects.last() for i in data[dodanySkladnik]: if type(i)!=list: a=request.POST.get(str(i)) ostatniskl.i=a #here is where it doesn't work. i is not i from above :( ostatniskl.save() -
Static images disappeared after using AWS for Heroku site
I made a site for Heroku using Django and I got it to the point where it kept all the static images and files on Heroku just fine but the images the user uploads got deleted on dyno reset; that's why I wanted to use AWS to host the files the user uploads. This is the code I am using in my settings: AWS_ACCESS_KEY_ID = os.environ.get('my key') AWS_SECRET_ACCESS_KEY = os.environ.get('my secret key') AWS_STORAGE_BUCKET_NAME = 'my bucket name' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' STATIC_URL = 'http://' + AWS_STORAGE_BUCKET_NAME + '.s3.eu-west-1.amazonaws.com/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' AWS_QUERYSTRING_AUTH = False I added the "eu-west-1" part in the static URL because it was in the bucket's URL but not in my site's src for the image. The problem is that now most of my JavaScript and CSS have disappeared as have all my static files that were previously just on Heroku and worked fine, furthermore the files that the user uploads also don't show up and the src doesn't containt the "eu-west-1" that I added (and it doesn't work without that part either). Can somebody help me make it so that my static files are on Heroku as before while user uploaded files … -
Form is not populated with data from request
The form is not populated with the data from request. This is the forms.py : class RulesForm(forms.Form): def __init__(self, *args, **kwargs): super(RulesForm, self).__init__(*args, **kwargs) self.add_fields() self.label_suffix = "" def add_fields(self): rules = Rule.objects.all() for a in rules: self.fields[a.id] = forms.BooleanField(label=a.rule, required=False) And my views.py : def my_rule(request): rules_form = RulesForm() if request.method == "POST": rules_form = RulesForm(request.POST) if rules_form.is_valid(): print(request.POST) print(rules_form.cleaned_data) context= {'rules_form': rules_form} return render(request, 'rules/sign_rule.html', context) When I check what does request.POST contains, I can see this value checked in the checkbox. For example if 16 is checked : <QueryDict: {'csrfmiddlewaretoken': ['qS2scx96GcoTq6iL1V6dZO0cdB2LF2q717Q19zvahdwg3U0gS1r1SjmCzvd9mb0B'], '16': ['on']> But I see it as False and not True in the cleaned_data : {2: False, 3: False, 4: False, 7: False, 8: False, 9: False, 10: False, 11: False, 12: False, 13: False, 14: False, 15: False, 16: False, 17: False, 18: False} Why ? -
What is the use and sense of Meta Class used in Django under Models Section. Also Why and When we specify it and when not
class Comment(models.Model): lesson_name = models.ForeignKey(Lesson , null=True, on_delete=models.CASCADE, related_name='comments') comm_name= models.CharField(max_length=100 , blank=True) author = models.ForeignKey(User , on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): self.slug = slugify("comment by" + "-" +str(self.author) + str(self.date_added)) super().save(*args, **kwargs) def __str__(self): return self.comm_name class Meta: ordering = ['-date_added'] -
Can we use django filter with a variable?
Here are my codes: Models.py class Members(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) username = models.CharField(max_length=100) email = models.EmailField() phone = models.CharField(max_length=14) Views.py (fails to return any value) def employeeView(request): member = User.username members = Members.objects.filter(username= member) return render(request,'members/user_profile.html', {'members': members}) Views.py (returns properly) def employeeView(request): members = Members.objects.filter(username= 'mahesh') return render(request,'members/user_profile.html', {'members': members}) I am trying to get the data out by filtering the Members.obejcts by passing the username of the logged-in user. It works when hardcoded, but not by passing a variable. Is there any workaround? -
How to Scale ERPNext application on your own server to 2000 user with heavy load?
How to Scale the ERPNext application on your own server to 2000 users with a heavy load? I have created one application server and two read/ write replica database servers. with heavy RAM and SSD's more than enough to handle the load. But at the time of load testing UI Becomes slow and unresponsive. Could anybody please help me figure out the right way to scale erpnext to 2000 users to our own server -
How to navigate to part of page in Django
So I have posts and I can add comments to them. I have a CreateCommentView and I want that the success_url goes to the home page where it has all posts, but navigate to the post I added a comment to. (so like it scroll down to the past I added comment to ) views.py class CommentCreatView(LoginRequiredMixin, CreateView): model = Comment fields = ['text'] template_name = 'comments/create.html' success_message = 'Your comment has been added' success_url = reverse_lazy('homepage') def form_valid(self,form): form.instance.user = self.request.user form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) models.py class Comment(models.Model): text = models.CharField(max_length= 2200) post = models.ForeignKey(Posts, on_delete=models.CASCADE , related_name='comments' ) user = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now()) def __str__(self): return self.text the homepage HTML {% extends "posts/base.html" %} {% block content %} {% for post in posts %} <h6>{{post.user.username}}</h6> <img src="{{ post.image.url }}" /> <h6>{{post.user.username}}</h6> <p>{{post.caption}}</p> <h6>Comments</h6> {% for comment in post.comments.all %} <hr class="bg-danger border-2 border-top border-primary"> <h6>{{comment.user}}</h6> <p>{{comment.text}}</p> {% endfor %} <div> <a href="{% url 'add-comment' post.id %}" class="btn btn-outline-primary mt-2">Add Comment</a> </div> {% endfor %} {% endblock %} -
django dict.get() takes no keyword arguments
I'm trying to build a form that sends an email to me and to the person who summited the form and also create an object in Aanmelden. Views.py def send_email(email): context = {'email': email} template = get_template('emails/message-confirmation.html') content = template.render(context) email = EmailMultiAlternatives( 'Test email', 'AmiSalta message confirmation', settings.EMAIL_HOST_USER, [email] ) email.attach_alternative(content, 'text/html') email.send() def activiteit(request, activiteit_id): activiteit = Activiteit.objects.get(pk=activiteit_id) form = AanmeldenForm() if request.method == 'POST': email = request.POST.get('email') send_email(email) form = AanmeldenForm(request.POST) if form.is_valid(): naam = form.cleaned_data['naam'] activiteit = Activiteit.objects.get(pk=activiteit_id) email = form.cleaned_data['email'] send_mail('Aangemeld!' + naam, activiteit, email, ['varela.enmanuel@gmail.com']) form.save return redirect('./') return render(request, "activiteit.html", { "activiteit": activiteit, 'form':form, }) models.py class Activiteit(models.Model): titel = models.CharField(max_length=64) docent = models.CharField(max_length=32) icon = models.ImageField() uitleg = models.TextField() lange_uitleg_1 = models.TextField() lange_uitleg_2 = models.TextField(default=None, blank=True) afbeelding_1 = models.ImageField(default=None, blank=True) afbeelding_2 = models.ImageField(default=None, blank=True) nos = models.IntegerField() rem = models.IntegerField() class Aanmelden(models.Model): naam = models.CharField(max_length=32) leerlingnummer = models.IntegerField(validators=[beperk_aanmelden,]) email = models.EmailField(name='email') klas = models.ForeignKey(Klas, on_delete=models.CASCADE, default=None, blank=True) nos = models.IntegerField(default=1) activiteit = ForeignKey(Activiteit, on_delete=models.CASCADE, default=None, blank=True) forms.py class AanmeldenForm(forms.ModelForm): class Meta: model = Aanmelden fields = ( 'naam','leerlingnummer','klas','activiteit', 'email') But I keep getting this error error message django dict.get() takes no keyword arguments. What is causing it? The emails get send anyway … -
My for loop stops working when I add an else condition
I am trying to define a function in order to create a new page in a wiki application. The user should provide a title and a content. If the title already exists in the list, the user should get an error message. If not, the new entry should be saved in the list with its content. Here is my code so far: def new_page(request): if request.method == "POST": title = request.POST.get("title") entries = util.list_entries() #this function is already defined and it returns a list of all names of encyclopedia entries. for entry in entries: if title.lower() == entry.lower(): return HttpResponse(f"ERROR: {entry} Already Exists") else: return render(request,"encyclopedia/new_page.html") The above code works fine, when I type in an existing title I get the error message. The problem starts when I add an else condition. Here's an example (for just trying out the code,I don't want the content to be saved yet.) def new_page(request): if request.method == "POST": title = request.POST.get("title") entries = util.list_entries() for entry in entries: if title.lower() == entry.lower(): return HttpResponse(f"ERROR: {entry} Already Exists") else: return HttpResponse("Thank you for your contribution!") else: return render(request,"encyclopedia/new_page.html") Now, even if I type in an existing title, I get "Thank you for your contribution!". … -
Preview option is worked one time, after i click edit and update the forms it allow me to login url in django?
views.py #Vendor Signup def VendorSignup(request): vendorform = VendorCreationForm() vendordetailform = VendorAdminDetailsForm() if request.method == 'POST': vendorform = VendorCreationForm(request.POST) vendordetailform = VendorAdminDetailsForm(request.POST, request.FILES) if vendorform.is_valid() and vendordetailform.is_valid(): # if vendorform.is_valid(): new_user = vendorform.save() vendordetailform.instance.vendoruser = new_user vendordetailform.save() # new_user.is_active = False new_user.save() user_details = CustomUser.objects.filter(id=new_user.id) vendor_details = user_details[0].vendor_details.all() return render(request,'vendor/preview.html', {'user_details':user_details, 'vendor_details':vendor_details}) else: vendorform = VendorCreationForm() vendordetailform = VendorAdminDetailsForm() return render(request, 'vendor/signup.html', {'vendorform': vendorform, 'vendordetailform':vendordetailform}) #Vendor Edit def VendorEdit(request, id=0): if request.method == "GET": vendor = CustomUser.objects.get(pk=id) print(vendor) form = VendorCreationForm(instance=vendor) vendordetails = VendorDetails.objects.filter(vendoruser_id=vendor.id) print(vendordetails) vendordetailform = VendorAdminDetailsForm(instance=vendordetails[0]) return render(request, 'vendor/edit.html', {'form':form, 'vendor':vendor, 'vendordetailform':vendordetailform}) else: vendor = CustomUser.objects.get(pk=id) form = VendorCreationForm(request.POST, instance=vendor) vendordetails = VendorDetails.objects.filter(vendoruser_id=vendor.id) vendordetailform = VendorAdminDetailsForm(request.POST, request.FILES, instance=vendordetails[0]) if form.is_valid() and vendordetailform.is_valid(): vendor=form.save() vendordetailform.instance.vendoruser = vendor vendordetailform.save() # vendor.is_active = False # vendor.save() return redirect('login') here I registered users and preview their details in preview.html.Edit is worked. but after update the register form, it won't me to preview the form, it redirect me to login page.I have save and edit button in preview.html. If i click save button it redirect me to login page and it worked, but when occuring this i want to inactive the user in the final stage of signup. can anyone please,solve this issue -
Find all appointments for specific date
My goal is to get all appointments (start_date and time) for current month and put them in a table under dates of the current month. For example show all dates of November (Monday, Tuesday, etc. and under the dates show the appointments that took place for that day. Can you propose a way of doing that? My first try is to get all dates of the month (November) and show them to template. Then get all appointments with start_date and time For example: # Show dates of current month and show them in template year = today.year month= today.month num_days = calendar.monthrange(year, month)[1] days = [datetime.date(year, month, day) for day in range(1, num_days+1)] print(days) days_list = [] for days in days: days_str = days.strftime('%A, %d') days_list.append(days_str) print(days_str) #Query for the appointments, something like: appointments = Appointment.objects.filter().... -
how change redis for recommender.py app in django?
i wrote a code for suggested product named recommender.py i want to change redis because my host does not support redis-server but i don't know how do that. i want to change all code from redis to mysql or postgresql or mongodb anyone can help me? this is my code from myshop.settings import REDIS_DB, REDIS_PORT import redis from django.conf import settings from .models import Product r = redis.Redis(host=settings.REDIS_HOST,port=settings.REDIS_PORT,db=settings.REDIS_DB class Recommender(object): def get_product_key(self,id): return f"product:{id}:bought_with" #product:1:bought_with def products_bought(self,products): product_ids = [p.id for p in products] for product_id in product_ids: #[1,2,3] for with_id in product_ids: if product_id != with_id: r.zincrby(self.get_product_key(product_id),1,with_id) def suggest_products_for(self,products,max_results=6): product_ids = [p.id for p in products] if len(products) == 1: suggestions = r.zrange(self.get_product_key(product_ids[0]),0,-1,desc=True)[:max_results] else: flat_ids = ''.join([str(id) for id in product_ids]) #[1,2,3] => "123" tmp_key = f"tmp_{flat_ids}" #"123" => tmp_123 keys = [self.get_product_key(id) for id in product_ids] r.zunionstore(tmp_key,keys) r.zrem(tmp_key,*product_ids) suggestions = r.zrange(tmp_key,0,-1,desc=True)[:max_results] r.delete(tmp_key) suggested_products_ids = [int(id) for id in suggestions] suggested_products = Product.objects.filter(id__in=suggested_products_ids) return suggested_products -
how to customize sent emails in djoser?
I build React&Django project and use Djoser for registration and auth. I want to customize sent email content on Gmail. Where should I change it? -
Django: ForeignKey(models) to not visible model?
below you can see a simple connection of two models via foreignkey! class Manufacturer(models.Model): name = models.CharField(max_length=50, null=False, blank=False) user_created = models.CharField(max_length=50, null=False, blank=False) date_created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['name'] def __str__(self) -> str: return self.name class CarModel(models.Model): manufacturer = models.ForeignKey(Manufacturer, null=False, blank=False, on_delete=models.CASCADE) name = models.CharField(max_length=50, null=False, blank=False) user_created = models.CharField(max_length=50, null=False, blank=False) date_created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['name'] def __str__(self) -> str: return f"{self.name} ({self.manufacturer})" My Question: is it possible to create such a connection, even if the first model (in this example the Manufacturer) is not created by django - so there is no typical modelclass - but still inside the same database? Like importing or loading the other model from the database to connect it? Also I'm using Postgresql! Thanks for your help and have a great sunday! -
Nginx. Issue to access redoc
I have the Django project and trying to deploy it on server using docker and nginx. There is no problem to deploy it and get access to required pages, but I can't get access to redoc page. Nginx config is following ( default.conf): server { listen 80; location /static/ { root /var/html/; } location /media/ { root /var/html/; } location /redoc/ { root /var/html; try_files $uri $uri/redoc.html; } location / { proxy_pass http://web:8000; } } docker-compose.yaml: services: db: image: postgres:12.4 volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env web: image: restart: always volumes: - static_value:/code/static/ - media_value:/code/media/ depends_on: - db env_file: - ./.env nginx: image: nginx:1.19.3 ports: - "80:80" volumes: - ./nginx/default.conf:/etc/nginx/conf.d/default.conf - static_value:/var/html/static/ - media_value:/var/html/media/ - .static/redoc.yaml:/var/html/redoc/redoc.yaml - .templates/redoc.html:/var/html/redoc/redoc.html depends_on: - web volumes: postgres_data: static_value: media_value: Could you, please, advice what is wrong is set up ? -
How to display querysets in Django?
I write a functiın and the final, function creates several model objects (same model different values). I listed these objects but I want to list just one time with the same dashboard_id value. I found something about that but I have an issue with displaying in the table. It is working but does not display the values. How can I solve it? views.py def reports_list(request): report_list = Reports.objects.values_list('dashboard_id', flat=True).distinct() context = { 'report_list': report_list, } return render(request, "report_list.html", context) report_list.html <table id="table_id" class="display"> <thead> <tr> <th>Kullanıcı</th> <th>Yüklenme Tarihi</th> <th>Görüntüle</th> </tr> </thead> <tbody> {% for report in report_list %} <tr> <td>{{ report.user.first_name }} {{ report.user.last_name }}</td> <td>{{ report.created_at }}</td> <td>view</td> </tr> {% endfor %} </tbody> </table> to be clear: -
Use GCC and java in Heroku dyno
I am trying to build a code compiler using Python Djano. The code works in my local machine as I use subprocess to compile and then run codes like python,java,c/c++. But when I upload it on Heroku which has a python build pack, it fails to run java and c/cpp codes because somehow it cannot access gcc and java [probably they are unavailable]. Hence how do I use java and cpp while retaining python too and run and execute the codes that are inputted from the front end. -
Django select_related() with latest() limit on related object
Consider having Table table and Reservation table in my restaurant Django APP. class Reservation(models.Model): table = models.ForeignKey( Table, on_delete=models.CASCADE, blank=False,null=False, related_name='reservations' ) def __str__(self): return str(self.pk) class Table(models.Model): def __str__(self): return str(self.pk) If I wanna to show a list of restaurant tables with it's corresponding reservation, then I need to select related reservation for each table. but I need to select related only the last reservation of each table (that is active right now). How To Achieve that? -
Django file upload with model form
there are tons of relevant posts: https://docs.djangoproject.com/en/3.2/topics/http/file-uploads/ Uploading A file in django with ModelForms https://github.com/axelpale/minimal-django-file-upload-example I am creating a simple app that allow user to upload css file: First, validate field field to make sure the file is css and the max size does not exceed 5MB. fields.py from django.db import models from django import forms from django.template.defaultfilters import filesizeformat def mb(n): return n * 1048576 class FileField(models.FileField): def __init__(self, *args, **kwargs): self.content_types = kwargs.pop('content_types', []) self.max_upload_size = kwargs.pop('max_upload_size', []) super().__init__(*args, **kwargs) def clean(self, *args, **kwargs): data = super().clean(*args, **kwargs) file = data.file try: content_type = file.content_type if content_type in self.content_types: if file.size > self.max_upload_size: raise forms.ValidationError('Please keep filesize under {}. Current filesize {}' .format(filesizeformat(self.max_upload_size), filesizeformat(file.size))) else: raise forms.ValidationError('File type rejected') except AttributeError: pass return data second, implement validation into model models.py # Create your models here. class Css(models.Model): file = FileField(upload_to='css', blank=True, null=True, content_types=['text/css'], max_upload_size=mb(5), ) third, create form for model creation forms.py class CssCreateForm(forms.ModelForm): class Meta: model = Css fields = ['file'] last, write a callable view views.py # Create your views here. def cssUploadView(request): if request.method == 'POST': print(request.POST['file']) print(type(request.POST['file'])) print(request.FILES) form = forms.CssCreateForm(request.POST, request.FILES) if form.is_valid(): print('---------') print(form.cleaned_data['file']) else: print('not valid') else: form = forms.CssCreateForm() return … -
How can I resolve fts5 error after I upgraded Wagtail
I have upgraded my Wagtail installation to 2.15.1 with Django 3.1.13 When I run manage.py migrate I get an error django.db.utils.OperationalError: no such module: fts5 I have searched but cannot find any solutions to this problem Can someone please help? -
|as_crispy_field got passed an invalid or inexistent field django?
views.py def VendorEdit(request, id=0): if request.method == "GET": vendor = CustomUser.objects.get(pk=id) print(vendor) form = VendorCreationForm(instance=vendor) vendordetails = VendorDetails.objects.filter(vendoruser_id=vendor.id) print(vendordetails) vendordetailform = VendorAdminDetailsForm(instance=vendordetails[0]) return render(request, 'vendor/edit.html', {'form':form, 'vendor':vendor, 'vendordetailform':vendordetailform}) else: vendor = CustomUser.objects.get(pk=id) form = VendorCreationForm(request.POST, instance=vendor) vendordetails = VendorDetails.objects.filter(vendoruser_id=vendor.id) vendordetailform = VendorAdminDetailsForm(request.POST, request.FILES, instance=vendordetails[0]) if form.is_valid() and vendordetailform.is_valid(): vendor=form.save() # vendordetailform.instance.vendoruser = vendor vendordetailform.save() # vendor.is_active = False # vendor.save() return redirect('login') edit.html <form method="POST" action="{% url 'vendor_edit' vendor.id %}" enctype='multipart/form-data'> {% csrf_token %} {{ vendorform.email|as_crispy_field}} {{ vendorform.first_name|as_crispy_field}} {{ vendorform.last_name|as_crispy_field}} {{ vendorform.mobile_number|as_crispy_field}} {{ vendorform.password1|as_crispy_field}} {{ vendorform.password2|as_crispy_field}} {{ vendordetailform.type_of_vendor|as_crispy_field}} {{ vendordetailform.aadhar_number|as_crispy_field}} {{ vendordetailform.aadhar_image|as_crispy_field}} {{ vendordetailform.pan_number|as_crispy_field}} {{ vendordetailform.pan_image|as_crispy_field}} {{ vendordetailform.store_name|as_crispy_field}} {{ vendordetailform.brand_name|as_crispy_field}} {{ vendordetailform.mail_id|as_crispy_field}} {{ vendordetailform.contact_no|as_crispy_field}} {{ vendordetailform.gst_number|as_crispy_field}} {{ vendordetailform.attach_gst_cert|as_crispy_field}} {{ vendordetailform.acct_number|as_crispy_field}} {{ vendordetailform.attach_passbook|as_crispy_field}} {{ vendordetailform.ifsc_code|as_crispy_field}} {{ vendordetailform.insta_account|as_crispy_field}} {{ vendordetailform.website|as_crispy_field}} {{ vendordetailform.street_name|as_crispy_field}} {{ vendordetailform.city|as_crispy_field}} {{ vendordetailform.pincode|as_crispy_field}} <button type="submit" class="btn btn-dark" value="Submit">Preview</button>&ensp; <a href="{% url 'login' %}">Already a Vendor?</a> </form><br> after the user signup, I allow them to preview and edit their details once they edit their details and preview, then click submit. It will redirect to login. The edit option is not working and after the preview submit not redirect to login the user. please need help. -
Django is using old views.py
So when running my project the homepage is good and the signup and in. However, some things don't work. I found errors where have things from old views.py. So I am thinking that Django is using a vies.py folder for other projects. views.py class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, DeleteView): model = Posts success_message = 'Your post has been deleted' #it is not working and I dont know why success_url = reverse_lazy('homepage') template_name = 'posts/delete.html' def test_func(self): post = self.get_object() if self.request.user == post.user: return True return False urls.py from django.urls import path from django.conf import settings from django.conf.urls.static import static from .views import PostsListView, PostCreatView, PostDeleteView urlpatterns = [ path('', PostsListView.as_view(), name='homepage'), path('delete/<int:pk>/', PostDeleteView.as_view(), name='delete-post'), path('creat-post', PostCreatView.as_view(), name='create-post') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) delete.html {% extends "posts/base.html" %} {% block content %} <form method="POST"> {% csrf_token %} <h2> Are you sure you want to delete your post?</h2> <button class="btn btn-outline-danger mt-1 mb-1 mr-1 ml-1" type="submit">Yes Delete</button> <a class="btn btn-outline-secondary mt-1 mb-1 mr-1 ml-1" href="{% url 'post-and-comments' object.id %}">Cancel</a> </div> </form> {% endblock %} list.html {% extends "posts/base.html" %} {% block content %} {% for post in posts %} <p class="font-weight-bold">{{post.user.username}}</p> {% if user == post.user %} <div> <a href="{% url 'delete-post' post.pk …