Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting list from Many to One Relationship Django
I have two models like these: class User(models.Model): id = models.AutoField(primary_key=True) username= model.CharField(max_length=25) class Book(models.Model): id = models.AutoField(primary_key=True) book_name = models.CharField(max_length=25) created_by = models.ForeingKey(User, on_delete=models.CASCADE) Then, I have a rest api with json for getting all books. def get_book_list(request): queryset = Book.objects.all() return JsonResponse({ 'result_list' : list(queryset.values()) }) Now, this api returns json like this: { "result_list" : [ { "id" : 1, "book_name" : "A-Book", "created_by_id" : 1}, { "id" : 2, "book_name" : "B-Book", "created_by_id" : 1}, { "id" : 3, "book_name" : "C-Book", "created_by_id" : 1} ] } I have user that id is 1, username is "Test". But, api does not return foreign key user object. Why? Is it possible to getting list like this ? : { "result_list" : [ { "id" : 1, "book_name" : "A-Book", "created_by" : { "id" : 1, "username" : "Test"} }, { "id" : 2, "book_name" : "B-Book", "created_by" : { "id" : 1, "username" : "Test"} }, { "id" : 3, "book_name" : "C-Book", "created_by" : { "id" : 1, "username" : "Test"} } ] } Any suggestions? Thank you -
Django - Indentation Error - (Submitting form with an Image field) [duplicate]
I'm trying to get my head around forms in Django at the moment (Still at the early stages of learning) although, I have managed to successfully submit post content data through my form, but I'm struggling with getting an image to upload. class CreateNewPost(LoginRequiredMixin, CreateView): model = Post fields = ['content', 'image'] template_name = 'post/post_new.html' success_url = '/' @login_required def post_image(self, form): form=upload() if request.method == 'POST': form = upload(request.POST, request.FILES) return render(request, 'post/post_new.html', {'form': form}) def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data['tag_line'] = 'Create a new post' return data The error in which I receive is: IndentationError at /posts/ unindent does not match any outer indentation level (views.py, line 149) Thanks, Jay -
How do I specify the hostname of the callback uri when using python-social-auth?
I'm using python-social-auth inside Django, so social-auth-app-django to be exact. The application is only an API for a single page application that acts as the frontend. The server that serves the frontend proxies requests to the backend, to avoid any issues with CORS, third party cookies, etc. This means you visit example.com, the SPA loads and makes requests to example.com/api which gets proxied to api.example.com/api. example.com is a NodeJS simple server, and api.example.com is the Django application. The URLs for the backend look something like this: urlpatterns = [ path("admin/", admin.site.urls), path("social-auth/", include("social_django.urls", namespace="social")), path("api/", include(router.urls)), path("api-auth/", include("rest_framework.urls")), path("", views.home, name="home"), ] api and social-auth are proxied. The front end has a link to start the authentication process to /social-auth/login/facebook/. That works, gets redirected to Facebook, but then when Facebook redirects back instead of landing on example.com/social-auth/... it lands on api.example.com/social-auth which fails with the error: "Session value state missing." How can I specify the redirect_uri sent to Facebook to be example.com instead of the default api.example.com? I'm aware that one possible solution is to skip proxying and deal with CORS/cookies/tokens, but I'm trying to get it working with proxying in this Stack Overflow question. -
Displaying tasks under specific project in django
HI I am currently trying to develop a project management system. I am stuck at showing tasks related to a particular project when I view project details model.py looks like this class Project(models.Model): name = models.CharField(max_length=50) start_date = models.DateField(default=date.today) due_date = models.DateField(default=date.today) progress = models.CharField(max_length=20, choices=progress) status = models.CharField(max_length=20, choices=status) priority = models.CharField(max_length=20, choices=priority) def __str__(self): return self.name def total_projects(self): return Project.objects.all().count() def get_absolute_url(self): return reverse('projects:project_list') class Task(models.Model): title = models.CharField(max_length=50) project = models.ForeignKey(Project, related_name="tasks", on_delete=models.CASCADE) priority = models.CharField(max_length=20, choices=priority) status = models.CharField(max_length=20, choices=status) assigned = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return '%s - %s' % (self.project.name, self.title) def get_absolute_url(self): return reverse('projects:add_task') views.py looks like this class ProjectListView(ListView): model = Project template_name = 'projects/project_list.html' class ProjectDetailView(DeleteView): model = Project template_name = 'projects/project_detail.html' def get_context_data(self, *args, **kwargs): projects = Project.objects.order_by('id') context = super(ProjectDetailView, self).get_context_data(*args, **kwargs) context["projects"] = projects return context I have tried searching the net, nothing is clear -
Stripe -> issue when configuring a customer portal through code
I am not able to update plan from the stripe customer portal(Manage billing portal) after configuring the portal through code. update_to = [settings.MONTHLY_FS_PRICE_ID, price_id] #list of price_id portal_config = stripe.billing_portal.Configuration.create( features={ "customer_update": { "allowed_updates": ["email"], "enabled": True, }, "invoice_history": {"enabled": True}, "payment_method_update": {"enabled": True}, "subscription_cancel": { "enabled": cancel_enabled, "mode": "immediately" }, "subscription_update": { "default_allowed_updates":["price", "promotion_code"], "enabled": True, "products": [ { "product": product_id, "prices": update_to } ], "proration_behavior": "always_invoice" } }, business_profile={ "privacy_policy_url": privacy_policy_url, "terms_of_service_url": terms_url, }, ) session = stripe.billing_portal.Session.create( customer=request.workspace.subscription.stripeCustomerId, configuration=portal_config, return_url='http://'+settings.CURRENT_SITE_URL+'/w/dashboard' ) return redirect(session.url) The error in the billing portal during updating to a different plan-> { "error": { "message": "This subscription cannot be updated to the specified pricing structure.", "type": "invalid_request_error" } } Updating plan works when using the default customer portal configured through no-code(i.e from the dashboard settings) but I want to configure through code for more customisation -
i try to run my code but keep getting the "NoReverse match at/" error
When i run the code, i keep getting this error. NoReverseMatch at / Reverse for 'panel-index' not found. 'panel-index' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'panel-index' not found. 'panel-index' is not a valid view function or pattern name. Exception Location: C:\Users\Daniel Litumbe\Desktop\Camtel\Camvir\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\Daniel Litumbe\Desktop\Camtel\Camvir\Scripts\python.exe Python Version: 3.8.2 Python Path: ['C:\Users\Daniel Litumbe\Desktop\Camtel\Camvir\inventory', 'c:\users\daniel ' 'litumbe\appdata\local\programs\python\python38-32\python38.zip', 'c:\users\daniel ' 'litumbe\appdata\local\programs\python\python38-32\DLLs', 'c:\users\daniel ' 'litumbe\appdata\local\programs\python\python38-32\lib', 'c:\users\daniel litumbe\appdata\local\programs\python\python38-32', 'C:\Users\Daniel Litumbe\Desktop\Camtel\Camvir', 'C:\Users\Daniel Litumbe\Desktop\Camtel\Camvir\lib\site-packages'] Server time: Tue, 25 May 2021 08:21:09 +0000 Error during template rendering In template C:\Users\Daniel Litumbe\Desktop\Camtel\Camvir\inventory\templates\partials\nav.html, error at line 4 Reverse for 'panel-index' not found. 'panel-index' is not a valid view function or pattern name. 1 <!--Navbar--> 2 <nav class="navbar navbar-expand-lg navbar-info bg-info"> 3 <div class="container"> 4 <a class="navbar-brand text-white" href="{% url 'panel-index' %}">Camtel Inventory</a> 5 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> 6 <span class="navbar-toggler-icon"></span> 7 </button> 8 9 <div class="collapse navbar-collapse" id="navbarSupportedContent"> 10 <ul class="navbar-nav mr-auto"> 11 <li class="nav-item active"> 12 <a class="nav-link text-white" href="{% url 'panel-index' %}">Home <span class="sr-only">(current)</span></a> 13 </li> 14 <li class="nav-item"> **Below are the views and urls of the code** **urls.py** … -
I am trying to set up django signals to let someone get noticed after creating a blog
but this code does not work... keep error message like 'TypeError at /blog/create/ Here are the codes I put at blog/signals.py @receiver(signals.post_save, sender=Post) def send_mail(sender, instance, created, **kwargs): print('signal send') subject = "Thank you" message = Post.objects.get(??) send_mail(subject, 'message', '', ['info@*****.com.au'], fail_silently=False, ) ?? is the problem... I put pk=pk, pk=id, I don't know what parameter I need to put here... -
Django : bulk upload with confirmation
Yet another question about the style and the good practices. The code, that I will show, works and do the functionality. But I'd like to know is it ok as solution or may be it's just too ugly? As the question is a little bit obscure, I will give some points at the end. So, the use case. I have a site with the items. There is a functionality to add the item by user. Now I'd like a functionality to add several items via a csv-file. How should it works? User go to special upload page. User choose a csv-file, click upload. Then he is redirected to the page that show the content of csv-file (as a table). If it's ok for user, he clicks "yes" (button with "confirm_items_upload" value) and the items from file are added to database (if they are ok). I saw already examples for bulk upload for django, and they seem pretty clear. But I don't find an example with an intermediary "verify-confirm" page. So how I did it : in views.py : view for upload csv-file page def upload_item_csv_file(request): if request.method == 'POST': form = UploadItemCsvFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file_name = handle_uploaded_item_csv_file(request.FILES['item_csv_file']) request.session['uploaded_file'] = … -
Adding a certain number of hours to the date and time
I have a string in the following format 2021-05-06 17:30 How do I convert this to a date and time and add a certain number of hours to a given row? For example 4 I also need to add a certain number of days to the line 2021-05-06 -
Allow related field in post request in DRF
I have created model with many to many relationship and I have join table when I keep additional variable for it: class BorderStatus(models.Model): STATUS_CHOICES = [("OP", "OPEN"), ("SEMI", "CAUTION"), ("CLOSED", "CLOSED")] origin_country = models.ForeignKey(OriginCountry, on_delete=models.CASCADE, default="0") destination = models.ForeignKey(Country, on_delete=models.CASCADE, default="0") status = models.CharField(max_length=6, choices=STATUS_CHOICES, default="CLOSED") extra = 1 class Meta: unique_together = [("destination", "origin_country")] verbose_name_plural = "Border Statuses" def __str__(self): return ( f"{self.origin_country.origin_country.name} -> {self.destination.name}" f" ({self.status})" ) Other models: # Create your models here. class Country(models.Model): name = models.CharField(max_length=100, unique=True, verbose_name='Country') class Meta: verbose_name_plural = "Countries" def __str__(self): return self.name class OriginCountry(models.Model): origin_country = models.ForeignKey( Country, related_name="origins", on_delete=models.CASCADE ) destinations = models.ManyToManyField( Country, related_name="destinations", through="BorderStatus" ) class Meta: verbose_name_plural = "Origin Countries" def __str__(self): return self.origin_country.name Here is my serializer for the endpoint: class BorderStatusEditorSerializer(serializers.ModelSerializer): """Create serializer for editing single connection based on origin and destination name- to change status""" origin_country = serializers.StringRelatedField(read_only=True) destination = serializers.StringRelatedField(read_only=True) class Meta: model = BorderStatus fields = ('origin_country', 'destination', 'status') And my endpoint: class BorderStatusViewSet(viewsets.ModelViewSet): queryset = BorderStatus.objects.all() serializer_class = BorderStatusEditorSerializer filter_backends = (DjangoFilterBackend,) filter_fields=('origin_country','destination') The problem Im having is that I cant create any new combination for the BorderStatus model in this serializer via post request. If I remove the lines: … -
DJango - How To pass the full model object as new field in serializer
I want to pass the full Artist model object to the Serializer so I created a new Field serializers.SerializerMethodField and passed Artist object inside it. but I get the error. getattr(): attribute name must be string class ArtistSerializer(serializers.ModelSerializer): similar_artists = serializers.SerializerMethodField(Artist.objects.all()) class Meta: model = Artist fields = ('id', 'artist_name', 'albums', 'similar_artists') I guess I'm doing it totally wrong. so is there any way to pass all values or all Artists in single object with serializer with a manual field. I want to achieve something like this in serializer. { "id": 1, "albums": [ { "id": 1, "album_name": "Fearless (Taylor's Version)" }, { "id": 7, "album_name": "Reputation" }, { "id": 8, "album_name": "1989" } ], "artist_name": "Taylor Swift", "similar_artists": [ { Artist Object } ] }, -
Django order by nested foreignkey
models.py: class Address(models.Model): text = models.TextField(max_length=2060, null=True, blank=True, default=None, unique=True) class Tag(models.Model): text = models.CharField(max_length=255, null=True, blank=True, default=None, unique=True) class AddressTagJoin(models.Model): address = models.ForeignKey(Address, on_delete=models.CASCADE, null=True, blank=True, related_name='address_tag_join') tag = models.ForeignKey(Tag, on_delete=models.CASCADE, null=True, blank=True, related_name='address_tag_join') In above, Address and Tag objects are only used as AddressTagJoin's foreignkey target. What I want to do is two kind of queryset.. When I got address "https://www.google.com", I want to get Tag queryset ordered by most used for Address (text = "www.google.com") Tag.objects.order_by(count_of_AddressTagJoin_and_It's_address_foreignkey_is_for_"www.google.com") In reverse, I got tag "google", I want to get Address queryset ordered by most how many used for Tag (text="google") Address.objects.order_by(count_of_AddressTagJoin_and_It's_tag_foreignkey_is_for_"google") How can I do that? -
How to send message to user in a Django Thread?
I have a long time execution function that I run in a Thread to avoid blocking the user during the process. But I have a problem when I want to notify the user at the end of this function to tell him that it's done (and tell him if it was a success or an error). I tried to use django.contrib.messages but unsuccessful. Here is my code simplified : from threading import Thread from django.contrib import messages def my_view(request): thread =Thread(target=run_creation, args=[request], daemon=True) thread.start() return render(request, 'main/home.html') def run_creation(request): print("sleep start") time.sleep(20) print("sleep end") messages.add_message(request, messages.INFO, 'Hello word') The problem is that I can't see the message in my template. Here is my template : {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} Thanks a lot for your help -
Progress-bar percentage is not the percentage of uploaded file
My progress bar is working but not with the percentage of the uploaded file. I don't know why. Could someone have a look on my code please. I couldn't figuring out the issue. Upload.js $(document).ready(function() { $('form').on('submit', function(event) { event.preventDefault(); var formData = new FormData($('form')[0]); $.ajax({ xhr : function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', function(e) { if (e.lengthComputable) { var percent = Math.round((e.loaded / e.total) * 100); $('#progressBar').attr('aria-valuenow', percent).css('width', percent + '%').text(percent + '%'); } }); return xhr; }, type : 'POST', url : '/upload', data : formData, processData : false, contentType : false, success : function() { alert('File uploaded!'); } }); }); }); upload.html <form class="" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> {{form}} <button type="submit" class="btn btn-success" name="button">Upload</button> <button type="button" class="btn btn-danger">Cancel</button> </div> </form> <div class="progress"> <div id="progressBar" class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div> </div> output (the form is not processing and the progress bar doesn't depend on the percentage of the percentage of the uploaded file (since the form is not processing when submitting) -
Django channel sends duplicate messages
When user sending a message, same message sent. Here is comsumer.py code async def receive(self, text_data): message= json.loads(text_data) await self.channel_layer.group_send( self.chat_id, { 'type': 'send_message', 'text': message['text'], 'created': str(message['created']).replace(' ', 'T'), }, ) async def send_message(self, event): print(event) await self.send(text_data=json.dumps(event)) I could see the same message being sent through the log. websocket: {'type': 'send_message', 'text': 'ㅡㅡ', 'image': '', 'created': '2021-05-25T18:05:54.471893'} websocket: {'type': 'send_message', 'text': 'ㅡㅡ', 'image': '', 'created': '2021-05-25T18:05:54.471893'} websocket: {'type': 'send_message', 'text': 'ㅡㅡ', 'image': '', 'created': '2021-05-25T18:05:54.471893'} websocket: {'type': 'send_message', 'text': 'ㅡㅡ', 'image': '', 'created': '2021-05-25T18:05:54.471893'} I'm using python 3.7, channels 3.0.2, channels-redis 3.2.0 and django 3.1.4 -
No such file or directory: file: /usr/lib/python3/dist-packages/supervisor/xmlrpc.py line: 560
When i trying to use this command "sudo supervisorctl reread" I get this error [Errno 2] No such file or directory: file: /usr/lib/python3/dist-packages/supervisor/xmlrpc.py line: 560 -
return render with get_context_data()
The scenario is I'm trying to render a specific class section and list of students that doesn't belong to any sections yet. How can I achieve this using function based views? Here's my code that doesn't work but at least this is the idea: def get_students(request, pk): section = Section.objects.get(id=pk) def get_context_data(self, **kwargs): context = super(get_students(request, pk), self).get_context_data(pk) context['section'] = section context['students'] = Account.objects.filter(Q(is_student=True) | Q(is_assigned=False)).order_by( 'last_name', 'first_name') return context return render(request, 'driver-list-modal.html', get_context_data(pk)) The template that I picture would contain the class section name and a table of unassigned students with a checkbox to include them to that section if selected. Thank you for answering! -
Filtering by natural key?
I don't have the ids of the objects I want because they were created by bulk_create: and bulk_create doesn't return objects with ids so I need to fetch them by their natural keys. Is it possible to fetch the objects by filtering by natural key? I've found nothing in the documentation. We can already do: id_list = [10,3,5,34] MyModel.objects.filter(id__in=id_list) I'd like the same thing with natural key: NK_list = [('bob','carpenter'),('jack','driver'),('Leslie','carpenter')] chosen_persons = Person.objects.filter(natural_key__in=NK_list) My model looks like this: class PersonManager(models.Manager): def get_by_natural_key(self, name, job): return self.get(name=name, job=job) class Person(Models.model): name = models.CharField(max_length=200) job = models.CharField( max_length=200) objects = PersonManager() class Meta: unique_together = [['name', 'job']] def natural_key(self): return (self.name, self.job) -
Data validation error in Django Serializer
Model: class Group(models.Model): emp = models.ForeignKey(Employee, on_delete=models.CASCADE) #try user name = models.CharField(max_length=500, default=0) groupmodels = models.ManyToManyField(GroupModels) sender_clients = models.ManyToManyField(Client) I am sending the data from frontend like the following: {'name': 'dcwhjbe', 'emp': 15, 'sender_clients': [{'id': 3}], 'receiver_clients': [], 'warehouses': [], 'groupmodels': []} But there is some problem in data validation Serializer class GroupsSerializer(serializers.ModelSerializer): groupmodels = GroupModelsSerializer(many=True) sender_clients = ClientSerializer(many=True) receiver_clients = ReceiverClientSerializer(many=True) warehouses = WarehouseSerializer(many=True) class Meta: model = Group fields = "__all__" def create(self, validated_data): print("v data", validated_data) items_objects = validated_data.pop('groupmodels', None) sc_objects = validated_data.pop('sender_clients', None) rc_objects = validated_data.pop('receiver_clients', None) ware_objects = validated_data.pop('warehouses', None) prdcts = [] sc = [] rc = [] ware = [] for item in items_objects: i = GroupModels.objects.create(**item) prdcts.append(i) instance = Group.objects.create(**validated_data) print("prdcts", prdcts) if len(sc_objects)>0: for i in sc_objects: inst = Client.objects.get(pk=i) sc.append(inst) . . . . return instance print("v data", validated_data) is never called except I get this in the response: sender_clients: [{user: ["This field is required."]}] Is it because it is trying to create a sender client ? I just want to add the already created sender_clients to Group -
Cannot use QuerySet for "\"User\": Use a QuerySet for \"User\"."
I am working on a django project, python version 3.8 with django version 3.2.3 and I have created a friend request model that currently only needs to make a friend request table entry. The request contains two parameters, the senders unique id, and the receiver's unique id. It then makes a friend request entry in the FriendshipRequest table (as described by the model shown below). The view.py is as shown below. @csrf_exempt def friend_request(request): if request.method != 'POST': return r.method_not_allow_405() try: client_json = json.loads(request.body) sent_user_id = client_json['sent_user_id'] received_user_id = client_json['received_user_id'] sent_user = models.User.objects.filter(unique_id=sent_user_id) received_user = models.User.objects.filter(unique_id=received_user_id) try: models.Friend.objects.add_friend(sent_user=sent_user, received_user=received_user, message="") return r.json_response(0, "friend request successful") except Exception as e: return r.json_response(-2, str(e)) # except Exception as e: return r.json_response(-2, str(e)) # catch errors made by sent_user, received_user lines, or json (no errors in this case) There are four main models defined, the User which represents the User information, I've only kept the relevant unique_id variable in the snippet. The FriendshipRequest model which represents a friend request, and uses a ForeignKey for the user that sent the request and the user that received it. There is a FriendshipManager model that manages friend request, and in this snippet only contains add_friend function, … -
Django Model field handle if foreign key is empty string
I currently maintain on Django admin multiple database, here's what current looks: class Notes(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) created_at = models.DateTimeField() updated_at = models.DateTimeField() created_by = models.CharField(max_length=255, blank=True, null=True) modified_by = models.CharField(max_length=255, blank=True, null=True) note = models.TextField() I have created router for allowing relations between User & Notes, which I want to do like this: class Notes(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) created_at = models.DateTimeField() updated_at = models.DateTimeField() created_by = models.ForeignKey(User, models.DO_NOTHING, null=True, db_column='created_by', related_name='created_by') modified_by = models.ForeignKey(User, models.DO_NOTHING, null=True, db_column='modified_by', related_name='modified_by') note = models.TextField() but due to default value on that database state is empty string (or ''), I received error ["'' is not a valid UUID."] So far what I did for handling this issues were creating new methods like def created_by_user(self): user = '' if not self.created_by: return user try: user = User.objects.get(pk=self.created_by) except User.DoesNotExist: pass return user created_by_user.short_description = _('Created by') is there any better solutions where Django admin handle this error? I've red and far solutions I found were : create migrations to make those fields default value is nullable (which I would not to approach, due to legacy database) using previous methods (which I think it's going to be expensive) using multiple types fields (?) … -
Django-Filters returns incorrect data
I have two models Products and Categories. I am using django-fliters to filter my queryset but in some cases its returning incorrect data. When I filter the products with parameter ParentCaregory = 1, it filters the correct data. But when I filter the products with parameter ParentCaregory = 3 it returns incorrect data As you can see its returning incorrect data. These are my models: class Categories(models.Model): parent_category = models.CharField(max_length=100) second_level_category = models.CharField(max_length=100) third_level_category = models.CharField(max_length=100) product = models.ForeignKey(to=Products, on_delete=models.CASCADE) class Products(models.Model): product_id = models.BigIntegerField(primary_key=True) # creating primary key sku = models.CharField(max_length=100) name = models.CharField(max_length=100) And this is the Filter Class I am using from django_filters import rest_framework as filters from data_tool.models import Products class DataFilter(filters.FilterSet): brand = filters.CharFilter(lookup_expr='iexact') shop_url = filters.CharFilter(lookup_expr='iexact') warranty = filters.CharFilter(lookup_expr='iexact') weight = filters.CharFilter(lookup_expr='iexact') categories__parent_category = filters.CharFilter(lookup_expr='iexact') categories__second_level_category = filters.CharFilter(lookup_expr='iexact') categories__third_level_category = filters.CharFilter(lookup_expr='iexact') marketplace_status = filters.CharFilter(lookup_expr='iexact') product_status = filters.CharFilter(lookup_expr='iexact') refund_and_return_policy = filters.CharFilter(lookup_expr='iexact') attribute_set = filters.CharFilter(lookup_expr='iexact') warrenty = filters.CharFilter(lookup_expr='iexact') class Meta: model = Products fields = ['brand', 'shop_url', 'warranty', 'weight', 'categories__parent_category', 'categories__second_level_category', 'categories__third_level_category', 'marketplace_status', 'product_status', 'refund_and_return_policy', 'attribute_set', 'warrenty'] -
How to pass input type "File" to another html [closed]
I have created a submit and edit claims form. When I submit the claim, I want the details of the receipt to show on editclaim as well. This is my submitclaim.html <label for="receipt">Receipt: </label> <input id="receipt" type="file" name="receipt_field"> In the editclaim.html <label for="receipt">Receipt: </label> <input id="receipt" type="file" name="receipt" value={{claims.receipt}}> The current database I'm using is sqlite. It is embedded into my web application. -
How to print sql query from django as Dubug is False
From doc how can I see the raw SQL queries Django is running? I can get sql executed by >>> from django.db import connection >>> connection.queries But it's only available while Debug = True How to print sql as Debug is False? Thanks -
How to update and create at the same time using nested serializers and viewsets in DRf?
my models: class User(AbstractUser): password = models.CharField(max_length=128, blank=True, null=True) email = models.EmailField(max_length=254, unique=True) dial_code_id = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100, unique=True) username = models.CharField(max_length=150, unique=True, blank=True, null=True) is_active = models.BooleanField(default=True) class Meta: db_table = "my_user" class UserLocation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='location') latitude = models.DecimalField(max_digits=8, decimal_places=3) longitude = models.DecimalField(max_digits=8, decimal_places=3) address = models.TextField() class Meta: db_table = "user_location" I have to update 'first_name', 'last_name' and at the same time I have to create an object in the 'UserLocation' table for the same user. For that I have created a viewset class BasicInformationViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = BasicInformationSerializer def list(self, request, *args, **kwargs): custom_data = { "status": False, "message": 'Method Not Allowed', } return Response(custom_data, status=status.HTTP_200_OK) def create(self, request, *args, **kwargs): custom_data = { "status": False, "message": 'Method Not Allowed', } return Response(custom_data, status=status.HTTP_200_OK) def update(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance, data=request.data) if serializer.is_valid(): serializer.save() custom_data = { "status": True, "message": 'Successfully added your basic information', } return Response(custom_data, status=status.HTTP_200_OK) else: custom_data = { "status": False, "message": serializer.errors, } return Response(custom_data, status=status.HTTP_200_OK) Serializer for the above views: class UserLocationSerializer(serializers.ModelSerializer): latitude = serializers.DecimalField(max_digits=8, decimal_places=3, required=True) longitude = serializers.DecimalField(max_digits=8, decimal_places=3, required=True) address = serializers.CharField(required=True) class Meta: model = UserLocation …