Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I link a comment to its corresponding post in Django?
I am building a Django project where I have an index page that lists all posts. The user can click on the name of a post and this will take them to a detail page with the complete post information (date, content, category). This detail page also has a link that will take the user to a form where they can leave a comment. Once the user clicks submit they are supposed to navigate back to the post detail page and the comment is supposed to be there. The issue I am having right now is that the comment is being automatically assigned to the first post in the index list rather than the post the user had visited (I think this may have something to do with the current default setting in my models, but how else can I get the post id?). How can I make it so that the comment is assigned to its correct post? I have tried everything with the models and views but nothing seems to work. Thank you for your help, I think the solution to this might be simple but I can't find it anywhere. Here is my relevant models: class UserPost(models.Model): … -
After upgrading to Django 3.2 my annotations on `ArrayAgg` fields not working
I have a fairly complicated model method that worked perfectly before upgrading to Django 3.2.8. It looks like so: @classmethod def get_inbox_for_user(cls, user: User) -> 'models.QuerySet[ShareRequest]': user_principals_ids = list(user.principals.values_list('id', flat=True)) annotated_share_requests = cls._default_manager\ .annotate( registered_staff_ids=ArrayAgg( 'contact__registered_staffing__staff_user', distinct=True, ) )\ .annotate( primary_registered_staff_ids=ArrayAgg( 'contact__registered_staffing__staff_user', filter=models.Q(contact__registered_staffing__is_primary=True), distinct=True, ) ) filtered_shared_requests = annotated_share_requests\ .filter( (models.Q(primary_registered_staff_ids__isnull=True) & models.Q(registered_staff_ids__contains=[user.id])) | (models.Q(primary_registered_staff_ids__isnull=True) & models.Q(registered_staff_ids__overlap=user_principals_ids)) | models.Q(primary_registered_staff_ids__contains=[user.id]) | models.Q(primary_registered_staff_ids__contained_by=user_principals_ids) ) return filtered_shared_requests Skipping the details, the important part is my annotate statements and further filtering by them. From the example below, you can see that registered_staff_ids results in [None], which looks like a part of the problem: In [39]: annotated_share_requests.first().registered_staff_ids Out[39]: [None] I was able to remedy it by providing an additional filter to my annotate statement, turning that expression into: annotated_share_requests = cls._default_manager\ .annotate( registered_staff_ids=ArrayAgg( 'contact__registered_staffing__staff_user', filter=models.Q(contact__registered_staffing__staff_user__isnull=False), distinct=True, ) )\ ... Which now shows the result as: In [40]: annotated_share_requests.first().registered_staff_ids Out[40]: [] However, the further filtering (specifically __overlap and __contained_by lookups fail, for example: In [56]: annotated_share_requests.values_list('primary_registered_staff_ids', flat=True) Out[56]: <QuerySet [[], []]> # looks great In [57]: annotated_share_requests.values_list('registered_staff_ids', flat=True) Out[57]: <QuerySet [[], []]> # looks great In [58]: user_principals_ids Out[58]: [] # looks great # BUT! In [59]: annotated_share_requests.filter(registered_staff_ids__overlap=user_principals_ids) Out [59]: FieldError: Cannot resolve expression type, unknown … -
How to check unique bulk_create
In Django there is a method get_or_create guaranteeing the uniqueness of the object. But when records for adding a lot more 1000 processing takes a lot of time (as 1000 requests for the creation of objects). I know about bulk_create, but it does not check on the uniqueness of the input attributes of the model. How do I speed up the addition of unique objects to the database? If possible in 1 request. Example model: models.py class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) admin.py # Create only one element (What I want to get) _, created = Person.objects.get_or_create(first_name='Leon', last_name='Mariano') _, created = Person.objects.get_or_create(first_name='Leon', last_name='Mariano') # Create 2 objects with different ID Person.objects.bulk_create(Person(first_name='Leon', last_name='Mariano'), Person(first_name='Leon', last_name='Mariano')) -
Django AJAX befor saving
Hi i'm new to django so any help is appreciated. I have a form that works, the inputs are filled and it is saved in the database. The problem is that I want to create a button "Process with Python" which if it is pressed, it must take an image that was uploaded in an input file and send this photo to get information from the same photo and then return to the form and fill in the rest of what I input with what came out of that function. Someone told me to use ajax for that. but I do not know how. how can I do this? -
Django - POST endpoint to update multiple tables. Return response with all relevant data
I have this POST endpoint below that creates a post. When a post is created the request can be accompanied by video and images. As you can see below a serializer handles the post data outside of images and video, because I need to do validation on the image and video. The response returns the data serialized, but only everything not related to image and video. I'd like the response to also return stuff like image and video url, uuid. How can I do this with the newly created post_obj? view.py @api_view(['POST']) def POST_create_post(request): serializer = PostSerializer(data=request.data) if serializer.is_valid(): try: post_obj = serializer.save() try: if 'images' in request.FILES.keys(): for img in request.FILES.getlist('images'): validate_image_upload(img) Photo.objects.create(post=post_obj, image=img) if 'video' in request.FILES.keys(): vid = request.FILES.get('video') validate_video_upload(vid) Video.objects.create(post=post_obj, video=vid) except ValidationError as e: return Response(dict(error=e, user_message=error_message_generic), status=status.HTTP_400_BAD_REQUEST) except django.db.utils.InternalError as e: return Response(dict(error=serializer.errors, user_message=error_message_generic), status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(dict(error=serializer.errors, user_message=error_message_generic), status=status.HTTP_400_BAD_REQUEST) serializer.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('creator', 'body', 'uuid', 'created', 'updated_at') models.py class Photo(AbstractBaseModel): post = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to=images_directory_path) @property def image_url(self): return self.image.url class Video(AbstractBaseModel): post = models.ForeignKey(Post, on_delete=models.CASCADE) video = models.FileField(upload_to=videos_directory_path) @property def video_url(self): return self.video.url -
Create custom permission for api view in django
I have a task object and a bid object. i am trying to add the permission in my api view that checks if the the same user that created the task is trying to create a bid for that task. if its the same user it shouldnt be allowed, a bid on the task should only be allowed by other users. To create a bid i use the example url https://my-app/api/bids/<str:task_id> so i can get the task the user is trying to create a bid on. currently in my permissions file i have this: class CheckTaskUserIsNotBidUser(permissions.BasePermission): """Check if the task user is the bid user""" def has_object_permission(self, request, view, obj): pass how can i retrieve the id of task from the request url so i can query the task model and check if its the user please. -
Is it possible to rebuild a single tree?
I can only find documentation for Model.objects.rebuild() which rebuilds all trees. What if I wanted to rebuild a single tree? Is that possible? If it's not possible - does that mean using move_node or insert_node results in rebuilding for all trees? -
File upload stops when it started
I developed a video upload page on a web site. Whe I try to upload a video file smaller than ~100mb everything works perfect but if I try to upload a larger file, the upload process stops at the beginning and continues after a couples minutes. I'm using Hetzner (Ubuntu 18) for my production server and DigitalOcean(Ubuntu 20) for staging. In the staging file uploading process doesn't care the file size. it's works like a charm, but in the production server the upload stops at the begining. Both servers has the same configuration (i handle the deployment and server configs with an Ansible script). They works on the same code, they have same nginx, supervisor and gunicorn configs but in the production server the upload stops. I've tried a lot of different structures in javascript, but nothing changed. Staging works, production fails. The only difference between two server is Ubuntu version but I don't think OS version would be an issue for a simple file upload. Here's my console.log output for the upload progress. You can see there are a lot of time between first and second output. Any ideas? -
Expected number but got ''
I have a form like this class MacaForm(forms.ModelForm): maca = forms.ChoiceField(required=False,choices=Maca.MacaChoices.choices, widget=forms.RadioSelect(attrs={'class': 'maca'}), initial=1) and a model like this class Maca(models.Model): class MacaChoices(models.IntegerChoices): maca1 = 1, maca2 = 2, But sometimes I hide this field, so this field is not render. But when I try to submit I got this error Expected number but got '' Can someone help me out to solve this problem? -
Edit View of a Django ModelFormset
I am creating an expense record application which has two forms. A normal modelform class ExpenseCreateForm(forms.ModelForm): expense_description = forms.CharField(widget=forms.Textarea(attrs={'rows': 3})) class Meta: model = models.Expense fields = ['expense_title', 'expense_description', 'expense_requester', 'expense_VAT', 'expense_discount', 'expense_sub_total', 'expense_total'] A modelformset_factory: class ItemCreateForm(forms.ModelForm): quantity = forms.DecimalField(required=False) amount = forms.DecimalField(required=False) class Meta: model = models.ExpenseItemModel can_delete = True, fields = ['item_name', 'item_price', 'item_link', 'quantity', 'amount'] ItemCreateFormset = modelformset_factory( models.ExpenseItemModel, form=ItemCreateForm, can_delete=True, extra=0, ) Below is my create page - the first 3 fields represent the normal model form and the next 2 rows can be added dynamically with jquery. Everything working fine and model instances submitting to the DB For my edit view, I was able to display the modelform instance as shown below my issue lies in displaying the instances of the modelformset_factory below is my edit view class DetailExpense(View): template = 'expense/expense_detail.html' def get(self, request, expense_id, company_slug): expense_record = models.Expense.objects.select_related('expense_requester').prefetch_related( 'expense_item').get(pk=expense_id) #expense_record_items = get_object_or_404(models.ExpenseItemModel,) editable = True expense_item_form = formset_factory(forms.ItemCreateForm) expense_form = forms.ExpenseCreateForm(instance=expense_record) context = { 'expense_record': expense_record, 'editable': editable, 'expense_item_form': expense_item_form, 'expense_form': expense_form, } return render(request, template_name=self.template, context=context) -
How to use Django roles for a SaaS product with an admin portal?
I would try to explain our desired product idea as clear as possible but feel free to ask further questions. So, basically what we want to build is a SaaS product that will be used by multiple clients. For now, we're not interested in custom domains like (cust1.myproduct.com, cust2.myproduct.com) and we will simply be using one database to manage all customers' data. So far so good. Our SaaS product will be sold to enterprise organizations which will then be used by their employees. So for any one customer organization, there are three types of roles that we would like to provide their users, as follows: Admin: An organization's admin that should be able to do all the settings for that particular organization Manager: An organization's manager that can manage the users that are under his/her team Employee: A normal user with bare minimal permissions that can only manage his own data Now, to provision customers for this SaaS product and to set their global settings (e.g. maximum allowed users, license type etc), we also plan to create an admin portal and APIs that will be used by our internal employees only. For this portal, we also want to define roles … -
VPS is unaccessible through ssh and cant connect website
the problem is the connection to my vps is lost on daily basis multiple times like 20 mins. When the server is down i can't connect website so i get the error: Err connection timed out. and i try connecting through ssh and it outputs a log: Connection refused. Nothing more nothing less i should solve this because it causes lots of trouble the only solution i came up with its restarting from the server provider site. But this happens frequently not one in a month or a year it happens 10 times a day. How should i debug the problem or how can i find a real solution. Any help is appreciated. Thanks. -
NoReverseMatch at /project/836d5772-26da-4a9b-811c-806af5b10a41/
.I got this error on the projects page; Reverse for 'edit-project' with arguments '('',)' not found. 1 pattern(s) tried: ['edit\-project/(?P[^/]+)/$']. I'm trying to create an edit view for the projects My views.py from django.shortcuts import render, redirect from .models import Project, Skill from .forms import ProjectForm # Create your views here. # rendering our home template def homePage(request): projects = Project.objects.all() skills = Skill.objects.exclude(body="") otherSkills = Skill.objects.filter(body="") context = { "Projects": projects, "Skills": skills, "Others": otherSkills, } return render(request, "base/home.html", context) # creating a view for the projects template def projectsPage(request, pk): project = Project.objects.get(id=pk) # querying the object by its id context = { "Project": project, } return render(request, "base/projects.html", context) # creating a view for project_form template def addProject(request): form = ProjectForm() # If request method is equal to POST, submit this form if request.method == "POST": # pass in the original post data and any files send from the frontend(we're sending files right to enctype) form = ProjectForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("home") context = { "Form": form, } return render(request, "base/project_form.html", context) # creating a view for project_form template def editProject(request, pk): project = Project.objects.get(id=pk) form = ProjectForm(instance=project) if request.method == "POST": form = ProjectForm(request.POST, … -
How to set an owner of created object by default in DRF?
I want to save my car object with request.user as owner (field in Car model). My code: views.py class CarViewSet(viewsets.ModelViewSet): serializer_class = CarSerializer queryset = Car.objects.all() lookup_field = 'slug' permissions_classes = [IsAuthenticated] def perform_create(self, serializer): serializer.save(owner=self.request.user) def get_queryset(self, *args, **kwargs): print(self.request.user.email) print(self.request.user.is_authenticated) return self.queryset.filter(owner=self.request.user.pk) When I visit my frontend page, I have a list of my cars displayed. email and is_authenticated (True) fields are printed correctly. Everything is ok until I try to refresh the page - the data disappears and I get an error: print(self.request.user.email) AttributeError: 'AnonymousUser' object has no attribute 'email' is_authenticated field is set to False respectively. I have also tried including owner field to CarSerializer: owner = serializers.HiddenField(default=serializers.CurrentUserDefault()) But nothing changed. How can I fix that? -
ValueError("No text section for incoming WebSocket frame!") Swift to DRF
Im trying to make a realtime messaging app using swift and django's rest framework. To make the app 'real time', I am incorporating Django channels. Right now when I send message data to my consumer, I get the error ValueError("No text section for incoming WebSocket frame!") Here is my django code: class MessageConsumer(AsyncJsonWebsocketConsumer): #connect to client async def connect(self): await self.accept() await self.send_json(content="Pong") query_string = self.scope['query_string'] self.conversation_id = int(query_string[16:].strip()) self.new_group_name = 'Conversation_' + str(self.conversation_id) await self.channel_layer.group_add(self.new_group_name, self.channel_name) # all_msgs = await self.get_conversation_messages() # await self.send_json(content=all_msgs) @database_sync_to_async def get_conversation_messages(self): conversation = Conversation.objects.get(conversation_id=self.conversation_id) messages = conversation.message_set.all() serializer = GetMessagesSerializer(messages,many=True) return serializer.data @database_sync_to_async def send_message(self, data): serializer = SendMessageSerializer(data=data) if serializer.is_valid(): serializer.save() return serializer.data raise ValueError('serializer is not valid') async def receive_json(self, content): serialized_message = await self.send_message(data=content) await self.send_json(content=serialized_message) async def disconnect(self, code): await self.channel_layer.group_discard(self.new_group_name, self.channel_name) await self.close() Here is my swift code: private func encodeMessageData(_ data: SendMessageStruct) -> Data? { guard let encodedData = try? JSONEncoder().encode(data) else { print("failed to encode message data") return nil } return encodedData } let webSocketMessage = URLSessionWebSocketTask.Message.data(encodedData) webSocketTask.send(webSocketMessage) { error in guard error == nil else { if let error = error { print("error in websocket task ERROR: \(error.localizedDescription)") } completion(.failure(AuthErrors.taskFailed)) return } print("sent websocket data") … -
can not upload image using Django-CKEditor (Error 400)
when I want to upload an image in CKEditor, it gives me the Error "HTTP error occurred during file upload (error status: 400)." enter image description here inside urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls import url from django.conf.urls.i18n import i18n_patterns from django.conf.urls.static import static urlpatterns = i18n_patterns( url(r'^admin/clearcache/', include('clearcache.urls')), path('admin/', admin.site.urls), path('', include('frontpages.urls')), path('ckeditor/',include('ckeditor_uploader.urls')), path('i18n/', include('django.conf.urls.i18n')), prefix_default_language=False, ) handler404='frontpages.views.error_404_view' if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) inside settings.py ---> for CKEDITOR #Ckeditor CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_UPLOAD_PATH="uploads/" CKEDITOR_CONFIGS={ 'myconfig':{ 'toolbar':"Custom", 'toolbar_Custom':[ ['Styles','Format','Font','FontSize','BidiLtr','BidiRtl'], ['JustifyLeft','JustifyCenter','JustifyRight','NumberedList', 'BulletedList','Bold','Italic','Underline','Strike','Undo','Redo'], ['Link','Unlink','Anchor'], ['TextColor','BGColor'], ['Smilely','SpecialChar'], ['Source','Scayt','Maximize'], ['Table','Templates','Iframe'], ], 'height': 100, }, } would you please help me with that -
How can I use function based view to make operations in a object with a modal?
I'm creating a website with a list of candidates where staff members can increment the grade of candidates by clicking in validate. I would like to increment the value of grade when I click on validate in the modal. It works because I can see in the admin panel that the grade of the candidate has been incremented but it does not redirect me in the list of candidates that was before. How can I do to redirect to the list of candidates that was before ? Here is the template displaying the list of candidates and the script displaying the modal : <table id="students-table" class="table"> <thead> </thead> <tbody> {% for student in student_list %} <tr> <td> <button type="button" class="validate-student bs-modal btn btn-sm btn-primary" data-form-url="{% url 'students:validate_grade' student.pk %}"> <span class="fa fa-eye"></span> </button> </td> </tr> {% endfor %} </tbody> <script type="text/javascript"> $(function () { $(".validate-student").each(function () { $(this).modalForm({ formURL: $(this).data("form-url")}); }); }); Here is the modal : {% load widget_tweaks %} <form method="POST" action=""> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel"><strong>{{ student.user.firstname }} {{ student.user.lastname }}</strong></h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p>Are you sure to validate this candidate ? ? </p> </div> <div class="modal-footer"> <button type="submit" … -
Image print issue in HTML using Django
I have recently started working with Python Django. I created a home page and it worked fine. But now I created another html template product.html and followed the same steps but the images weren't loading even though both the html files were in the same directory. I tried printing image product-1.jpeg in home page and it worked but in the other html page it isn't working. All the CSS are working fine. I don't know what am I doing wrong here. product.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>Document</title> <link rel="shortcut icon" type="image/png" href='{% static "images/favicon.ico" %}'/> </head> <body> <p style="color:red;">Hello</p> <img src="static/images/product-1.jpeg" alt="Product 1"/> </body> </html> Terminal Response It's showing Product/static/images/product-1.jpeg but what I typed was static/images/product-1.jpeg I don't know where's the error. [17/Oct/2021 00:42:21] "GET /Product/ HTTP/1.1" 200 416 Not Found: /Product/static/images/product-1.jpeg [17/Oct/2021 00:42:21] "GET /Product/static/images/product-1.jpeg HTTP/1.1" 404 2899 [17/Oct/2021 00:42:22] "GET /static/images/favicon.ico HTTP/1.1" 200 15406 [17/Oct/2021 00:49:31] "GET /Product/ HTTP/1.1" 200 442 Website Display Web Page View Let me know, if I need to upload other codes (urls.py, views.py, settings.py, etc. Btw home.html was working fine) -
How can i send mail to class values
how can I send the field information in my form on django as an e-mail at the same time? def gcreate(request): if request.method == 'POST': gmember = gunluk( adsoyad=request.POST['adsoyad'], adsoyad2=request.POST['adsoyad2'], vardiya=request.POST['vardiya'], aciklama=request.POST['aciklama'], incident=request.POST['incident'], alinanaksiyon=request.POST['alinanaksiyon'], ulasilmayanekip=request.POST['ulasilmayanekip'], ulasilmayanbilgisi=request.POST['ulasilmayanbilgisi'],) try: gmember.full_clean() except ValidationError as e: pass gmember.save() messages.success(request, 'Ekleme İşlemi Başarılı!') return redirect('/gunlukistakibi') else: return render(request, 'gcreate.html') -
queries of Foreinkey
i am currently trying to make a django project but i am stuck class Klasse(models.Model): klasse = models.CharField(max_length=60, null=True) def __str__(self): return self.klasse class Lehrer(models.Model): Name_und_Nachname = models.CharField(max_length=200, null=True) Klassenlehrer_von = models.ForeignKey(Klasse, max_length=200, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.Name_und_Nachname class Schüler(models.Model): name_und_Nachname = models.CharField(max_length=200, null=True) Klasse = models.ForeignKey(Klasse, max_length=200, null=True, on_delete=models.SET_NULL) Klassenlehrer = models.ForeignKey(Lehrer, max_length=200, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name_und_Nachname class Punkte(models.Model): punkte_ang = (("0", 0),("1", 1), ("2", 2), ("3", 3), ("4", 4), ("5", 5)) punkte_norm = (("0", 0),("1", 1)) Soziales_angagement = models.CharField( max_length=200, null=True, choices=punkte_ang,) Lernverhalten = models.CharField(max_length=200, null=True, choices=punkte_norm, ) Sozialverhalten = models.CharField(max_length=200, null=True, choices=punkte_norm,) konfliktlösung = models.CharField(max_length=200, null=True,choices=punkte_norm, ) eingentum_anderer = models.CharField( max_length=200, null=True, choices=punkte_norm,) date_created = models.DateTimeField(auto_now_add=True, null=True) so to the code i wanna say i know its not the most beautiful and not the best one. So back to my question i need a way to connect the foreinkeys betwen the students = Schüler and the Teachers = Lehrer i thaught i could make this with querying the Klasses and if the student and the teacher have the same class they get linked. is there any way to do this? -
Django problem accessing a field from view in the autocomplete
I'm using django-autocomplete-light in my project, but I'm with some problems passing an argument from my view (the argument is also in my URL) to the autocomplete Select2QuerySetView. What is the correct way to do it? My view has a period_id that I'm passing to my form by this way: def add_equipment_config(request, tower_id, period_id): ... form = EquipmentConfigForm(period_id=period_id) ... return render(request, 'add_equipment_config.html', {'form': form, 'tower_id': tower_id, 'period_id': period_id, 'conf_period': conf_period}) In my form I get the period_id inside the init: class EquipmentConfigForm(ModelForm): class Meta: model = EquipmentConfig fields = '__all__' period_id = 0 def __init__(self, *args, **kwargs): period_id = kwargs.pop('period_id') ... calibration = forms.ModelChoiceField( queryset=Calibration.objects.all().order_by('-id'), widget=autocomplete.ModelSelect2(url='calibration-autocomplete', forward=['period_id'], attrs={'style': 'width:100%'}) ) But I'm not able to pass the period_id inside the forward. Inside the Select2QuerySetView I'm always getting the value as None: class CalibrationAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): print(self.forwarded.get('period_id', None)) // Here I get None ... Can someone please help me with this? How can I get the period_id inside the Select2QuerySetView? Im struggling to find this solution. -
Django REST (DRF) - How to setup nice execptions in api_views?
I have the following API view and serializer to change a users password: views.py @api_view(['POST']) @permission_classes([AllowAny]) def user_create(request): exception_handler = UserUnavailable success_handler = UserCreated if request.method == 'POST': creation_serializer = UserCreateSerializer(data=request.data) try: if creation_serializer.is_valid(raise_exception=True): creation_serializer.save() user_serializer = NewUserSerializer(instance=creation_serializer.instance) return JsonResponse( {"status_code": success_handler.status_code, "default_detail": success_handler.default_detail, "default_code": success_handler.default_code, "new_user": user_serializer.data, }, status=status.HTTP_201_CREATED, safe=False) except APIException: return Response( {"status_code": exception_handler.status_code, "default_detail": exception_handler.default_detail, "default_code": exception_handler.default_code}, status=status.HTTP_400_BAD_REQUEST ) serializers.py class UserPasswordSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) password = serializers.CharField(max_length=128, write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(max_length=128, required=True) old_password = serializers.CharField(max_length=128, required=True) class Meta: model = get_user_model() fields = ('user', 'password', 'password2', 'old_password') extra_kwargs = {'password': {'write_only': True}} def validate_old_password(self, value): user = self.context['request'].user if not user.check_password(value): raise serializers.ValidationError( ({'old_password': _("Your old password was entered incorrectly. Please enter it again..")}) ) return value def validate(self, data): if data['password'] != data['password2']: raise serializers.ValidationError({'password2': _("The two password fields didn't match.")}) password_validation.validate_password(data['password']) return data def save(self, **kwargs): password = self.validated_data['password'] user = self.context['request'].user user.set_password(password) user.save() return user If I update a users password I simply get back http200 and the password has been set, nice! But if I send the same request a second time I just get back: { "status": "error", "error": "Bad Request" } Actually I would expect to … -
Conditional rendering of the Bookmark Button in React + Django Rest Framework
Hello? I am working on an ecommerce project and I want to render the Bookmark button conditionally to display that if a user saves a product the Bookmark button innerHTML changes from "Not Saved" to "Saved" in the frontend (React). The backend (Django) is working and user's bookmarks are being saved in the backend. In React I have used the following approach. {product.bookmarks && product.bookmarks.find(bookmark => bookmark.id === user.id) ? <p>Saved</p> : <p>Not Saved</p>} So it matches the Bookmark ID with the logged User's ID. The button is working and if a user saves a product it returns "Saved" in the frontend and if not saved it returns "Not Saved". Is this the best approach to use or there's a better method? I have also tried this approach in Django and it returns the data but I'm not sure how to use the data in React to render the button. @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def add_bookmarks(request, id, *args, **kwargs): saved = bool product = get_object_or_404(Product, id=id) if product.bookmarks.filter(id=request.user.id).exists(): saved = False product.bookmarks.remove(request.user) else: saved = True product.bookmarks.add(request.user) data = { 'saved': saved } print(data) return Response(data, status=status.HTTP_200_OK) -
Django: counts forms submitted
What I'd like to do with my model is to have and HTML page where to show my users how many question form they have submitted and how much they are still missing (I've five in my original template here I'm repoprting only two) and also for the admin to see how many users in total submitted the forms so this is my code: **HTML** {% extends "base.html" %} {% block content %} <main> <div class="container"> <div class="table-responsive text-nowrap"> <h2>Submission</h2> Total: {{ quest_done }}/2 {% if user.is_superuser %} Total Question 1: {{ question1_count }} Total Question 2: {{ question2_count }} {% endif %} </div> </main> {% endblock %} **question.models.py** class QuestionOne(models.Model): user = models.OneToOneField(UserInformation, blank=True, null=True, on_delete=models.CASCADE) question_1a = models.CharField(max_length=250, choices=point) question_2a = models.CharField(max_length=250, choices=point) question_3a = models.CharField(max_length=250, choices=point) quest_1_submitted = models.BooleanField(default=False) def __str__(self): return self.name + '_question_1' class QuestionTwo(models.Model): user = models.OneToOneField(UserInformation, blank=True, null=True, on_delete=models.CASCADE) question_1b = models.CharField(max_length=250, choices=point) question_2b = models.CharField(max_length=250, choices=point) question_3b = models.CharField(max_length=250, choices=point) quest_2_submitted = models.BooleanField(default=False) def __str__(self): return self.name + '_question_2' **question.views.py** quest_done = 0 quest_count = 0 def question_one(request): if request.method == 'POST': form = QuestionOneForm(request.POST, request.FILES) if form.is_valid(): questionnairename.quest_1_submitted = True question1_count = QuestionOne.objects.all().count() form.instance.user = request.user form.save() messages.success(request, 'Form submitted') if … -
?: (urls.E006) The STATIC_URL setting must end with a slash
I was trying to migrate my new schema for my database in django when I got this error: AttributeError: 'PosixPath' object has no attribute 'startswith' I looked online and I saw that if you wrap your paths with str(), the error goes away. But then I got this error: ?: (urls.E006) The STATIC_URL setting must end with a slash. I tried doing the obvious thing and changing STATIC_URL = BASE_DIR.parent / "svelte" / "public"(what I think was causing the error) That didn't work, so I tried STATIC_URL = BASE_DIR.parent / "svelte" / "public" /. That also didn't work, so know I need help.