Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django PDF generated not download last version
I have a Django view to show a preview of Pdf generated and works well. I have configured an AWS S3 service to save Pdf generated files and overwrite if existing with same name and works well because i have checked and downloaded manually from bucket. When it's generated again it's visualized well in the browser preview but when downloaded it appears the old version. views.py: @login_required() def budget_pdf(request, id=None): budget = get_object_or_404(app_models.Budget, id=id) concepts = budget.concept_budget.all() file = app_pdf.PDF(None, budget, concepts) pdf_file = file.generate_budget() file_name = 'Pto_' + str(budget.brand.client.name) + '_' + str(budget.name) + '_' + str(budget.code) + ".pdf" budget.pdf.save(file_name, ContentFile(pdf_file), save=True) return render(request, 'file.html', {'element': budget}) file.html: <iframe height=100% width="100%" src="{{ element.pdf.url }}" style="min-height: 800px;"></iframe> Anybody could help me please ? Thanks in advance. -
Django How to call a function in views.py from ajax by clicking submit button with variable
I am facing issue with calling a functions in views.py from script html HTML: <form method="POST" class="msger-inputarea"> {% csrf_token %} <input type="text" name="msg" class="msger-input" placeholder="Enter your message..."> <button type="submit" name="answer" class="msger-send-btn">Send</button> </form> <script type="text/javascript"> msgerForm.addEventListener("submit", event => { event.preventDefault(); const msgText = msgerInput.value; if (!msgText) return; appendMessage(PERSON_NAME, PERSON_IMG, "right", msgText); msgerInput.value = ""; botResponse(msgText); }); function botResponse(rawText) { alert(rawText) alert('inside ajax') $.ajax({ url: "{% url 'ajaxview' %}", method: 'POST', data: {'rawText': rawText , csrfmiddlewaretoken: '{{ csrf_token }}'}, success: function (response) { appendMessage(PERSON_NAME, PERSON_IMG, "left", response); }, }); } URL.py : path('/ajax-test-view', views.myajaxtestview, name='ajaxview') VIEWS.py : def myajaxtestview(request): input = request.POST.get('rawText') return HttpResponse(input) -
save to model after computed in serializer
The serializer will computed the average score of the data and return to view in field weekly_score class BrandChartsSerializer(serializers.ModelSerializer): rankings = serializers.SerializerMethodField() instagram = IGSerializer(allow_null=True) facebook = FBSerializer(allow_null=True) hashtags = BrandHashtagSerializer(allow_null=True, many=True) # rename the json field brand_uid = serializers.IntegerField(source='id') brand_name = serializers.CharField(source='name') origin = serializers.CharField(source="country") weekly_score = serializers.SerializerMethodField() class Meta: model = Brand fields = [ "rankings", "brand_uid", "brand_name", "origin", "instagram", "facebook", "hashtags", "weekly_score", ] def get_weekly_score(self,instance): data = self.get_rankings(instance) result = 0 counter = 0 while data: rankings = data.pop() for key,value in rankings.items(): isFloat = isinstance(value,float) if isFloat: result += value counter += 1 if counter is not 0: result = result/counter return result And I will do sorting in view by sorted() and return as list. It's work but I found that the speed of it is very very slow, so I would like to speed it up. One way I think I could try is, save the computed weekly_score to the models (it already have field in model design) So that i could use order_by of models. So the problem is, it is possible for me to do read and update at same view? It's possbile for me do save/update action in BrandChartsSerializer ? or … -
Chat Group Request is not Saving in Admin
I am building a ChatApp and I am stuck on a Problem. What i am trying to do :- I am trying to send user_1 group chat request from user_2 BUT The Problem is that, The request is not saving in Django Admin. Also request is unable to reach to user_1 What am i using ? I am using Ajax views.py def send_group_invite(request, user_pk, group_pk): request_sender = request.user reciever = get_object_or_404(User, pk=user_pk) group = get_object_or_404(ChatGroup, pk=group_pk) if request_sender == reciever: message = { 'text': f'You can\'t invite yourself', 'tags': 'error', } return JsonResponse({'message': message}) group_request = GroupRequest( request_sender=request_sender, reciever=reciever, group=group) group_request_check = GroupRequest.objects.filter( request_sender=request_sender, reciever=reciever) group_request.save() return JsonResponse({'message': message}) models.py class ChatGroup(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) group_admins = models.ManyToManyField(User, related_name='gropu_admins', blank=True) members = models.ManyToManyField(User, related_name='group_memebers', blank=True) template.html for (result of response.results) { let invite = `<a class="float-right inviteFriend btn" href="/social/send_group_invite/${result.id}/{{ group.id }}/"> <i class="fas fa-user-plus" style="font-size: 36px; color: green;"></i> Invites </a>` if (!result.is_allowed_group_invite) { invite = `<p class="float-right"><i class="fas fa-shield-alt" style="font-size: 36px; color: red;"></i> You can't add</p>` } let phone = '' let email = '' if (result.phone) { phone = `<i class="fas fa-phone-alt"></i>${result.phone}` } if (result.email) { email = `<i class="fas fa-envelope"></i>${result.email}` } $('.inviteUserResults').append(` <li class="media"> <a href="/people/${result.id}" target="_blank"> … -
'QuerySet' object has no attribute 'likes'
I am implementing a likes system for my post. I have used a ManyToManyField in my model. models.py class MarketingMaestro (models.Model): product_title = models.CharField(max_length=250) total_value = models.IntegerField() branding_video = models.CharField(max_length=300) likes = models.ManyToManyField(User, related_name='likes', blank=True) In this I get all the list of the users, and if someone likes the post it is updated in the field. But when I am trying to implement the logic where if the user has already liked the post he/she will be able to see the dislike button only. While doing so I am fetching all the values from the db and checking particular likes field but it is showing error 'QuerySet' object has no attribute 'likes' It is giving me error on the line if marking_maestro.likes.filter(id=request.user.id).exists(): I tried printing the value but is it returning just the queryset <QuerySet [<MarketingMaestro: MarketingMaestro object (1)>]> and if i print the product_title using (marking_maestro.product_title) but then I get the error saying 'QuerySet' object has no attribute 'product_title' -views.py def brand(request): # fetching all the projects marking_maestro = MarketingMaestro.objects.all() is_liked = False print(marking_maestro) if marking_maestro.likes.filter(id=request.user.id).exists(): is_liked = True # fetching the votes emailID = request.user.email context = { 'is_liked' : is_liked } return render(request, 'brand.html', {'marking_maestro' : … -
run a set of queries faster with python and postgres
in my example, I have a list of 3000 words to search in a database, so with this pyhton code (I am using django) the operation takes a lot of time and is done in 3.5 minutes with the average of 120ms for a querie. is there a method to speed up the execution of these queries with a script python using threads or something like that? def my_custom_sql(ent): for e in ent: with connection.cursor() as cursor: entity=e.replace("'","''") cursor.execute("SELECT object FROM yagofacts WHERE subject='{}' AND object LIKE '<wordnet_%>';".format(entity)) row = cursor.fetchall() print(row) -
How to import Session model in __init__.py ? - Django
How to import Session model in init.py ? - Django I'm trying to change the name of the default django table. I can do this and it works perfectly by changing the direct link on site-packages and it works perfectly. But this is bad, because for the project the nomenclature is different so I need to do this at run time app/__init __.py from django.contrib.sessions.models import Session Session._meta.db_table = "my_session" Error: D:\PyEnv38\lib\site-packages\django\apps\registry.py", line 136, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
how to add excel sheet data to mysql database using django
I have tried to get a code for adding excel sheet details to MySQL database using Python Django but i could not find a better code .Can anyone suggest a better way of adding data from excel sheet to database using Django. -
AttributeError at /api/updateorder/71 'RelatedManager' object has no attribute 'save'
I am trying to make update api for order objects. OrderItem model is in many to one relationship (with Foreignkey) with Order Model. Also, Billing Details model is one to one relationship with Order model. I am able to update Billing details fields and also Order fields, but cant update the OrderItem fields. I got this error saying 'RelatedManager' object has no attribute 'save' My models: class Order(models.Model): ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) total_price = models.CharField(max_length=50,blank=True,null=True) #billing_details = models.OneToOneField('BillingDetails',on_delete=models.CASCADE,null=True,blank=True,related_name="order") def __str__(self): return self.user.email class Meta: verbose_name_plural = "Orders" ordering = ('-id',) class OrderItem(models.Model): #user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants,on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) # def price(self): # total_item_price = self.quantity * self.item.varaints.price # return total_item_price total_item_price = models.PositiveIntegerField(blank=True,null=True,) def __str__(self): return f"{self.quantity} items of {self.item} of {self.order.user}" class Meta: verbose_name_plural = "Cart Items" ordering = ('-id',) class BillingDetails(models.Model): PAYMENT_TYPE = ( ('cash_on_delivery', 'Cash On Delivery',), ('credit/debit_card', 'Credit/Debit Card',), ('connect_ips', 'Connect IPS',), ('fonepay', 'Fonepay',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order = models.OneToOneField(Order, on_delete=models.CASCADE, blank=True, null=True, related_name='billing_details') address = models.CharField(max_length=100,blank=True,null=True) … -
How can I perform operation over model field and filter in django?
My model has a field named key, it looks like; key = models.CharField(max_length=64) I store encrypted string generated using pycrypto python package into key field. key = encrypted string of string 'abc' Now I try to filter over model using field key with encrypted string of same string, does not get any record beacaus each time i encrypt string 'abc' get different encrypted string. model.objects.filter(key=new encrypted string of abc) is that any way to perform decryption operation into model field and filter out using plain string like model.objects.filter(operation on key = 'abc') or do I need to go with any other solution. -
wfastcgi-enable it show 'Ensure your user has sufficient privileges and try again.'
I want to deploy my django website in window server 2008 by follow this tutorial https://www.youtube.com/watch?v=CpFU16KrJcQ&t=191s In step wfastcgi-enable it show message like this. command prompt Microsoft Windows [Version 6.0.6002] Copyright (c) 2006 Microsoft Corporation. All rights reserved. C:\Users\Administrator>wfastcgi-enable ERROR ( message:Unknown attribute "signalBeforeTerminateSeconds". ) An error occurred running the command: ['C:\\Windows\\system32\\inetsrv\\appcmd.exe', 'set', 'config', '/section:system .webServer/fastCGI', "/+[fullPath='c:\\users\\administrator\\appdata\\local\\pro grams\\python\\python37\\python.exe', arguments='c:\\users\\administrator\\appda ta\\local\\programs\\python\\python37\\lib\\site-packages\\wfastcgi.py', signalB eforeTerminateSeconds='30']"] Ensure your user has sufficient privileges and try again. C:\Users\Administrator> -
DRF how to sort value by custom field
serizalizer: class BrandChartsSerializer(serializers.ModelSerializer): rankings = serializers.SerializerMethodField() instagram = IGSerializer(allow_null=True) facebook = FBSerializer(allow_null=True) hashtags = BrandHashtagSerializer(allow_null=True, many=True) # rename the json field brand_uid = serializers.IntegerField(source='id') brand_name = serializers.CharField(source='name') origin = serializers.CharField(source="country") weekly_score = serializers.SerializerMethodField() class Meta: model = Brand fields = [ "rankings", "brand_uid", "brand_name", "origin", "instagram", "facebook", "hashtags", "weekly_score", ] def get_weekly_score(self,instance): data = self.get_rankings(instance) result = 0 counter = 0 while data: rankings = data.pop() for key,value in rankings.items(): isFloat = isinstance(value,float) if isFloat: result += value counter += 1 if counter is not 0: result = result/counter return result the field weekly_score is empty nullable field in model Brand and set value in serizalizer here is the viewset code: class BrandChartsViewSet(ModelViewSet): pagination_class = BrandChartsPagination serializer_class = BrandChartsSerializer queryset = Brand.objects.none() def get_serializer(self, *args, **kwargs): """ Return the serializer instance that should be used for validating and deserializing input, and for serializing output. """ serializer_class = self.get_serializer_class() kwargs['context'] = self.get_serializer_context() return serializer_class(*args, **kwargs) def get_serializer_context(self): start_date = self.request.query_params.get('start_date',None) end_date = self.request.query_params.get('end_date',None) if start_date is None: raise InvalidInputError() if end_date is None: raise InvalidInputError() start_date_obj = datetime.strptime(start_date,'%Y%m%d') end_date_obj = datetime.strptime(end_date,'%Y%m%d') return { 'start_date': start_date_obj, 'end_date': end_date_obj, } def list(self, *args, **kwargs): kwargs['context'] = self.get_serializer_context() queryset = Brand.objects.all() serializer = BrandChartsSerializer(queryset,many=True) … -
Celery Worker Error : self.buffer = mmap.mmap(self.fd, self.size) FileNotFoundError: [Errno 2] No such file or directory
I am getting self.buffer = mmap.mmap(self.fd, self.size) FileNotFoundError: [Errno 2] No such file or directory error while running celery with docker on windows. It is working perfectly on mac. dvu-celeryworker | [2021-03-26 11:08:20,286: CRITICAL/MainProcess] Unrecoverable error: FileNotFoundError(2, 'No such file or directory') dvu-celeryworker | Traceback (most recent call last): dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/celery/worker/worker.py", line 208, in start dvu-celeryworker | self.blueprint.start(self) dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/celery/bootsteps.py", line 119, in start dvu-celeryworker | step.start(parent) dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/celery/bootsteps.py", line 369, in start dvu-celeryworker | return self.obj.start() dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/celery/concurrency/base.py", line 132, in start dvu-celeryworker | self.on_start() dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/celery/concurrency/prefork.py", line 111, in on_start dvu-celeryworker | P = self._pool = Pool(processes=self.limit, dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/celery/concurrency/asynpool.py", line 486, in __init__ dvu-celeryworker | super(AsynPool, self).__init__(processes, *args, **kwargs) dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/billiard/pool.py", line 1046, in __init__ dvu-celeryworker | self._create_worker_process(i) dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/celery/concurrency/asynpool.py", line 503, in _create_worker_process dvu-celeryworker | return super(AsynPool, self)._create_worker_process(i) dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/billiard/pool.py", line 1142, in _create_worker_process dvu-celeryworker | on_ready_counter = self._ctx.Value('i') dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/billiard/context.py", line 181, in Value dvu-celeryworker | return Value(typecode_or_type, *args, lock=lock, dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/billiard/sharedctypes.py", line 78, in Value dvu-celeryworker | obj = RawValue(typecode_or_type, *args) dvu-celeryworker | File "/usr/local/lib/python3.8/site-packages/billiard/sharedctypes.py", line 46, in RawValue dvu-celeryworker | obj = … -
django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xC2\\x8E\\xC3\\xA9co...' for column 'announce' at row 1")
I am migrationg data from legacy database to new database. I tried code on local, it worked fine. When I am running code in production, for some fields, it's giving error django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xC2\\x8E\\xC3\\xA9co...' for column 'announce' at row 1") mysql version on local - 8.0.16 mysql version in production server - 5.7.33- How can I fix this. -
Single django data model with multiple subclasses for methods only
I want a single datamodel but to support inherited methods on the same data based on a field type. The simplest way I know to do it is class Foo(models.Model) name = models.CharField(max_length=16) role = models.CharField(max_length=16) data = models.JSONField() def html(self): if role == 'bar': return self.method_bar() elif role == 'baz': return self.method_baz() elif role == 'qux': return self.method_qux() else: return None def method_bar(self): # do something with self.data return def method_baz(self): # do something with self.data return def method_qux(self): # do something with self.data return I really do not like this approach because I have to add a new method when I add a new role rather than adding a new module with the transformation for that role and not risk breaking existing code. Is this alternative wasteful? class Foo(models.Model) name = models.CharField() role = models.CharField(choices=['bar', 'baz', 'qux'], default=None) data = models.JSONField() module = models.CharField(max_length=256) class = models.CharField(max_length=256) def html(self): mod = importlib.import_module(class_module) cls = getattr(mod, class_name, None) if cls is None: return None obj = cls() return obj.html() What are better/more elegant ways to achieve the same result? -
Request timeout/delay Issue
My Applications posts to Instagram using the Django rest-framework. Posting to Instagram is a two step process. First you must send the content to a media container. Then you must wait until Instagram finishes processing the photo/video. Once the media is done being processed you send the creation ID to Instagram to make the post public. In order to ensure that Instagram has enough time to process the media before the creation ID is sent, I use Django's time.sleep function to pause the request for 60 seconds. The problem is that this works on my desktop, but on my ec2 instance the same code fails when I pause the request longer than 10 seconds. To run my application I am using amazon EC2, Gunicorn and nginx. My Django code is this ```#print('posting photo to facebook') video_url = data.get('video_url') container_url = "https://graph.facebook.com/" + page_id + "/media?media_type=VIDEO&\ video_url=" + video_url + "&caption=" + text + "&access_token=" + access_token res = requests.post(container_url) data = res.json() time.sleep(60) publish_url = "https://graph.facebook.com/" + page_id + "/media_publish?\ creation_id=" + data['id'] + "&access_token=" + access_token res = requests.post(publish_url) data = res.json() print('result of video posting attempt') print(json.dumps(data)); a = res.status_code b = 200 #print(res.text) if a != b: … -
Get Data From A Foreign Key Django
I am trying to get all products related to an orderitem but am having a problem doing the query. I want to list all products in an orderitem. Hope i have provided everything needed. from django.core.validators import RegexValidator from django.db import models from django.urls import reverse from django.utils.text import slugify from django.contrib.auth import get_user_model class Order(models.Model): ref_code = models.CharField(max_length=20, blank=True, null=True) first_name = models.CharField(('first name'), max_length=30, blank=True) last_name = models.CharField(('last name'), max_length=30, blank=True) class Product(models.Model): category = models.ForeignKey(Category,related_name='products',on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True, unique=True) class OrderItem(models.Model): order = models.ForeignKey(Order,related_name='items',on_delete=models.CASCADE) product = models.ForeignKey(Product,related_name='order_items',on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) slug = models.SlugField(max_length=200, db_index=True) -
sequence item 3: expected str instance, InMemoryUploadedFile found in Django
I got error while i tried to send images via email in django the error appear in this line 'id_card': form.cleaned_data.get['id_card'], my form class Verification(forms.Form): first_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control', 'required': "True"})) last_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control', 'required': "True"})) email = forms.EmailField(max_length=150, widget=forms.TextInput(attrs={'class': 'form-control', 'required': "True"})) id_card = forms.ImageField(widget=forms.ClearableFileInput(attrs={'class': 'custom-file-input', 'id': 'card-id', 'required': "True"})) my views if request.method == 'POST': form = Verification(request.POST, request.FILES) if form.is_valid(): subject = 'request Verification' body = { 'first_name': form.cleaned_data['first_name'], 'last_name': form.cleaned_data['last_name'], 'email': form.cleaned_data['email'], 'id_card': form.cleaned_data['id_card'], } message = "\n".join(body.values()) try: send_mail(subject, message, 'mohamed89salah98@gmail.com', ['mohamed89salah98@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('after-verification') form = Verification() return render(request, 'personal/verification.html', {'form': form}) -
Basic Django POST not creating model with sqlite
When I click the submit button, it redirects me to the create model (in this case create record) page, and does not actually create a new model, it doesn't appear in the main page which shows all models that were created. I tried following this tutorial: Link I feel like I did mostly the same things as him, and yet my form submission button does not create my post. The differences between our programs is simply the naming and the number of fields in my model. The user registration form works, but that is using a function based view, this is using a class based view (should still work as far as I know), and there are barely any differences between the model creation html and the user registration html. Here's the model creation form, record_form.html: {% extends "catalog/base.html" %} {% block content %} <h1 class="text py-3 pt-4">Create a Record!</h1> <style> .text { font-size: 40px; font-weight: bold; color: #060007; } </style> <div class="shadow p-3 mb-3 bg-light rounded"> <form class="form" method="POST" action="/catalog/"> {% csrf_token %} <p> <label for="name">Name:</label> {{ form.name }} </p> <p> <label for="description">Description:</label> </p> <p> {{ form.description }} </p> <p> <label for="date_start">Date start:</label> {{ form.date_start }} </p> <p> <label … -
ValueError: "<User: >" needs to have a value for field "id" before this many-to-many relationship can be used?
I haved created customize User model. class User(AbstractUser): mobile = models.CharField(validators=[RegexValidator(regex="^\d{11}$", message="Length has to be 11", code="nomatch")], max_length=11) After the user who’s is_superuser is 0 and is_staff is 1 logs in, when this user who has permission to add users performs the operation of adding a user, the following error occurred. ValueError: "<User: >" needs to have a value for field "id" before this many-to-many relationship can be used. I just created the user model and start django, and don't know what happened, the version of django is 3.0.6 and the xadmin's version is 2.0.1. Later I performed the above operation when django's version is 1.11.11 and xadmin's version is 0.6.1, the operation adding a user is normal executed. please help me to solve this problem, thanks very much! -
How can i to create base class for extend to another class?
How can i to create base class for extend to another class class BaseCustomModelAdmin(admin.ModelAdmin): model = None list_display = [field.name for field in model._meta.get_fields()] search_fields = [field.name for field in model._meta.get_fields()] use like this class BaseCustomModelAdmin(BaseCustomModelAdmin): model = Person -
The view HomePage.views.signin didn't return an HttpResponse object. It returned None instead
this is my views.py file where the signin page is not getting loaded and showing the error while am clicking on signin "The view HomePage.views.signin didn't return an HttpResponse object. It returned None instead." could any one place help me out from django.shortcuts import render from. models import student from django.contrib.auth import authenticate from django.shortcuts import redirect # Create your views here. def HomePage(request): return render(request,'index.html',{'link':"https://cloudbinary.io/"}) def signup(request): return render(request,'signup.html') def register(request): if request.method == 'POST': name =request.POST["name"] email =request.POST["email"] mobile =request.POST["mobile"] Password=request.POST["password"] course =request.POST["course"] if student.objects.filter(Email=email).exists(): messages.info(request,'email already in use') return redirect('signup') else: Student =student(Name=name,Email=email,phone=mobile,Course=course,Password=Password) Student.save() print("user created") return render(request,'signup.html') def signin(request): if request.method=='POST': email1=request.POST['email1'] Password1=request.POST['Password1'] stud=auth.authenticate(Email=email1,Password=Password1) if stud is None: auth.login(request,stud) return redirect("/signin/") else: messages.info(request,'invalid credentials') return redirect('login.html') -
Django: How to Add Default Location for Forms.ImageField
I am changing my models to forms so that I can use a placeholder for my textboxes. In doing so, I am having difficulty changing the ImageField because it is providing me with an error that it recieved ``an unexpected keyword: default``` Here are my models.py: class Project(forms.Form): name = forms.CharField(max_length=30) #owner = models.ForeignKey(User, on_delete=models.CASCADE, null = True) bPic = forms.ImageField(default='defaultproban.jpg', upload_to='project_banner') logo = forms.ImageField(default='defaultlogo.jpg', upload_to='project_logo') dep_choice1 = ( ('Behavioral Sciences and Leadership', ('Behavioral Sciences and Leadership')), ('Chemistry and Life Science', ('Chemistry and Life Science')), ('Civil and Mechanical Engineering', ('Civil and Mechanical Engineering')), ('Electrical Engineering and Comptuer Science', ('Electrical Engineering and Comptuer Science')), ('English and Philosophy', ('English and Philosophy')), ('Foreign Languages', ('Foreign Languages')), ('Geography and Environmental Engineering', ('Geography and Environmental Engineering')), ('History', ('History')), ('Law', ('Law')), ('Mathematical Sciences', ('Mathematical Sciences')), ('Physics and Nuclear Engineering', ('Physics and Nuclear Engineering')), ('Social Sciences', ('Social Sciences')), ('Systems Engineering', ('Systems Engineering')), ('Independent', ('Independent')), ) department = forms.CharField( max_length=50, choices=dep_choice1, default='Independent', ) purpose = forms.CharField(max_length=50, null = True, widget=forms.TextInput(attrs={'placeholder':'Write Your Mission Statement'})) description=forms.TextField(widget=forms.TextInput(attrs={'placeholder':'Briefly Describe Your Project, Progress, Goals, and Your Team!'})) tag_choice = ( ('Data Analysis' , ('Data Analysis')), ('3D Printing' , ('3D Printing')), ('Robotics' , ('Robotics')), ('Coding' , ('Coding')), ('Science' , ('Science')), ('Drones' , ('Drones')), ('Math' … -
DRF get field from other serizalizer
I'm trying to solve my previous question : drf ordering by custom field and add ranking in to_representation My idea now is create an nullable field in model (db), so that I could try to store the custom field into the nuallable field and then sort it by nullable field in viewset not serizalizer. However how could I pass the value to this nullable empty field in serizalizer? the nullable field I define is weekly_score and here is the code: def get_weekly_score(self,instance): data = super().to_representation(instance) rankings = data.pop('rankings', None) result=0 if rankings: popscore_sum = 0 counter = 0 for value in rankings: for key, value in rankings[counter].items(): isFloat = isinstance(value, float) if isFloat: popscore_sum += value counter += 1 result = popscore_sum / counter return result However it give error Django:“RuntimeError: maximum recursion depth exceeded” -
Is something wrong with the password change page on Django admin?
Using Django 3.16, going into the admin console and managing a user (admin/auth/user/412/change/ in the example of user id 412), I attempt to change the user password by clicking on the link "you can change the password using this form". But when I click on the link I get the error "User with ID "412/password". It's like the URL settings aren't pulling the PK/ID out of the URL properly. (You'll see I'm using the Grappelli styling for the admin console. I've tested it without Grappelli and I get the same errors.) My urls.py has the usual line path('admin/', admin.site.urls). Is there some reason why this might be happening, or something I can do about it? thanks John