Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Incorrect padding when attempting to update profile picture
My project is built on React and Django. I would like to enable users to update profile information. Noticed that I was initially getting a 304 error when it specifically comes to updating the profile picture. and realized that this had something to do with Django requiring multipart form data. I then tried to upload the profile picture using a base64 encoding string, but now getting the error Incorrect padding Here is my serializers.py: #upload profile picture using base64 encoding string instead of raw file (not supported by default) class Base64ImageField(serializers.ImageField): def to_internal_value(self, data): from django.core.files.base import ContentFile import base64 import six import uuid #check if this is base64 string if isinstance(data, six.string_types): #check if the base64 is in the data format if 'data:' in data and ';base64' in data: header,data = data.split(';base64,') try: decoded_file = base64.b64decode(data) except TypeError: self.fail('invalid_image') #Generate file name: file_name = str(uuid.uuid4())[:12] #Get the file name extension file_extension = self.get_file_extension(file_name, decoded_file) complete_file_name = "%s.%s" % (file_name, file_extension, ) data = ContentFile(decoded_file, name=complete_file_name) return super(Base64ImageField, self).to_internal_value(data) def get_file_extension(self, file_name, decoded_file): import imghdr extension = imghdr.what(file_name, decoded_file) extension = "jpg" if extension == "jpeg" else extension return extension #updating user profile class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) city = … -
Reverse for 'list-events' not found
Im currently following a Django tutorial to learn views and URLs. I have watched the tutorial over and over and cant see what I am doing wrong. I receive the error: Exception Value: Reverse for 'list-events' not found. 'list-events' is not a valid view function or pattern name. Views.py from django.shortcuts import render, redirect import calendar from calendar import HTMLCalendar from datetime import datetime from .models import Event, Venue from .forms import VenueForm, EventForm from django.http import HttpResponseRedirect # Create your views here. # all events is listed in the urls.py hence why the function is named all_events def update_event(request, event_id): event = Event.objects.get(pk=event_id) form = EventForm(request.POST, instance=event) if form.is_valid(): form.save() return redirect('list-events') return render(request, 'events/update_event.html', {'event': event, 'form':form}) def add_event(request): submitted = False if request.method == 'POST': form = EventForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/add_event?submitted=True') else: form = EventForm if 'submitted' in request.GET: submitted = True return render(request, 'events/add_event.html', {'form': form, 'submitted': submitted}) def update_venue(request, venue_id): venue = Venue.objects.get(pk=venue_id) form = VenueForm(request.POST, instance=venue) if form.is_valid(): form.save() return redirect('list-venues') return render(request, 'events/update_venue.html', {'venue': venue, 'form': form}) def search_venues(request): if request.method == "POST": searched = request.POST['searched'] venues = Venue.objects.filter(name__contains=searched) return render(request, 'events/search_venues.html', {'searched': searched, 'venues': venues}) else: return render(request, 'events/search_venues.html', {}) … -
Test of Django ProfileListView fails with ValueError: Cannot assign "<SimpleLazyObject:....>": "Profile.user" must be a "User" instance
I am a Django beginner and a SOF newbie, sorry if this question sounds a silly to some. I am struggling with my integration tests. In my app I have a one-to-one User/Profile relationship. I have a list view to show registered users' profile data: class ProfileListView(views.ListView, LoginRequiredMixin): model = Profile template_name = 'registration/profile_list.html' paginate_by = 8 def get_context_data(self, *, object_list=None, **kwargs): context = super(ProfileListView, self).get_context_data() # superuser raises DoesNotExist at /accounts/profiles/ as they are created with createsuperuser in manage.py # hence are not assigned a profile automatically => create profile for them here try: context['current_profile'] = Profile.objects.get(pk=self.request.user.pk) except ObjectDoesNotExist: Profile.objects.create(user=self.request.user) context['current_profile'] = Profile.objects.get(pk=self.request.user.pk) # get all other users' profiles apart from staff and current user regular_users = User.objects \ .filter(is_superuser=False, is_staff=False, is_active=True) \ .exclude(pk=self.request.user.pk) context['non_staff_active_profiles'] = Profile.objects.filter(user__in=regular_users) return context I want to test the get_context_data() method to ensure it returns: correct logged in user correct queryset of non-staff profiles My test breaks as soon as I try something like: response = self.client.get('/accounts/profiles/') I understand I need to pass user/profile data to the client but I could not figure out how to do that. It looks like it fails because of context['current_profile'] = Profile.objects.get(pk=self.request.user.pk) and I have no idea why. … -
Embed Plotly in html with responsive behavior: can I change legend position based on screen width?
I am using Plotly to embed a plot on an HTML page. My website is responsive, but I am not satisfied with the legend of the plot that I have embedded. Here you can see two screenshots: on the left, we see the plot on a widescreen, and on the right with a narrow one. vs As shown in the figure, the plot looks good on the widescreen (left). However, when the screen is narrow (right), the legend takes too much space and the plot is shrunk. Moving the legend below when the screen is small would solve the issue (as depicted with the red drawing). Is it possible to embed such a responsive behavior in Plotly when adding the legend? Thanks in advance! :) -
How I can use a django variable in if statement of django template into a javascript string variable
I want to add a div to my page using a javascript variable. This div must take a class right or left ,but my if condition doesn't work in this variable, And it works if I try it without javascript. This is my view : def chat(request,sender_id,receiver_id): if request.user.is_authenticated: if request.user.profile == 'C' or request.user.profile == 'A': user = User.objects.filter(id=request.user.id).get() receiver_user = User.objects.filter(id=receiver_id).get() if request.user.profile == 'A': chat = Chat.objects.filter(Q(sender_id=sender_id) | Q(receiver_id=sender_id)).all() elif request.user.profile == 'C': chat = Chat.objects.filter(Q(sender_id=sender_id,receiver_id=receiver_id) | Q(sender_id=receiver_id,receiver_id=sender_id)) context = { 'user': user, 'chat': chat, 'receiver_user': receiver_user, } return render(request,'chat/chat.html',context) return render(request, 'Login/logout.html') And this is my javascript : $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url : "{% url 'getMessages' request.user.id receiver_user.id %}", success: function(response){ console.log(response); $("#display").empty(); for (var key in response.chat) { var temp='<div class="msg-box {% if request.user.id == chat.sender_id %} right {% else %} left {% endif %}">\ <div class="details">\ <p class="msg">'+response.chat[key].message+'</p>\ <p class="date">'+response.chat[key].msg_time+'</p></div></div>'; $("#display").append(temp); } }, error: function(response){ console.log('An error occured') } }); },100); }); -
Django Polymorphic Serializer Object of type ListSerializer is not JSON serializable
I'm working on a django view to return a nested list inside another list of records, to do this I use a nested serializer. The thing is that nested serializer is a Polymorphic serializer that decomposes to many other serializers. When I'm using a normal serializer instead of the polymorphic one the approach works fine, but when I use a polymorphic serializer it gives the following error Object of type ListSerializer is not JSON serializable Here is how I'm calling the first serializer in my view return Response(serializers.FormEntriesHistorySerializer(forms,many=True,context={'device_id': kwargs.get('device_id')}).data) And this is the parent serializer class FormEntrySerializer(serializers.ModelSerializer): #form = FormSerializer(read_only=True) response_set = ResponsePolymorphicSerializer(many=True,read_only=True) class Meta: model = models.FormEntry fields = '__all__' def to_representation(self, instance): response = super().to_representation(instance) response["response_set"] = sorted(response["response_set"], key=lambda x: x["id"],reverse=True) return response def validate(self, attrs): print("Validation in on going") return attrs The error is triggered by the ResponsePolymorphicSerializer, as I said this approach works fine if I use a normal serializer instead. But in this case I need to do it with the polymorphic. Here's my polymorphic serializer's definition class ResponsePolymorphicSerializer(PolymorphicSerializer): model_serializer_mapping = { models.FreeTextResponse: FreeTextResponseSerializer, models.ShortTextResponse: ShortTextResponseSerializer, I'd gladly appreciate some guidance on this. Thanks. -
How to use memray with Gunicorn and Django?
I have a project with Django and I did a multiread with Gunicorn. but my project has a memory leak. I want to monitor memory with "memray" but I don't know how to use "memray". -
Form not submitting to database in Django
I have created a form in Django and the information from this form must be registered in the database. But I have a problem. The information is not recorded in the database. I guess it's the JavaScript file that's blocking it. I remove the JavaScript file and the form works fine. But I don't want to remove the JavaScript file. How can I solve this problem? views.py def index(request): if request.POST: fname_lname = request.POST.get('name') number = request.POST.get('number') newForm = models.Form(fname_lname=fname_lname, number=number) newForm.save() return render(request, 'index.html') return render(request, 'index.html') model.py class Form(models.Model): fname_lname = models.CharField(max_length=50) number = models.IntegerField(max_length=15) send_date = models.DateTimeField(auto_now_add=True) index.html <div class="formbg"> <div class="formcolor"> <form class="forminput" method="post" action="/"> {% csrf_token %} <div class="label"> <label class="labels">Ad və Soyadınız <span>:vacibdir</span></label> <div class="input"> <input name="name" required type="text" class="inputs" /> </div> </div> <div class="label"> <label class="labels">Telefon nömrəniz <span>:vacibdir</span></label> <div class="input"> <input name="number" required type="number" class="inputs" /> </div> </div> <div class="formbut"> <button type="submit" class="btnsubmit">Göndər</button> </div> </form> </div> </div> </div> </div> <!-- SECTION19 --> <!-- SECTION20 --> <div class="security"> <i class="fa-solid fa-lock"></i> <p>SİZİN MƏLUMATLAR YADDAŞDA QALMIR VƏ 3-CÜ TƏRƏFƏ GÖSTƏRİLMİR</p> </div> <!-- SECTION20 --> <!-- SECTION21 --> <div class="finish"> <p>Məxfilik siyasəti</p> <h1>* - Q7 GOLD KİŞİ GÜCÜNÜN FORMULU</h1> </div> <!-- SECTION21 --> <script src="{% static … -
Django not redirecting to the web page
I am creating a messaging application in django with a built-in DLP system. I want to redirect to a web page when a sensitive word is detected in the message. But the webpage is not being redirected to. It is showing in the terminal but not on the front-end. In consumers.py async def chat_message(self, event): message = event['message'] username = event['username'] if (re.findall("yes|Yes", message)): response = await requests.get('http://127.0.0.1:8000/dlp/') print('message') else: await self.send(text_data=json.dumps({ 'message': message, 'username': username })) The output in the terminal WebSocket CONNECT /ws/2/ [127.0.0.1:32840] HTTP GET /dlp/ 200 [0.00, 127.0.0.1:32842] message -
Django doesn't create session cookie in cross-site json request
I want to make cross-site JavaScript call from third-party domain (in this case my desktop/localhost server) to my remote Django server hosted on my_domain.com/ and calling REST WS exposed on my_domain.com/msg/my_service with using session/cookies for storing session state. But when I call this service (hosted on remote Django server) from my desktop browser or localhost Django server (JS is in index.html), Django doesn't create session cookie and on remote server are doesn't store session state. But when i call this service from Postman or from same localhost JS to localhost instance of same Django service it works and session is created. My JS script in index.html which make call to WS send_message: fetch('http://my_domain.com/ws/my_service', { method:"POST", credentials: 'include', body:JSON.stringify(data) }) .then(res => res.json()) .then(json => { showResponse(json.message); }) When I run this script from my desktop browser or my localhost server it runs correctly with cookies and sessions parameters. Django my_service implementation view @csrf_exempt def my_service(request): if request.method == "POST": message_bstream= request.body request.session.set_expiry(0) message= json.loads(message_bstream) out,sta=state_machine_response(message["message"],int(request.session["state"])) request.session["state"] =sta respo={"message":out} response = HttpResponse(json.dumps(respo), content_type="application/json") response.set_cookie(key='name', value='my_value', samesite='None', secure=True) #return JsonResponse(respo, safe=False, status=200) return response else: return HttpResponseNotFound ("Sorry this methode is not allowed") Or I try generate response like return JsonResponse(respo, safe=False, … -
Django Framework: Reading Data from MSSQL-Database directly? Or import the dataset to sqlite3?
I would like to build an admin dashboard in Django framework. So far I have only worked with sqlite3 databases in Django. However, the admin dashboard should read statistics from an MSSQL database and display them accordingly. (Sales figures as a graph, other sales in a table, etc.) The turnover figures are very extensive. There are several thousand entries per month and the client would like to be able to filter by any date period. Only data from the MSSQL database should be read. Writing or updating the data is not desired. So far this is no problem, but I wonder what is the better solution to implement the project. Should I connect the MSSQL database directly to Django or should I read the MSSQL database in certain intervals and cache the "results" in a sqlite3 database? Caching seems to me to be the nicer solution, as we don't need real-time data and the performance of the MSSQL server might not suffer as a result. But I would have to build an additional connector to transfer the data from MSSQL to sqlite3. How would you approach such a project? Short version: I´d like to display data in django-framework App, should … -
How to nest models fields under another key for serializer
I have this type of Post model class Post(models.model): id = models.UUIDField(primary_key=True, default=uuid4) user = models.ForeignKey(UserProfile, null=True, on_delete=models.CASCADE) tags = models.ManyToManyField("Tags", blank=True, related_name="posts") title = models.CharField(max_length=200) body = RichTextField(blank=True, null=True) post_views = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True, verbose_name=("created_at")) in the serializer, I want to nest title, body, created_at under another key named article serializers.py class ArticleSerializer(serializers.ModelSerializer): title = serializers.CharField() content = serializers.CharField(source="body") created_at = serializers.CharField() class Meta: model = Post fields = ("title", "body", "created_at") class PostSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField(slug_field="email", read_only=True) article = ArticleSerializer(required=True) tags = TagSerializer(many=True, required=False) post_views = serializers.IntegerField(read_only=True) def to_representation(self, instance): data = super().to_representation(instance) cat = data.pop("category") title = data.pop("title") content = data.pop("body") created_at = data.pop("created_at") data["categories"] = cat data["article"] = {"title": title, "content": content, "created_at": created_at} return data class Meta: model = Post fields = "__all__" views.py class ArticleView(APIView): def get_object(self, pk: int): try: if pk: return Post.objects.filter(pk=pk, draft=False) return Post.objects.filter(draft=False) except Post.DoesNotExist: raise Http404 def get(self, request: Request, pk=None): post = self.get_object(pk) serializer = PostSerializer(post, many=True) return Response(serializer.data) The error that I'm getting AttributeError: Got AttributeError when attempting to get a value for field `article` on serializer `PostSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Post` instance. … -
" pip install django-deep-serializer" doesn't work
I keep trying to install django-deep-serializer but I keep on getting this error. I have uninstalled python and reinstalled it already. I currently have python 3.10.4 and pip is 22.0.4 Defaulting to user installation because normal site-packages is not writeable WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))': /simple/django-deep-serializer/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))': /simple/django-deep-serializer/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))': /simple/django-deep-serializer/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', ConnWARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))': /simple/django-deep-serializer/ ERROR: Could not find a version that satisfies the requirement django-deep-serializer (from versions: none) ERROR: No matching distribution found for django-deep-serializer -
wich type of modele in django for this form of values?
I want to create a model in my django app for this value, in this value we have ";" : 0;-0.0110227457430789;-0.0117428254241928; how can corige me please ? value = models.CharField(max_length=1000, blank=True, null=True) -
Django IsAuthenticated views always return 403
I have various views and viewsets, when I add the IsAuthenticated permission class I always get the 403 forbidden error Response { "detail": "You do not have permission to perform this action." } In views @api_view(["GET"]) @permission_classes([IsAuthenticated]) def protected_profile(request): In viewsets permission_classes = [IsAuthenticated] When I remove this class my requests work I've even checked if request.user.is_authenticated it returns true. It was working few hours back, I've reverted to previous git commits and now the problem continues to persist, my JWT is right as well. I'm on Django 3.2.3 and channels 3.0.3 if that helps. Any help would be appreciated. Edit: the same deployment works fine on heroku. So, I've dropped the DB locally restarted everything but its still the same. -
'WSGIRequest' object has no attribute 'is_ajax' in django 4
i had built a website with django 3 and i updated it to django 4 since this update i get this error I need help to solve this problem, thank you 'WSGIRequest' object has no attribute 'is_ajax' this is my views views.py def SingleBlog(request, Slug): post = get_object_or_404(Blog, Slug=Slug, Status="p") comments = BlogComment.objects.filter(Post=post, Reply=None, Status="p") is_liked = False if post.Like.filter(id=request.user.id).exists(): is_liked = True if request.method == 'POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid: content = request.POST.get('Text') reply_id = request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = BlogComment.objects.get(id=reply_id) comment = BlogComment.objects.create(Post=post, User=request.user, Text=content, Reply=comment_qs) comment.save() # return HttpResponseRedirect(post.get_absolute_url()) else: comment_form = CommentForm() context = { 'object': post, 'comments': comments, 'is_liked': is_liked, 'comment_form': comment_form, } if request.is_ajax(): html = render_to_string('partial/comments.html', context, request=request) return JsonResponse({'form': html}) return render(request, 'blog-single.html', context) def post_like(request): # post = get_object_or_404(Blog, id=request.POST.get('post_id')) post = get_object_or_404(Blog, id=request.POST.get('id')) is_liked = False if post.Like.filter(id=request.user.id).exists(): post.Like.remove(request.user) is_liked = False else: post.Like.add(request.user) is_liked = True context = { 'object': post, 'is_liked': is_liked, } if request.is_ajax(): html = render_to_string('partial/like_section.html', context, request=request) return JsonResponse({'form': html}) thank you -
how to read with Jquery and element readonly for django
Object1 see the image plx there are some readonly field that i set up on django, but i want to read the values using Jquery but really idk how to do it, i want to do it cuz depending of the value that is set on field "tipo" i want a make some values visibles or not. let tipo_persona_check = function(){ if ($('#id_tipo').val() == 'fisica'){ $('.field-empresa').hide(); $('label[for=id_persona').text('Suscriptor'); }else{ $('label[for=id_persona').text('Apoderado'); $('.field-empresa').show(); } in this case im hidding or showing field empresa depending of the value of id_tipo, but when it is on readonly, this id not exist, there is just a span class called readonly (for all readonly) with the value, but idk how to get from it, i need to know if the value is "fisica" or another from the readonly field tipo, to do things. any ideas? -
Import "knox.models" could not be resolved
im trying to import knox.models in my views.py file but i get error "Import "knox.models" could not be resolved" , i have installed knox and add it to my app settings but still got the same error -
RuntimeError: Model doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I am writing an app in Django and I'm trying to do some unit testing but I can't seem to find why the test is failing that is the test page: import re from django.test import TestCase from django.urls import reverse from . import models class BasicTests(TestCase): def test_firstname(self): print('test11') acc = models.Accounts() acc.first_name = 'Moran' self.assertTrue(len(acc.id) <= 9, 'Check name is less than 50 digits long') self.assertFalse(len(acc.id) > 50, 'Check name is less than 50 digits long') the error i get is : RuntimeError: Model class DoggieSitter.accounts.models.Accounts doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS thats my installed app: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts' ] -
Getting has_permission() missing 1 required positional argument: 'view' instead of JSON Response
Getting has_permission() missing 1 required positional argument: 'view' instead of JSON Response from rest_framework import filters from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated from apps.fm.models.asset import Asset from apps.fm.serializers import AssetSerializer from django.shortcuts import render, redirect from django.urls import reverse class AssetViewSet(viewsets.ModelViewSet): model = Asset serializer_class = AssetSerializer permission_classes = [IsAuthenticated] filter_backends = [filters.SearchFilter, filters.OrderingFilter] search_fields = ['name'] ordering_fields = ['id'] ordering = ['-id'] def get_permissions(self): uagent = ['Chrome','Firefox'] if self.request.user_agent.browser.family in uagent: return [] return [IsAuthenticated] def retrieve(self, request, *args, **kwargs): instance = self.get_object() uagent = ['Chrome','Firefox'] if self.request.user_agent.browser.family in uagent: authentication_classes = [] #disables authentication permission_classes = [] #disables permission return redirect(reverse("feedback")+"?type=Asset&id="+str(instance.id)) serializer = self.get_serializer(instance) return Response(serializer.data) def get_queryset(self): queryset = self.model.objects.all() return queryset -
How to create different database tables for user types in Django?
Here is what I am trying to do. The project has Two Type of users: Spot Owners Spot Rentee Owners can add slot, Rentees can book slot. Here is my code: models.py: class UsersManager(BaseUserManager): def create_user(self, nid, password=None): if not nid: raise ValueError('Users must have an nid address') user = self.model( nid=self.normalize_email(nid), ) user.set_password(password) user.save(using=self._db) return user class Users(AbstractBaseUser): user_type = ( ('R', 'Rentee'), ('S', 'Spot Owner'), ) nid = models.CharField(max_length=30, unique=True, primary_key=True) name = models.CharField(max_length=200) email = models.CharField(max_length=200) password = models.CharField(max_length=128) contact = models.CharField(max_length=15, null=True) last_login = models.DateTimeField(auto_now_add=True, null=True) is_spot_owner = models.CharField(max_length=10, choices=user_type,default='user') USERNAME_FIELD = 'nid' objects = UsersManager() def __str__(self): return self.nid class SpotOwner(Users,models.Model): owner_info = models.CharField(max_length=200) def __str__(self) -> str: return self.nid.nid class Rentee(models.Model): nid = models.ForeignKey(Users, on_delete=models.CASCADE) vehicle_type = models.CharField(max_length=200) rentee_credit = models.IntegerField() def __str__(self): return self.name forms.py: class UserForm(ModelForm): class Meta: model = Users fields = '__all__' class RenteeForm(ModelForm): class Meta: model = Rentee fields = '__all__' views.py: def signup(request): form = UserForm(request.POST) print("Errors",form.errors) if request.method == 'POST': print(request.POST) if form.is_valid(): user = form.save() user.set_password(request.POST.get('password')) user.save() nid = request.POST.get('nid') password = request.POST.get('password') user = authenticate(request, nid=nid, password=password) login(request,user,backend='django.contrib.auth.backends.ModelBackend') messages.success(request, 'User created successfully') return redirect('/') else: print("Form invalid") context = {'form': form} return render(request, 'home/signup.html',context=context) Now, … -
how to use variable in html templates django
I would to use the variable to setup name and age in my html files for app in Django. my code is: myapp\views.py from django.shortcuts import render # Create your views here. def test1(request): myname = 'abc' myage = 30 context = {'name': myname,'myage' : myage} return render(request,'index1.html',context) myapp\urls.py from django.urls import path from . import views urlpatterns = [ path('test1/',views.test1) ] myapp\templates\index1.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>thang1</title> </head> <body> <h1>this is template test1</h1> <p>I'm {{ myage }} years old</p> <p>My name is {{ myname }} </p> </body> </html> with above code, only get myold , it can not take myname. Can someone help assist me on this ? I would like to have both myname and my age in the html view. -
How i can add correctly data to an existing choicefield and save it in database: Django
I want to add some choices to an exiting fieldchoice from the database, I have did that in my views.py: if request.method == 'GET': form = FormOperation(instance=request.user, ) var = Metry.objects.filter(user=request.user).last().profile.name varr = Metry.objects.filter(user=request.user).last().profile.category form.fields['dite'].choices.append((varr, var)) print(form.fields['dite'].choices) models.py: dite = models.CharField(null = True, max_length=60,choices = CHOICES) forms.py: class FormOperation(forms.ModelForm): class Meta: model = Operation exclude = ("user",) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) after "append" the choice , As a test I have did a "print" to see the choice and it's normal i can see it in my terminal, but not in the page browser of my django application indeed ,i can see just the first choices without considering what i have append in my views.py,... Any help will be appreciated. -
importerror: cannot import name 'ungettext' from 'django.utils.translation'
I upgraded to django 4. I have realized that I get this error when Irun python manage.py runserver What did it change to??? importerror: cannot import name 'ungettext' from 'django.utils.translation' -
How to subtract values when product is added to shopcart
I have been successful when subtracting quantity of my product when an order is made. I have also been successful subtracting values for the user when product is added to shopcart. The problem is I cannot subtract the variant of the product. It says "Variants matching query does not exist." Here is my code. models.py class Product(models.Model): VARIANTS = ( ('None', 'None'), ('Size', 'Size'), ('Color', 'Color'), ) user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) #many to one relation with Category title = models.CharField(max_length=150) image = models.ImageField(null=False, upload_to='images/') price = models.DecimalField(max_digits=12, decimal_places=2,default=0) amount = models.IntegerField(default=0) variant = models.CharField(max_length=10, choices=VARIANTS, default='None') detail = RichTextUploadingField() slug = models.SlugField(null=False, unique=True) def __str__(self): return self.title class Variants(models.Model): title = models.CharField(max_length=100, blank=True,null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) color = models.ForeignKey(Color, on_delete=models.CASCADE,blank=True,null=True) size = models.ForeignKey(Size, on_delete=models.CASCADE,blank=True,null=True) image_id = models.IntegerField(blank=True,null=True,default=0) quantity = models.IntegerField(default=1) price = models.DecimalField(max_digits=12, decimal_places=2,default=0) def __str__(self): return self.title class ShopCart(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) variant = models.ForeignKey(Variants, on_delete=models.SET_NULL,blank=True, null=True) # relation with variant quantity = models.IntegerField() def __str__(self): return self.product.title views.py def product_detail(request,id,slug): query = request.GET.get('q') current_user = request.user category = Category.objects.all() product = Product.objects.get(pk=id) if product.variant != 'None': variantid = request.POST.get('variantid') # from variant add to cart checkinvariant …