Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django add dynamic fields to front end and then insert it to Model
I have a Model which consists of almost 500+ fields. I want to take data through the front end Form. But the issue is I can't display all the 500 fields. I will add the fields which I need. like on day-1 I will add 3 fields. food = 230 , petrol = 500, rent = 700. on the second day, fields may vary. I can add 20 fields on the second day. All these fields are pre-defined in the model. how should I create these fields dynamically in the front end and then how I will pass it to view function and how I will store it in the Model. enter image description here -
Django REST framework TokenAuthentication returns anonymous user
How do I properly implement DRF TokenAuthentication without the request object returning an anonymous user when I try to log in? according to the docs, when authenticated, the TokenAuthentication object provides the request.user which is the Django user instance and the request.auth which is the token instance. But even after authentication, request.user returns anonymouse user. What could I be doing wrong? Client request: //function to get token export default function axiosConfig() { // request header const headers = { "Content-Type": "application/json" } // Get token from local storage. Token is stored when user registers. const token = localStorage.getItem("token"); if (token) headers["Authorisation"] = `Token ${token}`; return headers; } Redux action import axiosConfig from "../../utils/axiosConfig"; const config = axiosConfig export const login = (email, password) => (dispatch, getState) => { const body = { email, password }; // Change to absoulte path when deploying to production axios .post("http://localhost:8000/api/auth/login", body, config()) .then((res) => { dispatch({ type: SIGN_IN_SUCCESFUL, payload: res.data, }); console.log(res); }) .catch((err) => { dispatch({ type: SIGN_IN_FAIL, payload: err.response, }); console.log(err.response.data, err.response.status); }); }; Django url: from django.urls import path from authentication.views import RegisterationView from authentication.views import LoginView from authentication.views import LogoutView urlpatterns = [ path("auth/register", RegisterationView.as_view()), path("auth/login", LoginView.as_view()), path("auth/logout/<int:id>", LogoutView.as_view()), ] … -
Django how to write queryset for get all admin user and use them in signals as receiver
My purpose of using django signals is notify every admin when any author create new blog post. So I want to use all admin as a receiver and the only author who creating the blog post will be sender. currently I am using this User.objects.get(username='jhone' )#jhone is an admin user queryset for set receiver specific admin user. How to call all admin user and make theme all as receiver. here is my code: #models.py #using notifications model for signals class Notifications(models.Model): blog = models.ForeignKey('blog.Blog',on_delete=models.CASCADE) blogcomment = models.ForeignKey('blog.BlogComment',on_delete=models.CASCADE, blank=True,null=True) NOTIFICATION_TYPES = (('New Comment','New Comment'),('Comment Approved','Comment Approved'), ('Comment Rejected','Comment Rejected'),('pending post','pending post'),('post approved','post approved'),('post rejected','post rejected')) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_from_user") receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_to_user") #others fields...... class Blog(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE,max_length=100) #others fields.... def blog_notify(sender, instance, *args, **kwargs): blog = instance blog_title = blog.title sender = blog.author receiver = User.objects.get(username='jhone') if sender == blog.author and blog.is_published == "published": notify = Notifications(blog=blog, sender=sender,receiver =receiver ,text_preview = blog_title[:250], notification_type="post approved") notify.save() post_save.connect(Blog.blog_notify, sender=Blog) I also tried few queryset for set all admin user as receiver but non of theme didn't work. receiver = User.objects.all().filter(is_superuser=True) I am getting this error Cannot assign "<QuerySet [<User: Jhone>, <User: admin1>, <User: admin2>]>": "Notifications.user" must be a … -
Could not parse the remainder: '[cat_id]' from 'menu[cat_id]'
I am new to django and jinja template. I am getting below error: Could not parse the remainder: '[cat_id]' from 'menu[cat_id]' I am trying to create dynamic tabs in my header for product categories, below is my code where error is happening: {% for cat_id in menu %} <span class="navbar-item {% if 'sub_cat' in menu[cat_id] %} has-dropdown is-hoverable{% endif %}" style="{% if 'sub_cat' in menu[cat_id] %}align-items:center{% endif %}" > menu is the dictionary and below is the sample structure for the same: menu = { 1: { 'category': 'Jewellery', 'slug': 'abc', 'sub_cat': { 3: { 'category': 'Earrings', 'slug': 'def' } } }, 2: { 'category': 'Apparel', 'slug': 'ghi' } } I am using python version 3.8, I tried degrading it to 3.7 as well, but error is still coming. I am not sure if changing python version helps or not. Thanks in advance -
How to Remove the #Hash from the URL when redirect with django in view
i am using redirect method like the following: def f_login(request): if request.user.is_authenticated: return redirect('home') but i note the #login html hash id (which i used in my html url link) still forwarded to the new redirected link , as the following: http://127.0.0.1:8000/dashboard/#login is there any way to remove the #login hash id in my view function ? thanks -
TemplateDoesNotExist when displaying a template from another application in a Django project
I have a website with two applications dos_website, which contains the home and main pages, and the blog, which contains the news: ubu@DESKTOP-QL4RO3V:/mnt/c/Users/antoi/Documents/Programming/Work/Dos/webapp$ tree -L 1 . ├── README.md ├── __init__.py ├── blog/ ├── db.sqlite3 ├── dos_website/ ├── firstrecord.json ├── firstrecord.txt ├── manage.py ├── requirements.txt └── website/ 3 directories, 7 files I would like to access the blog page of my website whose address is supposed to be http://127.0.0.1:8000/blog/: webapp/dos_website/templates/dos_website/base.html <head> <meta charset="utf-8"> </head> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top"> <div class="container"> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li> <a role="button" href="{% url 'blog:all_blogs' %}" class="btn btn-primary">Actualités</a> </li> </ul> </div> </div> </nav> </html> The redirection is first handled by the urls.py file of the web application that manages this page: webapp/website/urls.py from django.contrib import admin from django.urls import path, include from dos_website import views from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), # Home path('', views.home, name='home'), # blog path('blog/', include('blog.urls')), ] And therefore it is redirected to the urls.py file of the blog application: webapp/blog/urls.py from django.contrib import admin from django.urls import path, include from . import views app_name = 'blog' urlpatterns = [ path('', views.all_blogs, name='all_blogs'), ] Here is … -
Models don't show up in the django admin
My model does not show up in the Django admin. I don't understand this. I have been doing this several times before: from django.contrib import admin from djntra.models import Thing class ThingAdmin(admin.ModelAdmin): pass admin.register(Thing, ThingAdmin) I have no clue what's going on. -
Django dictionary update sequence element #0 has length 0; 2 is required
after passing this line of code in my context processor I am getting above error 'notifications.views.Count_Notifications I am facing this problems for unauthenticated user. I am passing context in context processor for showing few user info in my base.html navbar such as number of notifications, user name etc. here is my code: views.py @login_required def Count_Notifications(request): count_notifications_comment = 0 count_notifications_author = 0 blog_author = Blog.objects.filter(author=request.user) if request.user.is_authenticated: count_notifications_comment = Notifications.objects.filter(sender=request.user,is_seen=False).count() count_notifications_author = Notifications.objects.filter(user=request.user,is_seen_author_noti=False).count() return {'count_notifications_comment':count_notifications_comment,'count_notifications_author':count_notifications_author,'blog_author':blog_author} settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'notifications.views.Count_Notifications' ], }, }, ] console error updates.update(processor(self.request)) ValueError: dictionary update sequence element #0 has length 0; 2 is required [18/Jul/2021 01:03:04] "GET / HTTP/1.1" 500 99622 -
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.