Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HMAC-SHA-256 signature verification failure on Telegram Web Login
I'm trying to add Telegram Web Login to my Django+Vue project. I'm handling login on Vue and directly passing the authorization data taken from TG to Django via DRF. That's working fine. The problem occurs in the verification on REST's POST view. When i was using js-sha256 library on Vue it works perfectly and im getting the true value of hash string provided by sha256.hmac() function from the js-sha256 library. I'm struggling to get same hash on Python. Here is the TG data verification explained and the code i'm using in POST view: class TelegramLoginSerializer(serializers.Serializer): raw_data = serializers.JSONField(required=True) def create(self, validated_data): raw_data = validated_data['raw_data'] tg_data = "\n".join([f'{k}={raw_data[k]}' for k in sorted(raw_data)]) if raw_data['hash'] != self.verify_telegram_data(tg_data): return PermissionDenied() else: ... @staticmethod def verify_telegram_data(data): secret_key = hashlib.sha256(settings.TG_BOT_TOKEN.encode('utf-8')) message = data.encode('utf-8') return hmac.new(secret_key.digest(), message, hashlib.sha256).hexdigest() -
Pagination with Django Class Based View on second page is messed up with formatting
I am trying to paginate the blog created in django using class based view, the first page is ok and well formatted but next pages won't retain the formatting and "div" "container" class overrides. this is the view.py: class HomeView(ListView): model = Post template_name = 'blog.html' paginate_by = 2 The template: <div class="container"> <h1 class="" style="margin-top: 4%;">The Blog</h1> {% for post in object_list %} <div class="row d-flex justify-content-center mb-5" style="margin-top: 5%;"> <div class="row "> <div class="col" style="margin-right: 0%; padding-right: 0%; padding-left: 0%;"> <img src = '{{ post.header_image.url }}' height="250" width="100%"> </div> <div class="row text-center"> <p class="title-two" style="padding-top: 15%;">{{ post.title }} </p> </div> </div> </div> <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <li><a href="?page=1">&laquo; first</a></li> <li><a href="?page={{ page_obj.previous_page_number }}">previous</a></li> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }} </span> {% if page_obj.has_next %} <li><a href="?page={{ page_obj.next_page_number }}">next</a></li> <li><a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a></li> {% endif %} </span> </div> As shown in the pictures the first page works fine but next pages mess up with formatting. -
Trying to speed up a Serializer for a Django model - too many queries made
I'm trying to speed up my API. I need to (at least I assume I need to) use SerializerMethodField to calculate different bits of info I need included with the object. When I do that, in those methods I have to get the related _set data - which ends up hitting the database. As you can imagine, once I have a list of a large amount of users (for example: when I show all users in the web API) it takes forever to return, because of those hits to the DB. I'm not sure the best way to handle this - I believe prefetch_related and/or select_related is the answer, I'm just unsure of the best way to implement those functions. My code looks like this (pastebin version): # MODELS class User(models.Model): name = models.CharField(max_length=50) # ...etc... class Assignment(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT ) job = models.ForeignKey(Job, on_delete=models.PROTECT) location = models.ForeignKey(Location, on_delete=models.PROTECT) # SERIALIZER class UserSerializer(serializers.HyperlinkedModelSerializer): assignment_job = serializers.SerializerMethodField() multiple_locations = serializers.SerializerMethodField() multiple_jobs = serializers.SerializerMethodField() class Meta: model = User fields = [ "url", "id", "username", "first_name", "last_name", "full_name", "email", "is_staff", "assignment_job", "multiple_locations", "multiple_jobs", ] def get_assignment_job(self, obj): assignment = obj.assignment_set.get(primary=True) return assignment.job.description def get_multiple_locations(self, obj): location_count = obj.assignment_set.filter( end_date__isnull=True … -
Django CreateView doesn't save object and doesn't give error
I'm working on a new project and I'm having difficulties adding new objects from the users page. It can be added from admin dashboard. This is the model: class Product(models.Model): title = models.CharField(max_length=150) price = models.IntegerField() image = models.ImageField(upload_to='products') description = models.TextField(max_length=500) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('product-details', kwargs={'pk': self.pk}) I have this view: class ProductCreateView(LoginRequiredMixin, CreateView): model = Product fields = ['title', 'image', 'description', 'price'] def form_valid(self, form): form.instance.owner = self.request.user #form.save() return super().form_valid(form) product_form.html: {% extends "index/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Product</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Save</button> </div> </form> </div> {% endblock content%} I tried a couple of times and I didn't work. So I searched for solutions and tried the following: instance = form.save(commit=False) instance.owner = self.request.user instance.save() return super().form_valid(instance) and this self.object.owner = self.request.user self.object = form.save() return super(ProductCreateView, self).form_valid(form) within the form_valid(). Neither of them worked. So I can open the form and fill the fields. When I send it, the object is not saved but it doesn't give any error. It just reloads the form. -
Is it possible read the document.body of a secondary window of different domain with postMessage()?
I am bulding a web app: a SPA using React in frontend and Django rest framework to API endpoints. I am in the part of the social login, which is done entirely in the backend (there is a exchange of providers tokens by own JWTs), so it is necessary make the request to the server, which redirect the user to the login of the specific provider. However, due to Facebook, Google and others providers do not permit this request using AJAX, I decided to create a popup (through window.open()) to make this redirection. Whether login is successful this window is redirect again towards a View of Django that returns a JSON with the JWT. Hence, this secondary window has a JWT in the domain of my server (Django). I planned read this JSON from the body of this secondary window to get the JWT, and I read (Code response form parent window, SecurityError: Blocked... and others) the only way to communicate windows in different domains is with postMessage(). But when I try, I receive the next message: SecurityError: Permission denied to access property "document" on cross-origin object In fact both of them are runnning in localhost, just with different port. … -
Django: What is wrong with this simple code to make user session validation. No errors in Visual Studio Code. Code in body section not work properly
I'm new here. Before asking the question, I tried to search. I have become convinced that it should work, and it is not. It works: <a href= "{% url 'logout' %}" class="btn btn-danger btn-sm">Logout</a> <a href= "{% url 'login' %}" class="btn btn-success btn-sm">Login</a> It is not: {% if user.is_autenticated %} <p>Hello {{ user.username }}</p> <a href= "{% url 'logout' %}" class="btn btn-danger btn-sm">Logout</a> {% else %} <a href= "{% url 'login' %}" class="btn btn-success btn-sm">Login</a> {% endif %} I am a beginner, so sorry experienced colleagues. :) Does anyone have an idea why? In the browser, you can always see only the login button, even after logging in. The login procedure works correctly because without logging in you cannot manipulate the data. Br Marek -
Django - querying and comparing multiple many to many relationships
Case: a user is creating a new requisition. I need to filter the fields(clearances) he is allowed to select/see in his requisition; based on a comparison of the following: users department(s) users workplace(s) compared against departments workplace(s) departments clearance fields clearance workplace(s) my models: class Place(models.Model): ... name = CICharField(max_length=100) descr = models.TextField(null=True, blank=True) parent = models.ForeignKey( 'self', on_delete=models.CASCADE, null=True,blank=True, related_name='children', ) #------------------------------ class User(AbstractUser): .... place = models.ManyToManyField(Place, blank=True, related_name='users') organization = models.ManyToManyField(Organization, blank=True) .... #------------------------------ class Organization(models.Model): ... parent = models.ForeignKey( 'self', on_delete=models.CASCADE, null=True,blank=True, related_name='children', ) place = models.ManyToManyField(Place, blank=True) ... #------------------------------ class Clearance(models.Model): ... parent = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='clearances') place = models.ManyToManyField('Place', blank=True, related_name='clearances') name = models.CharField(max_length=200) ... #------------------------------ class Requisition(models.Model): ... created_by = models.ForeignKey(User, on_delete=models.CASCADE) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) place = models.ManyToManyField(Place, blank=False, related_name='requisitions') clearance = models.ManyToManyField(Clearance, blank=True, related_name='requisitions') ... Example scenario: user is a member of only 1 department: "Tech dpt" user is located in "London" and "Edinburgh" Tech dpt is located in "London", "Edinburgh" and "Glasgow" The clearances for "Tech dpt" is C1: London C2: Glasgow C3: London and Edinburgh C4: Edinburgh C5: London, Edinburgh and Glasgow the closest query I manage is the following: users_clearances = ( Clearance.objects #fetch all clearances attached to … -
How can I limit choices in this model form's ModelChoice widget using attributes in itself?
I can't find the way to limit the widget's choices to the objects in the fields 'jugadorA', and 'jugadorB', which are Jugador models. the form in forms.py: class ganadorForm(ModelForm): class Meta: model = Juego fields = ['ganador', 'jugadorA', 'jugadorB', 'torneo', 'ronda'] widgets = { 'ganador': ModelChoiceField(queryset=queryset=Jugador.objects.filter(Q(fields['jugadorA']) | Q(fields['jugadorB'])), to_field_name='nombre') } the model in models.py class Juego(models.Model): torneo = models.ForeignKey(Torneo, on_delete=models.CASCADE, null=False) ronda = models.ForeignKey(Ronda, on_delete=models.CASCADE, null=False) jugadorA = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, related_name='jugadorA') jugadorB = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, related_name='jugadorB') ganador = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, default=None, related_name='ganador') -
different classes for the same field rendered manually, each class is seen by different html files
Hello I have a question and it is that I want to place a class here {{form.status}} The problem is that {{form.status}} I am using it in a file called list.html and another called add.html. I already put the class from forms.py with widgets and I am using it in add.html file. I need another class for {{form.status}} that is only seen by the list.html file <div class="mb-3"> <label class="form-label mb-4" for="validationCustom14">Status</label> {{ form.status }} </div> -
Django models.foreignKey not being picked up and causing a Not Null Constraint error
Fairly new to Python and Django and having an issue with a foreignKey in that it's not being picked up. I am loading the data from some JSON I've get from an API call. There are two models I'm looking at, Team and Player. models (snipped for brevity): class Team(models.Model): code = models.IntegerField(null=True) name = models.CharField(max_length=30, null=True) short_name = models.CharField(max_length=3, null=True) id = models.IntegerField(primary_key=True) class Player(models.Model): total_points = models.IntegerField(null=True) squad_number = models.IntegerField(null=True) id = models.IntegerField(primary_key=True) goals_scored = models.IntegerField(null=True) minutes = models.IntegerField(null=True) team = models.IntegerField(null=True) team_code = models.IntegerField(null=True) player_team = models.ForeignKey(Team, on_delete=CASCADE) Both models have a unique id, id and code. Strange, but that's the way the data comes! Team.code maps to Player.team_code and Team.id maps to Player.team. In reality I could use either. I created player_team in Player with a ForeignKey link back to Team. I load and save Team first, then Player. teams = [Team(**data_dict) for data_dict in data['teams']] Team.objects.all().delete() Team.objects.bulk_create(teams) players = [Player(**data_dict) for data_dict in data['elements']] Player.objects.all().delete() Player.objects.bulk_create(players) The error I get is django.db.utils.IntegrityError: NOT NULL constraint failed: players_player.player_team_id I don't really understand how exactly it is linking the two models. I can see that in Player it is saying models.ForeignKey(Team...) so that makes sense. But how … -
Where can I find django(ORM) practice problems?
I'm really finding it very difficult to source practice problems for Django and its ORMs. I've heard Mosh's paid course has such exercises. I'm just getting started with Django mostly referring to youtube and its official documentation. I hope one of you who reads this could help me out. I don't know if this is the right forum to ask. Thanks in advance! -
Add CSRF to locust post request to prevent django error - Forbidden (CSRF cookie not set.)
How to add CSRF to the URL to test django from locust to prevent the error Forbidden (CSRF cookie not set.)? Here is what I have tried: @task def some_task(self): response = self.client.get("/") csrftoken = response.cookies['csrftoken'] self.client.post( "api/", {'csrfmiddlewaretoken': csrftoken}, headers={ 'X-CSRFToken': csrftoken, }) -
Is there any way to make this filter query smaller
These are my tables: class Employee(models.Model): name = models.CharField() class Job(models.Model): title = models.CharField() class Employee_Job(models.Model): employee_f = models.ForeignKey(Employee, on_delete=models.CASCADE) job_f = models.ForeignKey(Job, on_delete=models.CASCADE) class Salary(models.Model): employee_job_f = models.ForeignKey(Employee_Job, on_delete=models.CASCADE) @property def name(self): return Employee.objects.filter(id = ( Employee_Job.objects.filter(id = self.employee_job_f_id ).first().employee_f )).first().name This query seems very long to me, I thought select_related() should help with this, but it follows foreign keys and return ALL results not the result that is related to THIS instance of Salary. -
How can I add Django table list on edit page change_form.html?
Friends, how can I add into admin edit page Django admin like table? So, I got MaterialAdmin. I've added change_view() function in it and all the necessary data put into extra_content like this: class MaterialAdmin(admin.ModelAdmin): change_form_template = 'admin/change_material_form.html' search_fields = ['name'] autocomplete_fields = ("manufacturer", ) list_display = ("_show_name_with_manufacturer", "_show_material_groups_quantity", "_show_boxing", "unit",) def get_queryset(self, request): qs = super().get_queryset(request) return qs.select_related("manufacturer").prefetch_related("material_group", "material_item", "unit") def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = extra_context or {} material = Material.objects.filter(id=object_id).select_related("manufacturer").prefetch_related("material_group", "material_item", "unit").first() material_items = material.material_item.all() material_groups = material.material_group.all() works = MaterialGroupWork.objects.filter(material_group__in=material_groups).distinct() extra_context['material_items'] = material_items extra_context['material_groups'] = material_groups extra_context['works'] = works return super(MaterialAdmin, self).change_view( request, object_id, form_url, extra_context=extra_context, ) admin.site.register(Material, MaterialAdmin) Now I have access to the data in my custom change_material_form.html .... <div> {% for material_item in material_items %} {{ material_item }} {% endfor %} </div> <div> {% for material_group in material_groups %} {{ material_group }} {% endfor %} </div> <div> {% for work in works %} {{ work.work }} {% endfor %} </div> What I really want is to replace those divs with Django Admin tables. How can I implement this? I looked in the template file "change_list_results.html" and it has some result_headers и results data. But I don't know how to get "results" … -
Django Template Not Receiving Context Object
I'm trying to implement a simple sign up form and slightly tearing my hair out. For some reason, the view doesn't seem to be properly passing the context object I pass it (regardless of what it is.) here's my code: urls.py path(r"signup/", client_views.signup_view, name="page-signup") views.py def signup_view(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('page-index') else: form = SignUpForm() context = {'form': form} return render(request, 'registration/signup.html', context=context) registration/signup.html {% extends "base.html" %} {% load static %} {% block header %} Sign Up {% endblock %} {% block content %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign Up</button> </form> {% endblock %} forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('first_name', 'last_name', 'email', 'password1', 'password2', ) I've confirmed it's generating the form properly as html it's also definitely rendering the correct template doesn't pass any context even if it's just a string or something doesn't work with any forms doesn't work in other templates, implying to me it's in the view … -
See variable values in developer tools for Django templates
I have a template in Django which uses some variables. For example, I use {% with swatch_matrix=item_group.get_swatch_matrix %} Without rendering this on-screen is there a way to use the developer tools, or something else, to check what value is being generated here? -
Python Django - dynamically add and create objects in ModelMultipleChoiceField
I have a problem with something that I thought was quite common, but I cannot find the answer to it anywhere. I have 2 models Item and Group, where an item can be a member of many (or none) groups. I am writing a view for creating an Item. My code looks like this: # models.py class Group(models.Model): ... class Item(models.Model): item = models.CharField(...) groups = models.ManyToManyField(Group) # forms.py class NewItemForm(forms.Form): item = forms.CharField() groups = forms.ModelMultipleChoiceField( queryset = models.Group.objects.all(), widget = forms.CheckboxSelectMultiple, required = False ) In my template I add javascript that allows user to dynamically crate a new checkbox (and setting it's value to something like __new__group_name) for a new group. What I want to accomplish it to allow user to create a new group and add an item to it, while this item is currently being created. Unfortunately this cannot work, because checkboxes generated by Django are sending a primary key of Group and there obviously is not a group with primary key __new__group_name so validation of this form failes. While it is correct and I am glad it does, I cannot find a easy solution for this problem. The only thing I can think about … -
django: repeat testcase with different fixtures
I have a Django TestCase, all of whose tests I'd like to run for two different sets of data (in this case, the Bike object whose colour can be red or blue). Whether that's through loading different fixtures, or the same fixtures and manipulating the colour, I have no preference. See below example: class TestBike(TestCase): fixtures = [ "testfiles/data/blue_bike.json", ] def setUp(self, *args, **kwargs): self.bike = Bike.objects.get(color="blue") run_expensive_commands(self.bike) def test_bike_1(self): # one of many tests def test_bike_2(self): # second of many tests One way I considered was using the parameterized package, but then I'd have to parameterize each test, and call a prepare() function from each test. Sounds like a whole lot of redundancy. Another is to multiple-inherit the test with different fixtures. Also a bit too verbose for my liking. -
how i can connect between 2 django services using mqtt?
"how i can connect two Django services using MQTT (i want to create a customer in the first service and then dispatched it to the another service)` -
Speeding up Django Rest Framework Model Serializer N+1 Query problem
I have a DRF ModelSerializer class that serializes anOrder model. This serializer has a field: num_modelA = serializers.SerializerMethodField() ` def get_num_modelA(self, o): r = ModelA.objects.filter(modelB__modelC__order=o).count() return r Where ModelA has a ForeignKey field modelB, ModelB has a ForeignKey field modelC, and ModelC has a ForeignKey field order. The problem with this is obviously that for each order that gets serialized it makes an additional query to the DB which slows performance down. I've implemented a static method setup_eager_loading as described here that fixed the N+1 query problem for other fields I was having. @staticmethod def setup_eager_loading(queryset): # select_related for "to-one" relationships queryset = queryset.select_related('modelD','modelE') return queryset My idea was I could use prefetch_related as well to reduce the number of queries. But I am unsure how to do this since Order and ModelA are separated by multiple foreign keys. Let me know if any other information would be useful -
Wagtail Create Snippet from the frontend to accepts Images (Django)
I have a simple snippet using Django Wagtail. I would like to be able to update the logo from a "CreateView" but when it renders in my view it's expecting a foreign key. I would imagine it would be easy to create a from to do this but it's not. @register_snippet class MerchantSnippet(models.Model): name = models.CharField(max_length=255, blank=False, null=False, unique=True) logo = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, ) def __str__(self): return '{} {}'.format(self.user.first_name, self.user.last_name) panels =[ FieldPanel('name'), ImageChooserPanel('logo'), ] edit_handler = TabbedInterface([ ObjectList(panels, heading='Content'), ]) class ProductCreateView(CreateView): model = ProductSnippet fields = ['name','logo'] class ProductUpdateView(UpdateView): model = ProductSnippet fields = ['name','logo'] When I use the default example in the template I ended up just getting a drop down. {% render_field field class+="form-control" %} How would I be able to see an image preview in the event I am updating the snippet and the ability to upload a different one . In the event I am creating a new item the ability to select an upload an image. -
Iterating over model object in template is returning no results - Django
This is my model: pass class Listing(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=500) url = models.URLField() live = models.BooleanField(default=True) author = models.ForeignKey('User', on_delete=models.CASCADE, name='author') category = models.ForeignKey('Category', on_delete=models.CASCADE, name='category', default="") def __str__(self): return f'{self.id}: {self.title}' class Bid(models.Model): price = models.DecimalField(decimal_places=2, max_digits=10) bid_count = models.IntegerField() highest_bidder = models.ForeignKey('User', on_delete=models.PROTECT, name="highest_bidder", default=None, blank=True, null=True) listing = models.ForeignKey('Listing', on_delete=models.CASCADE, name='listing', default="") def __str__(self): return f'{self.listing.title} ({self.price})' class Category(models.Model): title = models.CharField(max_length=200) def __str__(self): return self.title class Watchlist(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE, name='user') item = models.ManyToManyField('Listing', blank=True, null=True) def __str__(self): return f"{self.user}'s Watchlist" This is my view: currentUser = request.user watchlist = Watchlist.objects.filter(user=request.user).values() bids = Bid.objects.all() return render(request, 'auctions/userWatchlist.html', { 'currentUser': currentUser, 'watchlist': watchlist, 'bids': bids }) I've also tried not passing in .values() and using .all in the template instead. Here's the template: {% block body %} <h2>Watchlist</h2> <div class="container"> <div class="row"> {% for listing in watchlist %} <div>{{ listing }}</div> <div class="col"> <div class="card" style="width: 18rem;"> <img src="{{ listing.item.url }}" class="card-img-top" alt="{{ listing.item.title }}"> <div class="card-body"> <h5 class="card-title">{{ listing.item.title }}</h5> <p class="card-text">{{ listing.item.description }}</p> {% for bid in bids.all %} {% if bid.listing == listing.item %} <p class="card-text">Bid price: {{ bid.price }}</p> {% endif %} {% endfor %} <a href="{% url 'item_details' … -
Django Many to Many relationship Query Filter
class servers(models.Model): hostname=models.CharField(max_length=100) ip= models.CharField(max_length=100) os= models.CharField(max_length=100) class application(models.Model) name=models.CharField(max_length=100) URL= models.CharField(max_length=100) servers= models.ManyToManyField(servers, blank = True, null=True) current DB status 3 servers 2 with os as linux and 1 with os as windows 2 applications Requirement : application can have many servers and each server can be part of many applications also Need support to create filter only those applications whose os is windows. I tried below but it is returning all three servers. def viewapp(request,pk) criterion1 = Q(id=pk) criterion2 = Q(servers__os__startswith="windows") prodlist = application.objects.filter(criterion1 & criterion2) -
how I'm gonna create the URL pattern for each topic?
I want to create a URL patterns for each topic. How I'm gonna do that?? This is my code: models.py from django.db import models from django.db import models class Task(models.Model): title = models.CharField(max_length=50) completed = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title urls.py from django.urls import path from . import views app_name = 'my_app' urlpatterns = [ path('', views.index, name='index'), path('add_task/', views.add_task, name='add_task'), ] forms.py from django import forms from .models import Task class TaskForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'add new task...'})) class Meta: model = Task fields = '__all__' views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Task from .forms import TaskForm def index(request): task = Task.objects.all() context = {'task': task} return render(request, 'my_app/index.html', context) def add_task(request): if request.method == 'GET': form = TaskForm() else: form = TaskForm(data=request.POST) if form.is_valid(): form.save() return redirect('my_app:index') context = {'form': form} return render(request, 'my_app/add_task.html', context) base.html To do {% block content %}{% endblock %} index.html {% extends 'my_app/base.html' %} {% block content %} <p><a href="{% url 'my_app:add_task' %}">Add task</a></p> <ul> {% for tasks in task %} <li> {{ tasks }} </li> {% empty %} <li> <p>There's no task</p> </li> {% endfor %} </ul> {% endblock %} add_task.html {% … -
how to save the uploaded images in Django backend
Here I have written a code for multi uploading images. This I have done in vue.js and backend is Django. So here while user uploads an multiple images so it is uploading the image and it is showing in console. But the issue i am not able to access this in backend. And below I have past django function if anyone have an idea how to save this images in backend from last one week struggling alot to save the images in backend nut not succeeded yet please help me if anyone have an idea about this <body> <div id="el"> <div id="my-strictly-unique-vue-upload-multiple-image"> <vue-upload-multiple-image @upload-success="uploadImageSuccess" @before-remove="beforeRemove" @edit-image="editImage" @data-change="dataChange" :data-images="images" ></vue-upload-multiple-image> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script> <script src="https://unpkg.com/vue-upload-multiple-image@1.0.2/dist/vue-upload-multiple-image.js"></script> <script type="text/javascript"> var vm = new Vue({ el: '#el', data() { return { images: [] } }, components: { VueUploadMultipleImage, }, methods: { uploadImageSuccess(formData, index, fileList) { console.log('data k', fileList); console.log('data1', formData); console.log('data2', index); }, beforeRemove(index, done, fileList) { console.log('index', index, fileList) var r = confirm("remove image") if (r == true) { done() } else { } }, editImage(formData, index, fileList) { console.log('edit data', formData, index, fileList) }, dataChange(data) { console.log(data); } } }); </script> </body> views.py def fileupload(request): return render(request, 'fileupload.html')