Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
zappa throwing errors after uploading to lambda
Hi I am new to zapper and aws I am getting errors when i use zappa to upload using zappa==0.48.2 python 3.6 Django==3.1.5 see error below [1626571209893] [DEBUG] 2021-07-18T01:20:09.893Z 42b0c70d-dd34-45a2-a844-xxxxxxxxxxyyyyy Zappa Event: {'time': '2021-07-18T01:19:33Z', 'detail-type': 'Scheduled Event', 'source': 'aws.events', 'account': '630589988206', 'region': 'us-west-2', 'detail': {}, 'version': '0', 'resources': ['arn:aws:events:us-west-2:630589988206:rule/appname-dev-zappa-keep-warm-handler.keep_warm_callback'], 'id': '97b022f9-7ece-b2a6-49a0-9b9aa33fbac0', 'kwargs': {}} [1626571209893] [DEBUG] 2021-07-18T01:20:09.893Z 42b0c70d-dd34-45a2-a844-xxxxxxxxxxyyyyy Zappa Event: {} [1626571450446] [DEBUG] 2021-07-18T01:24:10.446Z 66301a7e-0c98-40c1-a54a-5xxxxxxxxxx Zappa Event: {'time': '2021-07-18T01:23:33Z', 'detail-type': 'Scheduled Event', 'source': 'aws.events', 'account': '630589988206', 'region': 'us-west-2', 'detail': {}, 'version': '0', 'resources': ['arn:aws:events:us-west-2:630589988206:rule/appname-dev-zappa-keep-warm-handler.keep_warm_callback'], 'id': '0513b111-9296-e9b6-73fa-fe0bdfa30215', 'kwargs': {}} [1626571450447] [DEBUG] 2021-07-18T01:24:10.447Z 66301a7e-0c98-40c1-a54a-5xxxxxxxxxx Zappa Event: {} -
Django Admin - dynamic select options with foreignkey and manytomanyfields
Here the supplier is related to Supplier model (ForeignKey) and substrate is with Substrate (ManyToManyField). The main model here is SupplierInfo from which we can filter suppliers and get their respective substrate. When ever admin clicks on the dropdown of Arrival_supplier and, SupplierInfo_substrate should be filtered with the supplier name and should be able to receive SupplierInfo_substrate inside Arrival_substrate. The Arrival model, where the filtered SupplierInfo_substrate should be saved. class Arrival(models.Model): submitted_on = DateTimeField(auto_created=True, null=True, blank=False, editable=False) edited_on = DateTimeField(auto_now_add=True) submitted_by = ForeignKey(get_user_model(), on_delete=models.SET_NULL, null=True) supplier = ForeignKey(Supplier, null=True, on_delete=models.SET_NULL) arrival_date = DateField(auto_now_add=True, null=True, blank=False) substrate = ManyToManyField(Substrate, blank=True) The Substrate and Supplier models, which are connected to Arrival and Supplier. class Substrate(models.Model): name = CharField(max_length=299, unique=True, null=True, blank=False) class Supplier(models.Model): name = CharField(max_length=299, unique=True, null=True, blank=False) The SupplierInfo model, from which supplier and its substrate should be filtered. Note: One supplier can have multiple substrates. Simply, filtering supplier returns multiple query set each with a different substrate (ForeignKey) name. class SupplierInfo(models.Model): supplier = ForeignKey(to=Supplier, on_delete=models.SET_NULL, null=True, blank=False) substrate = ForeignKey(to=Substrate, on_delete=models.SET_NULL, null=True, blank=False) mushroom = ForeignKey(to=Mushrooms, on_delete=models.SET_NULL, null=True, blank=False) weight = FloatField(null=True, validators=[MinValueValidator(0.9)],blank=False) yield_min = FloatField(null=True, validators=[MinValueValidator(0.9), MaxValueValidator(100)]) yield_max = FloatField(null=True, blank=True, validators=[MinValueValidator(0.9), MaxValueValidator(100)], ) status = BooleanField(null=True) -
Django: How do I use the result from one function in a model to use in another model's function?
I want to use the total_pages in the Book model to find the remaining_pages. I don't know what to put for ? class Book(models.Model): title = models.CharField(max_length=100) start_page = models.IntegerField() end_page = models.IntegerField() def total_pages(self): total_pages = self.start_page-self.end_page return total_pages class Tracker(models.Model): dateRead = models.DateTimeField('entry date') bookmark = models.IntField() book = models.ForeignKey(Book, on_delete=models.CASCADE) def remainingPages(self): remaining_pages = ? - self.bookmark return remaining_pages -
How to capture certain information in a session from a form using ajax
I am trying to learn Django and I am making an eCommerce site that has sessions. I building the cart app and I intend to capture qty, price and item.id in a session using AJAX. To understand the concept, I am attempting to capture only the itemid from the HTML. Unfortunately after a few attempts I haven't been able to update the session. I know the session is not updating from running manage.py shell after clicking the "add to cart" button on the page by decoding the session info using the method below: from django.contrib.sessions.models import Session s = Session.objects.get(pk='<sessionid from chrome cookies>') s.get_decoded() Result = {'skey': {}} Here is my cart app: class Cart(): def __init__(self, request): self.session = request.session cart = self.session.get('skey') if 'skey' not in request.session: cart=self.session['skey'] = {} self.cart = cart def add(self, item): item_id = item.id if item_id not in self.cart: self.cart[item_id] = {'price':str(item.price)} self.session.modified = True Here is my AJAX script: <script> $(document).on('click'), '#add-button',function (e) { e.PreventDefault(); $.ajax({ type: 'POST', url: '{% url "store_cart:cart_add" %}', data: { itemid: $('#add-button').val(), action: 'post' }, success: function (json) { }, error: function(xhr,errmsg,err) {} }); }) </script> Here is my html form I am dealing with: <form class="cart … -
I have a slight misunderstanding about Django’s user’s authentication system
How does Django create users? Does it create users automatically? For example, when someone opens a Django site, is a user object automatically created? I see in a lot of codebase, they use request.user to access the logged in user in views.py but then again, does a user need to login before the User object is created? I have an application I want to create but then, I wouldn’t want to create a Django login system since most users will be logging in only via some third party OAUTH service, like login with Spotify or something. In this case, is there a way to merge both authentication systems? Can I still access the logged in user using request.user? -
Django formset factory getting error object has no attribute save
Info: I want to upload multiple files while creating new customer. I want to use formset_factory for file update. when i try to submit the form i am getting this error CustomerFileFormFormSet object has no attribute save. can anybody tell me how tell me how can i update multiple files while adding new customer in database? models.py class FileData(models.Model): """Files Model""" customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, blank=True) title = models.CharField(max_length=100) file = models.FileField(upload_to='data', blank=True) def __str__(self): return self.title views.py def CustomerCreate(request): """Customer Create View""" customer_form = CustomerForm() customer_file = formset_factory(CustomerFileForm, extra=1) if request.method == 'POST': customer_form = CustomerForm(request.POST) formset = customer_file(request.POST, request.FILES) if customer_form.is_valid() and formset.is_valid(): customer = customer_form.save(commit=False) customer.dealer = request.user customer.save() file = formset.save(commit=False) file.customer = customer file.save() return redirect('/') context = { 'customer_form': customer_form, 'formset': customer_file, } return render(request, "customer/customer-create.html", context) -
handle duplicate attribute in django model fields, looking for best practise
I'm having a senario, where my model have different fields but the share the same attribute for example I have the following model: class Skills(models.Model): pace = models.IntegerField() shooting = models.IntegerField() passing = models.IntegerField() dribbling = models.IntegerField() defending = models.IntegerField() physic = models.IntegerField() gk_diving = models.IntegerField() gk_handling = models.IntegerField() gk_kicking = models.IntegerField() gk_reflexes = models.IntegerField() gk_speed = models.IntegerField() . . . So Is there a way that can let me writing my model in better way? I mean when I want to update, for example, from models.IntegerField() to models.IntegerField(validators=[MaxValueValidator(100),MinValueValidator(1)]). I have to do the update for the whole fields. -
is it possible to pass template variable to django template tag
I created a custom django template tag and it accepts few arguments. Now the problem I am facing is that, the argument that would be passed to template is dynamic and dependent on the value passed from view function. suppose template has value arg1 and I want to pass it to template tag, so I do like {% custom_tag {{arg1}} %} but it doesn't interpret arg1 as variable but a string, any workaround? -
No images nor css showing up on deployed django app heroku
I have launched the this github repository website in this url with Heroku but as you can see there are no images and no .css styling. How is it possible and how to solve this problem? 2021-07-17T21:11:31.115305+00:00 heroku[web.1]: State changed from starting to up 2021-07-17T21:11:32.189726+00:00 app[web.1]: 10.32.150.15 - - [17/Jul/2021:21:11:32 +0000] "GET / HTTP/1.1" 200 8379 "-" "Mozilla/5.0 (Windows NT 10.0; Win 64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" 2021-07-17T21:11:32.191300+00:00 heroku[router]: at=info method=GET path="/" host=dosmusical.herokuapp.com request_id=4ac7c234-855b-4ac4-aaee-56746352ec73 fwd="185.104.137.33" dyno=web.1 connect=1ms service=93ms status=200 bytes=8620 protocol=https 2021-07-17T21:11:32.206068+00:00 app[web.1]: 10.35.232.224 - - [17/Jul/2021:21:11:32 +0000] "GET / HTTP/1.1" 200 8379 "-" "Mozilla/5.0 (Windows NT 10.0; Wi n64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" 2021-07-17T21:11:32.206552+00:00 heroku[router]: at=info method=GET path="/" host=dosmusical.herokuapp.com request_id=72da5619-c34f-4d19-a069-339cc3d38088 fwd="185.104.137.33" dyno=web.1 connect=1ms service=61ms status=200 bytes=8620 protocol=http 2021-07-17T21:11:32.653544+00:00 app[web.1]: 10.32.150.15 - - [17/Jul/2021:21:11:32 +0000] "GET / HTTP/1.1" 200 8379 "-" "Mozilla/5.0 (Windows NT 10.0; Win 64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" 2021-07-17T21:11:32.654864+00:00 heroku[router]: at=info method=GET path="/" host=dosmusical.herokuapp.com request_id=dcf31e75-36a3-4b1e-b7b3-fa9631278f69 fwd="185.104.137.33" dyno=web.1 connect=1ms service=3ms status=200 bytes=8620 protocol=https 2021-07-17T21:11:32.656678+00:00 app[web.1]: 10.35.232.224 - - [17/Jul/2021:21:11:32 +0000] "GET /static/vendor/bootstrap/css/bootstrap.min.css HTTP/1.1" 4 04 179 "http://dosmusical.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537 .36" 2021-07-17T21:11:32.657225+00:00 heroku[router]: at=info method=GET path="/static/vendor/bootstrap/css/bootstrap.min.css" host=dosmusical.herokuapp.com req uest_id=d27178a7-957f-43d6-b882-0aadcbb3a77a fwd="185.104.137.33" … -
getting all records with same foreign key in django
I'm working on my first project in Django/Postgres, an app to track plant breeding projects. I have a Generation model that connects to a Project model with ForeignKey (i.e., each breeding project consists of multiple generations of offspring): class Generation(models.Model): # ... project = models.ForeignKey( Project, related_name="generations", on_delete=models.CASCADE ) I'd like to add a generation_number field that auto-increments based on the associated project - if there are already 3 records with the same foreign key in the Generation table, then the next record created with that FK should get assigned a generation_number of 4. My understanding is that I can't use an AutoField because this is not a primary key, so I'm trying to write a method that counts the number of records with the same FK and adds 1, something like: def increment_gen_number(self): last_count = Project.objects.filter(pk=self.project).count() return last_count+1 gen_number = models.IntegerField(default=increment_gen_number) I'm guessing there are some syntax issues since I'm still new to Python and this feels like a bit of a kludge. How can I get this to work? -
Message: mutate() missing 1 required positional argument: 'file'
I am trying to upload an image using Apollo, GraphQL, and Django. I see the file in my console so it is properly input in the form. I am still getting the error back from the server: Upon pressing submit: const customSubmit = async (data) => { try { const updateResponse = await updateGmProfile({ variables: { email: data.email }, }); const uploadResponse = await uploadFile({ variables: { file: data.proImg[0] }, }); if (updateResponse && uploadResponse) { addToast("Sucessfully updated!", { appearance: "success", autoDismiss: true, }); router.push(getGMDashboard()); } } catch (error) { console.log("updateGMProfile error:", error); addToast(error.message, { appearance: "error", autoDismiss: true }); } }; Upload Query Function const [uploadFile, { uploadData }] = useMutation(uploadFileMutation); Upload Mutation export const uploadFileMutation = gql` mutation uploadFileMutation($file: Upload!) { uploadFileMutation(proImg: $file) { user { id username } } } `; From console: File {name: "logo.gif", lastModified: 1623080829083, lastModifiedDate: Mon Jun 07 2021 11:47:09 GMT-0400 (Eastern Daylight Time), webkitRelativePath: "", size: 5671877, …} Why do I keep getting this error even though the file is present during the mutation? [GraphQL error]: Message: mutate() missing 1 required positional argument: 'file', Location: [object Object], Path: uploadFileMutation -
Django Annotate and aggregate behaviour clarification. Auto filtering?
Im writing an API in DRF and had some questions on the behaviour of annotate and aggregate on query sets. So I essentially have models Product, Producer, and a model inventory. An inventory contains a product fk, producer fk and quantity and price fields, among other unimportant fields. I have a view which lists out all the inventory items, and filters them based on producer. Im trying to annotate the query set to aggregate and sum the quantity of each product among all inventory items. Initially I just referenced the quantity field directly. That way works apparently, however Im suspicious because it works even if I don't specify that it needs to filter entries based on product. For safety, I access the product model from the inventory model, and then did a reverse relationship from product back to inventory, and referenced the quantity to be aggregated. I get the same expected values, and in this way I understand why its working, however it feels inefficient. I need some clarification on why the simple solution works, and if I should use it, since nowhere am I filtering my product, however the aggregated values are aggregated based on product. class Inventory(models.Model): item_ID … -
How i can add product review option in django?
Below i have added and image of it for example, enter image description here -
What is the Best AWS service(Elastic Beanstalk or Lightsail) I can use to deploy django application for large scale usage, or any other than AWS
I want to use AWS to deploy my Django application what would be the best option as I am planning an application that would serve many people around and more than 1 lack. -
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 …