Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Open port 587 (firewall rule) on Ubuntu 20.04 to send email
Introduction I got a Digital Ocean droplet with Ubuntu 20.04 installed on which I run a Django application. This application is trying to send emails through port 587 with TLS enabled. However, when it tries to send an email it returns the following error: self.connection = self.connection_class(self.host, self.port, **connection_params) File "/usr/lib/python3.8/smtplib.py", line 1043, in __init__ SMTP.__init__(self, host, port, local_hostname, timeout, File "/usr/lib/python3.8/smtplib.py", line 255, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python3.8/smtplib.py", line 339, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python3.8/smtplib.py", line 1049, in _get_socket new_socket = socket.create_connection((host, port), timeout, File "/usr/lib/python3.8/socket.py", line 808, in create_connection raise err File "/usr/lib/python3.8/socket.py", line 796, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused Nmap Network Scanning nmap -p 25,465,587 droplet_ip Starting Nmap 7.91 ( https://nmap.org ) at 2021-07-17 20:43 CEST Nmap scan report for digital_ocean_droplet (droplet_ip) Host is up (0.00010s latency). PORT STATE SERVICE 25/tcp closed smtp 465/tcp closed smtps 587/tcp closed submission Nmap done: 1 IP address (1 host up) scanned in 0.17 seconds UFW Rules sudo ufw status verbose Status: active Logging: on (low) Default: deny (incoming), allow (outgoing), disabled (routed) New profiles: skip To Action From -- ------ ---- 22/tcp (OpenSSH) ALLOW IN Anywhere 80,443/tcp (Nginx Full) … -
how to correctly saving a profile instance in django
I have a problem with creating a profile instance in Django. when I try to update a profile the images of the profile don't save in the database My guess is that the form.save(commit=False) does not upload the photo nor update the field as it should but I do not understand why : here is my code: models.py class Profile(models.Model): user = models.OneToOneField(User, primary_key =True, on_delete=models.CASCADE, related_name= 'profile') image = models.OneToOneField(UserImage, on_delete=models.SET_NULL, null=True, blank=True) phone_number = models.CharField(max_length=50, null = True, blank = True) followers = models.ManyToManyField(User, related_name='follower', blank=True) following = models.ManyToManyField(User, related_name='following', blank=True) biography = models.TextField(max_length=250, null=True, blank=True) class UserImage(models.Model): avatar = models.ImageField(blank=True, null=True,upload_to='avatar_pic') header_image = models.ImageField(blank=True, null=True,upload_to='header_pic') forms.py class ProfileForm(ModelForm): class Meta: model = Profile fields = ( 'phone_number', 'biography', ) class ImageProfileForm(ModelForm): class Meta: model = UserImage fields = ( 'avatar', 'header_image', ) views.py @login_required def CompleteSignUp(request): if request.method == 'POST': profile_form = ProfileForm(request.POST,request.FILES ,instance=request.user.profile) image_profile_form = ImageProfileForm(request.POST, instance=request.user.profile.image) if profile_form.is_valid() and image_profile_form.is_valid(): profile = profile_form.save(commit=False) images = image_profile_form.save() profile.user = request.user profile.social = social profile.image = images profile_form.save() return redirect('blog:Home') else: profile_form = ProfileForm( initial={ 'phone_number':request.user.profile.phone_number, 'biography':request.user.profile.biography } ) if request.user.profile.image: image_profile_form = ImageProfileForm( initial={ 'avatar':request.user.profile.image.avatar, 'header_image':request.user.profile.image.header_image } ) else: image_profile_form = ImageProfileForm() return render(request, 'user/createprofile.html', {'form_p': … -
Getting an object rather than the desired attribute in DJango
I am trying to append ids of objects from a particular model into a list but am unable to do so: Error: Field 'unq_id' expected a number but got <main: main object (8)>. Views.py: def experts(request): if 'post' in request.session: del request.session['post'] print("del") cat = categories.objects.all() list2 = [] testlist = [] testlist2= [] listforexpid = [] exp = Expert.objects.all() for objects in exp: testlist.append(objects.unq_id) listforexpid.append(objects.e_id) print(objects.e_id) for obj in testlist: a = main.objects.get(unq_id = obj) testlist2.append(a.first_name) for x in exp: list2.append(x.image.url) for obj in exp: exp_name = main.objects.values_list('first_name') unq_id = main.objects.values_list('unq_id') c = zip(list2,testlist2,listforexpid) return render(request, 'Main/experts.html', {'exp':exp, 'list2':list2, 'c':c, 'cat':cat}) Line on which i am getting error: a = main.objects.get(unq_id = obj) Models.py: class main(models.Model): unq_id = models.BigAutoField(primary_key=True) email = models.CharField(max_length=80) password = models.CharField(max_length=256) first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) dob = models.CharField(max_length=80) phone = models.BigIntegerField(default=0) status = models.CharField(max_length = 12, default = 'active') def verify_password(self, raw_password): return pbkdf2_sha256.verify(raw_password, self.password) class Expert(models.Model): unq_id = models.OneToOneField(main, on_delete=models.CASCADE, primary_key = True) cat = models.CharField(max_length=500) aop = models.CharField(max_length=500) exp = models.CharField(max_length=500) firm = models.CharField(max_length=500) Loc = models.CharField(max_length=500) qualification = models.CharField(max_length=500,default='None') qualification1 = models.CharField(max_length=500,default='None') qualification2 = models.CharField(max_length=500,default='None') image = ResizedImageField(default = None,upload_to= 'expert/images',size=[100, 100], quality = 100) e_id = models.BigIntegerField() The thing … -
python/django errors runserver
python manage.py runserver python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\threading.py", line 950, in _bootstrap_inner self.run() File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "C:\Users\Admin\Desktop\python\intourist\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Admin\Desktop\python\intourist\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Admin\Desktop\python\intourist\venv\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Admin\Desktop\python\intourist\venv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Admin\Desktop\python\intourist\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Admin\Desktop\python\intourist\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Admin\Desktop\python\intourist\venv\lib\site-packages\django\urls\resolvers.py", line 413, in check messages.extend(check_resolver(pattern)) File "C:\Users\Admin\Desktop\python\intourist\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Admin\Desktop\python\intourist\venv\lib\site-packages\django\urls\resolvers.py", line 413, in check messages.extend(check_resolver(pattern)) File "C:\Users\Admin\Desktop\python\intourist\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Admin\Desktop\python\intourist\venv\lib\site-packages\django\urls\resolvers.py", line 339, in check warnings = self._check_pattern_name() File "C:\Users\Admin\Desktop\python\intourist\venv\lib\site-packages\django\urls\resolvers.py", line 347, in _check_pattern_name if self.pattern.name is not None and ":" in self.pattern.name: TypeError: argument of type 'function' is not iterable -
Pull out all feild data on a single model object
I'm trying to load user info into a profile page template. How would I get all the feild data for a single user? How could I extract all the data on Users.objects.get(pk=13)? It just shows that I have the object but I need to expand it to get the name, bio, profile pic ect so I can display it. -
what is the difference between os.environ.setdefault() vs os.environ.putenv()
Both are supposed to set environmental variables >>> help(os.environ.putenv) putenv(name, value, /) Change or add an environment variable Be supposed to `os.environ.putenv`` add an environment variable, Why doesn't this work In the manage.py file. -
How to validate a token in Django Knox Authentication
I am using knox authentication to login user after validating otp using the view below class LoginPhoneApi(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self,request,formt=None): serializer = LoginwithPhoneSerializer(data = request.data) serializer.is_valid(raise_exception = True) user = serializer.validated_data['user'] login(request,user,backend='django.contrib.auth.backends.ModelBackend') userid = user.id username = user.username fullname= user.full_name temp_list=super().post(request, format=None) temp_list.data["userid"]=userid temp_list.data["username"]=username temp_list.data["fullname"]=fullname print(temp_list.data["token"]) return Response({"data":temp_list.data}) I am able to login and get the authentication token. Now one of my view requires authenticated users. How do I validate this token which is in the header of the url request. I am able to fetch the token. How do I use this token to validate and login the user. def dispatch(self, request, *args, **kwargs): self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name']) auth_method, token = self.request.META['HTTP_AUTHORIZATION'].split(' ', 1) Please let me know if you need more information. -
How to create views.py for multiple models including many-to-many
I'm new to Python and DjangoRestFramework. I am trying to create an image upload system with image-tagging. "Tags" have a many-to-many relationship with "Images". The forms are in the React.js in the front-end. I am trying to understand how to write a view for this. I have not seen a clear solution to this online. here is upload/models.py from django.db import models from django.db.models.fields import UUIDField from django.contrib.postgres.functions import RandomUUID def upload_path(instance, filename): return '/'.join(['images', str(instance.contributor), str(instance.caption), str(instance.date_created), filename]) class Image(models.Model): image = models.ImageField(upload_to=upload_path) contributor = models.ForeignKey( 'accounts.User', related_name='+', on_delete=models.CASCADE, default='user0') caption = models.CharField(max_length=100) date_created = models.DateTimeField(auto_now_add=True, null=True) id = UUIDField(primary_key=True, default=RandomUUID, editable=False) theme = models.CharField(max_length=10) class Tags(models.Model): tag = models.ManyToManyField(Image, through='Junction') class Junction(models.Model): image = models.ForeignKey(Image, on_delete=models.CASCADE) tags = models.ForeignKey(Tags, on_delete=models.CASCADE) Here are two possible solutions for the upload/views.py: from django.shortcuts import render from django.http import HttpResponse from rest_framework import viewsets from .serializers import JunctionSerializer from .models import Image, Tags, Junction #SOLUTION_1: class JunctionView(viewsets.ModelViewSet): serializer_class = JunctionSerializer query_set = Junction.objects.all() def get_context_data(self, request, *args, **kwargs): image = request.data['cover'] tags = request.data['tags'] Junction.objects.create(image=image, tags=tags) return HttpResponse({'message': 'Successful Upload'}, status=200) #SOLUTION_2 class JunctionView(): ???? def get_context_data(self, **kwargs): context = super(JunctionView, self).get_context_data(**kwargs) context['image'] = Image.objects.all() context['tags'] = Tags.objects.all() return context Is it … -
Efficiently bulk updating many ManyToMany fields
A version of this question has been asked here several times but none of the answers provided solve my exact problem. I'm trying to bulk_create a batch of objects of a model with a ManyToMany field. In this case, the ManyToMany field refers to the same model, though I'd also be interested in the general case. Let's say this is my model: class Person(models.Model): name = models.CharField(max_length=20, blank=True, null=True) friends = models.ManyToMany("self", related_name="friends_with", null=True) After bulk_creating a large number of Person objects, I want to add the information who's friends with whom within this group. Is there a more efficient way to go about this than looping through each new Person and calling .set(friend_pks) or .add(*friend_pks)? I.e., an analogue of bulk_update. I've achieved some speed-up by wrapping the loop into with transaction.atomic() (from this answer) but it's still quite slow. -
Failed to load resource: the server responded with a status of 404 (Not Found) my plugins and jQuery
I am trying to run this on a Django server and getting an error stating it failed to load resources of my plugins and jQuery. I would appreciate any help as I am a newbie. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" type="image/png" href="images/favicon-32x32.png" sizes="32x32" /> <link rel="icon" type="image/png" href="images/favicon-16x16.png" sizes="16x16" /> <title>Travel</title> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,900" rel="stylesheet"> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="styles/styles.css" rel="stylesheet" type="text/css"> <link href="styles/custom-responsive-styles.css" rel="stylesheet" type="text/css"> <script type="text/javascript" src="scripts/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="scripts/all-plugins.js"></script> <script type="text/javascript" src="scripts/plugins-activate.js"></script> </head> -
How is it possible to get data from one form that has multiple textareas in Django
I'd like to get data from one form that has multiple textareas inside , In my views: 'compare_ingredients' I've tried requesting data from my form id 'compareform' also the textarea id 'ingredients', but when I enter something into one texture and click on submit it comes back as 'None' when I print. Here is my html and views: html : <div class="container-fluid"> <h4>Please enter in your ingredients:</h4> <h6>(Seperate each item by comma)</h6> <br> <button class="add_item">Add Item</button> <br> <div class="row row-cols-1 row-cols-md-2 mx-auto"> <form action="{% url 'compare_ingredients' %}" method="POST" name="compareform" id="compare"> {% csrf_token %} <br> <button type="submit" class="btn btn-info sub_btn">Submit</button> <button type="submit" class="btn btn-secondary back_button"> <a href="{% url 'home' %}" class="back_button_text">Back</a> </button> <br> <br> <div class="row form_row"> <div class="col mb-4"> <h5>Item 1</h5> <div class="card form_card"> <div class="card-body compare_cardbody"> <textarea name="ingredients1" id="ingredients" cols="30" rows="10" form="compareform"></textarea> </div> </div> </div> <div class="col mb-4"> <h5>Item 2</h5> <div class="card form_card"> <div class="card-body compare_cardbody"> <textarea name="ingredients2" id="ingredients" cols="30" rows="10" form="compareform"></textarea> </div> </div> </div> </div> </form> </div> </div> views.py: def compare_ingredients(request): if request.method == "POST": ingredients = request.POST.get('compareform') print(ingredients) return render(request, 'result/compare.html') -
Django for template language not working/ rendering any data
I have been working on Django for 2 months now. Before I have retrieved data from the database to the template inside the affiliation app. Now I am trying to render data to another app from views, but the data are not rendered and as well the for loop in the django template doesnot display any data. I am feeling the code may be right, but i am not knowing where i am being mistaken. Below are details: Views- from affiliation.models import AffProduct def Sproducts(request): if request.user.is_authenticated: current_user = request.user # define current user resulted = AffProduct.objects.all() return render(request, 'onlineshopping.html', { 'object': resulted }) Urls- path('/', views.onlineshopping, name='onlineshopping'), path('onlineshopping/', views.Sproducts) HTML- {% for object in resulted %} <h1>Product Title:{{ object.product_title }}</h1> <p>Product ID:{{ object.uid }}</p> <p>Specification:{{ object.specification }}</p> <p>Terms & Condition:{{ object.terms_conditions }}</p> <p>Sale Price:Rs.{{ object.sale_price }}</p> <p>Discount:{{ object.discount }}%</p> {% endfor %} Directory- -myblink(Project) -affiliation(app1) -models.py #Model is saved here 'AffProduct' -onlineshopping(app2) -views.py #Want to render the details from here to the template -
I have a mistake like this "AttributeError at /uz/account/update/ 'str' object has no attribute '_meta' "
the above error occurs when you click the save button,but in the docs I think I am putting in the correct parameters. Where that bit of code is in my views.py: class AllUserUpdate(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): alluser = CustomUser.objects.get(username=self.request.user.username) form = CustomUserForm(instance=alluser) context = {'form':form} return render(request, 'account/AllUserAccount.html', context) def post(self, request, *args, **kwargs): form = CustomUserForm(self.request.POST, self.request.FILES, instance=self.request.user.username) if form.is_valid(): form.save() messages.info(self.request, "Your are change successfully created!") context = {'form': form} return redirect('all_user_update') This is what my template looks like: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <h3>Full name: {{ request.user.full_name }}</h3> {{ form.as_p }} <input type="submit" class=" btn btn-primary" value="Save"> </form> forms.py: class CustomUserForm(UserCreationForm): password1 = forms.CharField(widget=forms.PasswordInput( attrs={'class': 'form-control mt-2', 'name': 'password1', 'placeholder': 'enter the password...'})) password2 = forms.CharField(widget=forms.PasswordInput( attrs={'class': 'form-control mt-2', 'name': 'password2', 'placeholder': 'Repeat the password...'})) class Meta: model = CustomUser fields = ('full_name', 'email', 'user_type', 'phone', 'password1', 'password2', 'username') widgets = { 'full_name': forms.TextInput(attrs={'class': 'form-control mt-2', 'name': 'full_name'}), 'username': forms.TextInput(attrs={'class': 'form-control mt-2', 'name': 'username'}), 'email': forms.EmailInput(attrs={'class': 'form-control mt-2', 'name': 'email'}), 'phone': forms.TextInput(attrs={'class': 'form-control mt-2', 'name': 'phone'}), 'user_type': forms.Select(attrs={'class': 'form-control mt-2', 'name': 'user_type'}), } enter image description here i want users to change their personal pages -
Is there a way to add differential privacy mechanism as a third parties in a dataset?
i'm a final year students of informatics, I'm currently working on my final project with topic differential privacy. the ideas of the system that i want to make is creating a simple web which the function is only to query data from database, then there'll gonna be a checklist button to turn on differential privacy method. So if i checked on it, the system will query the data with differential privacy method (i'll be using exponential mechanism) then if i don't the system will directly query the data without differential privacy method. The web framework that i'll be using is django. The point is i only need to implement the mechanism, then compare it, then do a simple testing, then make the analysis of it. i will not analyze the algorithm & it's formula specifically. Only limited to the analysis of the implementation that has been done. I'm new to this and i'm not really good with coding. so i really need any of your help as soon as possible, how to implement this differential privacy method. i'd be so thankful for your help. -
Error when changing from Sqlite3 into Postgresql in Django, with annotation and pagination
I'm learning Django and used Sqlite3 for my site until today, I changed the database into Postgres. My site kind of mimics Facebook. I have a ListView that will list all posts. In get_queryset(), I annotate each post with some additional info, such as number of likes and dislikes, number of comments, have current logged in user followed the owner of the post. I also paginated the result so that my site only displays 5 post per page. Here is my code: class PostListView(FormMixin, ListView): model = Post paginate_by = 5 template_name = "network/newsfeed.jinja" body_title = "All Posts" context_object_name = "posts" form_class = PostCreateForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.get_form() context['body_title'] = self.body_title return context def get_queryset(self): queryset = Post.objects.select_related('owner').annotate( comment_count=Count('comments', distinct=True), like_count=Count( Case( When(likes__is_like=True, then=Value(1)), output_field=IntegerField ), distinct=True ), dislike_count=Count( Case( When(likes__is_like=False, then=Value(1)), output_field=IntegerField ), distinct=True ), ).order_by('-created_time') # improve: do we need query all? if self.request.user.is_authenticated: return queryset.annotate( follow_already=Exists( Follow.objects.filter(followed=OuterRef('owner'), follower=self.request.user) ), like_already=Exists( Like.objects.filter(owner=self.request.user, post_parent=OuterRef('pk'), is_like=True) ), dislike_already=Exists( Like.objects.filter(owner=self.request.user, post_parent=OuterRef('pk'), is_like=False) ) ) return queryset.annotate( follow_already=Value(False, output_field=BooleanField()), like_already=Value(False, output_field=BooleanField()) ) My site was OK with Sqlite3. But I get an error when changing into Postgres, that occurs on line 17 in get_internal_type() (see the picture), … -
signals and tasks file are not connecting in django celery
I am using Django signals to trigger a task (sending mass emails to subscribers using Django celery package)when an admin post a blogpost is created from Django admin. The signal is triggered but the task function in the task file is not called. It's because I put a print function which is not printing inside the task function. My signlas.py file: from apps.blogs.celery_files.tasks import send_mails from apps.blogs.models import BlogPost,Subscribers from django.db.models.signals import post_save from django.dispatch import receiver def email_task(sender, instance, created, **kwargs): if created: print("@signals.py") send_mails.delay(5) post_save.connect(email_task, sender=BlogPost,dispatch_uid="email_task") My task.py file from __future__ import absolute_import, unicode_literals from celery import shared_task # from celery.decorators import task from apps.blogs.models import BlogPost,Subscribers from django.core.mail import send_mail from travel_crm.settings import EMAIL_HOST_USER from time import sleep @shared_task def send_mails(duration,*args, **kwargs): print("@send_mails.py") subscribers = Subscribers.objects.all() blog = BlogPost.objects.latest('date_created') for abc in subscribers: sleep(duration) print("i am inside loop") emailad = abc.email send_mail('New Blog Post ', f" Checkout our new blog with title {blog.title} ", EMAIL_HOST_USER, [emailad], fail_silently=False) Here. the print("@send_mails.py") is not executed but print("@signals.py") in signals.py file is executed. Hence, signals is received after the Blogpost model object is created but the function inside task.py which is send_mails is not executed. I have installed both celery … -
Which Python Framework to use for my upcoming project?
I am currently working as a web developer. My current project is about developing a visualization tool for monitoring heart rate and accelerometer data of traumatic patients. Currently I am using Flask and SQLAlchemy for this project. I will start working on another project of an online educational web portal for patients suffering from epilepsy. I am thinking of using Django and MySql to develop the portal. The reason for that is to learn a new technology and understand the difference. Is choosing a new technology a good idea or should I stick to using Flask framework? All other projects in my lab are done using Flask SQLAlchemy. -
Get model field name from ImageField upload_to Django
I have several images in a model that need filenames assigning using ImageField( upload_to=image_upload). Each image field is assigned a number image_1, image_2, image_3 etc. What I need to know is how I can access the field name that is calling the image_upload function, so that I can use its image number? class FileTest(models.Model): def image_upload(self, filename): field = self.name # something like this, but it doesn't work?? return f"image-{field[-1]}.jpg" image_1 = models.ImageField(upload_to=image_upload, storage=OverwriteStorage()) image_2 = models.ImageField(upload_to=image_upload, storage=OverwriteStorage()) image_3 = models.ImageField(upload_to=image_upload, storage=OverwriteStorage()) -
Django: How can I take the choice in drop-down list and redirect to another page?
I'm currently just learning Django and I'm doing electronic grade book. I have tried everything, have read all the documentation, but nothing helps. It seems I miss a simple logic somewhere. I need to make two pages: The first one "teacher_interface" is a simple inteface for the teacher with just one drop-down list, teacher chooses the necessary class (i.e 1C, 2B, 4C) and the button "Students", which should somehow take the chosen class from drop-down list input and redirect to the second page "class_students". The second "class_students" is alike the "teacher_interface", but with the table of students of the chosen class. I have the One-to-many relation between classes Student and Class: Firstly, I tried redirecting from "teacher_interface" to "class_students", using in template: {% url "name" %} Parts of code: 1) models.py https://dpaste.org/eqxm 2) urls.py https://dpaste.org/eUEO 3) views.py https://dpaste.org/ap8D#L 4) template teacher_interface.html https://dpaste.org/v4m9 5) template class_students.html https://dpaste.org/0gXK But it shows me: Reverse for 'class_students' with no arguments not found. 1 pattern(s) tried: ['school/teacher/(?P<class_id>[0-9]+)/class/$'] I tried everything, but nothing helped, this and the similar: Django - getting Error "Reverse for 'detail' with no arguments not found. 1 pattern(s) tried:" when using {% url "music:fav" %} I understood maybe this two options of … -
Django Form POST problem in a Bootstrap Modal
I'm searching for this issue for days... And, unfortunately, couldn't find the answer. I have a view (Buildings) and I want to add/edit a Building with a modal. With my current code, I can add new Building. However, because I can't pass the id (pk) of an existing Building, I can't update it. I've two views: one for the table, other for the form. I noticed that, when I POST, my Building view posts, not the newBuilding view. I tried to get pk from kwargs in newBuilding view, but I can't get it in the post method. The only thing left is to update.. Let me share my code. Thanks in advance! urls.py path('app/buildings/', login_required(views.Buildings.as_view()), name='buildings'), path('app/buildings/<int:pk>', login_required(views.NewBuilding.as_view()), name='buildings-pk'), models.py class Buildings(TemplateView): template_name = 'main_app/buildings.html' model = models.Building def get_context_data(self, **kwargs): context = super(Buildings, self).get_context_data(**kwargs) # Get selected site from cache active_site = models.Site.objects.filter(id=self.request.session.get('active_site')).get() context['active_site'] = active_site filtered_buildings = models.Building.objects context['buildings'] = filtered_buildings.all() return context def get_form_kwargs(self): kwargs = super(Buildings, self).get_form_kwargs() kwargs.update({'active_site': self.request.session.get('active_site'), 'edited_building_id': None}) return kwargs def post(self, request, *args, **kwargs): if request.method == 'POST': NewBuilding.post(self, request=request, slug=None) return HttpResponseRedirect(reverse_lazy('main_app:buildings')) else: print("error") ... class NewBuilding(FormView): template_name = 'main_app/new/new_building.html' form_class = forms.NewBuildingForm active_site = None def get_context_data(self, **kwargs): context = … -
Don't want confirm password field in add_fieldsets in django custom UserAdmin
django custom UserAdmin required password1 and password2 in add_fieldsets.I don't need that confirm password field.I already created register form and custom user model with one password field for registration.Now when I want to register from registration form password is not being hashed because of one password field but when I register user from admin dashboard with password1 and password2 is being hashed succesfully.How to solve it.Below is my admin.py code: from django import forms from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import Employee class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = Employee fields = ('email', 'date_of_birth',) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: model = Employee fields = ('name', 'email', 'password', 'date_of_birth', 'is_active') def clean_password(self): return self.initial["password"] class UserAdmin(BaseUserAdmin): form = UserChangeForm add_form = UserCreationForm list_display = ('name', 'email', 'date_of_birth','created_at','updated_at',) list_filter = () fieldsets = ( (None, {'fields': ('name', 'email', 'password')}), ('Personal info', {'fields': ('date_of_birth','gender','role',)}), ) … -
How to set different permissions depending on the request method?
I am creating an API for some polls. I need the author to be the only one who can view the votes, but the authenticated users to view the polls, questions, and to post votes. The author is just an instance of User, as like as the voters. I'm using Djoser to provide the authentication API, model serializers, and breaking my mind between CBVs and viewsets. Here are my models, if it can help. from django.db import models from django.contrib.auth import get_user_model from django.utils import timezone import datetime User = get_user_model() class Poll(models.Model): title = models.CharField(max_length=200, verbose_name="Naslov ankete") description = models.TextField(verbose_name="Opis ankete") author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="polls", verbose_name="Autor") class Meta: verbose_name = "Anketa" verbose_name_plural = "Ankete" def __str__(self): return self.title class Question(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE, related_name="questions", verbose_name="Anketa") question_text = models.CharField(max_length=200, verbose_name="Tekst pitanja") pub_date = models.DateTimeField(verbose_name="Datum objavljivanja") class Meta: ordering = ["pub_date", "question_text"] verbose_name = "Pitanje" verbose_name_plural = "Pitanja" def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now def verbose_question_text(self): return f"Pitanje: {self.question_text}" class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="choices", verbose_name="Pitanje") choice_text = models.CharField(max_length=200, verbose_name="Tekst opcije") # votes = models.IntegerField(default=0, verbose_name="Glasovi") class Meta: ordering = ["-votes", "pk"] verbose_name = "Opcija" verbose_name_plural = … -
Django - Display Image in Template from form ( ImageField ) without saving to Model
I have been struggling with this for a couple of days. I am trying to create an html page in which the user imports an image and resizes it ( all of this without saving anything to a model ). I want to do 3 main things: After the user selects his image, to have the image displayed even if the form has not been submittedand to display the current width and height of the image. To be able to access and modify those width and height values and to change the values. After "submit" has been sent, to have on the same page the transformed image and to be able to download. Also, I am a beginner, this being my first project. I would much appreciate if you can share some of your knowledge and leave me some tips :) forms.py class ImageForm(forms.Form): image = forms.ImageField() views.py def image_resize(request): form = forms.ImageForm() if request.method == "POST": form = forms.ImageForm(request.POST or None, request.FILES or None) if form.is_valid(): image_object = form.cleaned_data['image'] w, h = image_object.image.width, image_object.image.width print(w, h) else: form = forms.ImageForm(request.POST or None, request.FILES or None) context = {'form':form} return render(request, 'images/image-grayscale.html', context) Let me know if something else is … -
How can I use current object as variable
I'm a complete beginner at django and currently trying to create a library website. Users can issue books, and I want users who have done so, to see 2 extra buttons: unissue and extend. In my mind, this is what I want to be able to write: {% for b in Borrower %} {% if b.book == {{book}} %} {% if b.student == {{user}}%} #buttons {% endif %} {% endif %} {% endfor %} Obviously the error happens at {{book}} and {{user}} because it cannot parse the rest. I'm not sure what the correct syntax is to access current object and user being viewed. -
Django rest framework PUT method work with Postman but not Javascript FormData
Currently in a model, I defined a JsonField: bounding = models.JSONField(blank=True, null=True) The Postman request work well: But when I use XMLHttpRequest in Javascript: let data = new FormData(); data.append('bounding', JSON.stringify(myArray)); let xhttp = new XMLHttpRequest(); xhttp.open('PUT', '/image/', true); xhttp.send(data); The bounding field is always None. What can I do to fix this problem?