Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use custom widget to override django JSONField
I'm trying to use a 3-party widget like django-json-widget to edit the JSONField in my form. This is how my Form looks so far: class ConfigsForm(forms.Form): ks_config = JSONField() This code works fine, but the interface is quite ugly. I'm looking for something like django-json-widget package to be able to edit JSON data. But so far i wasn't able to implement it properly. And here is my view for it: def configs_details(request, sim_id): simulation = get_object_or_404(Simulation, pk=sim_id) ks_config = os.path.join(os.getcwd(),'configs', str(simulation.uuid), 'ks_config.json') with open(ks_config) as jsn: form = ConfigsForm(request.POST or None,initial={'ks_config': json.load(jsn)}) if form.is_valid(): # validate and save pass template = 'sim_configuration.html' context = {'Form': form} return render(request,template, context) What I tried. Adding following lines to the form above: class ConfigsForm(forms.Form): ks_config = JSONField() widgets = { 'ks_config': JSONEditorWidget(mode='code') } Also, I have to specifically use Form and not ModelForm. Here is my HTML form page: {% extends 'base.html' %} {% block head %} <title>Configs</title> {% endblock head %} {% block body %} <div class="container"> <br> <form action="" method="post"> {% csrf_token %} {{ Form.as_p}} <input type="submit" value="Submit" /> </form> </div> {% endblock body %} -
How can I see all trhe attributes of a queryset?
Hello I have this code using Django : a = Clients.objects.get(id=1) And I would like to display all the attribute of a I mean all the field of a. How can I do to do this ? Thank you very much ! -
Django lazy load images
i am working on a Django project, where we built a Bootstrap carousel of images. My task now is to try and lazy load those images. How would I write a view in Django and in HTML that would request the next image in the list and the render it. The carousel does have a back and next button that could be used as an event but I am unsure how I would go about partially rendering the slideshow. Thanks in advance. -
How to save a PDF acro form displayed on client side using iframe
I am currently trying to show a PDF with fillable form fields on my webpage, with the help of an iframe. My aim is to let the user fill in the form and click a save button which would then save that PDF file to my backend database [Django Application]. -
Error 403 CSRF cookie not set. axios post request to django server
I have been trying to send a simple post request to my django server using axios package in react. But everytime, I'm getting a backend error saying CSRF Cookie not set. Here is my React Code: componentDidMount() { let csrfToken = getCsrfToken() console.log(csrfToken) axios({ method: "POST", url: 'http://localhost:8000/getStats', headers: { "Content-Type": "application/json", "x-csrftoken": csrfToken }, data: { "city": "pune" } }).then(response => { console.log(response); }).catch(err => { console.log(err); }) } This is added in my django server: CSRF_COOKIE_NAME = "x-csrftoken" -
Difference between just adding app name vs appname.apps.AppConfig in Django
hello I am new to Django. So I read some tutorials. Some tutorials tell you to type just the app name in the installed_apps.Like this. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'core', 'user', 'recipe', ] On the other hand, some tutorials tell you to do it like this. What is the difference. I am also using Django Rest Framework if that makes any difference. INSTALLED_APPS = [ 'core.apps.CoreConfig', ] -
UpdateWithInlinesView for django-extra-views not working with crispy_forms
I have a Django app with django-extra-views to create and maintain a pair of related models. The set up is as follows: # models.py class ModelA(models.Model): # fields def get_absolute_url(self): return reverse('model_a:detail', kwargs={'pk': self.id}) class ModelB(models.Model): model_a = models.OneToOneField(ModelA, on_delete=models.CASCADE) # other fields I have two corresponding views and forms: # views.py class ModelBView(InlineFormSetFactory): model = ModelB form_class = ModelBForm prefix = 'model_b' class ModelACreateView(LoginRequiredMixin, PermissionRequiredMixin, CreateWithInlinesView): model = ModelA inlines = [ModelBView, ] permission_required = ('add_model_a') template_name = 'apps/model_a/create.html' form = ModelAForm fields = '__all__' def get_success_url(self): return self.object.get_absolute_url() class ModelAUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateWithInlinesView): model = ModelA inlines = [ModelBView, ] permission_required = ('change_model_a') template_name = 'apps/model_a/update.html' form = ModelAForm fields = '__all__' def get_success_url(self): return self.object.get_absolute_url() # forms.py class ModelAForm(forms.ModelForm): class Meta: model = ModelA fields = [ # some fields ] initial = [...] class ModelBForm(forms.ModelForm): class Meta: model = ModelB fields = [ # some fields ] The trouble happens in the template files. The CreateWithInlinesView works, while UpdateWithInlinesView does not, when paired with crispy_forms. Following is the code that DOES NOT work. When I press the 'Save' button, it brings me back to the update page and when I check the details page, things are unchanged: … -
Django: How to add a manytomany field(from user to user itself) to the built in user model
example field that i want to add in built in User model class bulit_in_user_model(models.Model): relationships = models.ManyToManyField('self',on_delete=models.CASCADE) how to do that -
How to create dynamic header with vertical table in django template
This is my image enter image description here I have data like. data = [ { "name":"bolb", "category_name":"Electronics", "size":"34", "price":"890", "currency_name":"Rs", }, { "name":"bolb", "category_name":"Electronics", "size":"2", "price":"9099", "currency_name":"Rs", } ] I need to show this data into html template like as below. <table> <tbody> <tr> <td>Category Compare</td> <td>bolb</td> <td>bolb asun</td> </tr> <tr> <td>price </td> <td>890</td> <td>9099</td> </tr> <tr> <td>category_name</td> <td>Electronics</td> <td>Electronics</td> </tr> <tr> <td>currency_name</td> <td>Us</td> <td>Us</td> </tr> </tbody> </table> My desire output table vertically with dynamic. I have added image also for clarification. Can i change my variable data or i can do it using for loop.Please suggest best idea or code will be appreciate. -
Django: How to return a Single Object (not Array) in a ModelViewSet?
I want to get a single object out of my Profile model. That works perfectly if I use the filter method like below. However it returns me an array that contains a single object. What i want is just the object but not inside a list / array. When i want to use the get_object function i get the error that i can not use it within the ModelViewSet. So i wonder how can i get a single object out of my model while using a ModelViewSet? class ProfileViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = ProfileSerializer queryset = Profile.objects.all() def get_queryset(self): if self.action == 'list': return self.queryset.filter(user=self.request.user) return self.queryset -
how to filter values of main table from foreign key table view?
I a trying to display the values of a foreign key table sorted upon the values of other foreign table. am unable to find a way to show all the type of categories available in a specific city in the views. From the 'views' I am able to get all the business's present in the specific city, but along with that I want to find the category types available in the specific city. A help is very much appreciated #models.py class business(models.Model): title = models.CharField(max_length=200) category = models.ForeignKey('Type', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=1000, help_text="Enter a brief description of the business") city = models.ForeignKey('City', help_text="Select a city for this business") def get_absolute_url(self): return reverse('business-detail', args=[str(self.id)]) def __str__(self): return self.title class Type(models.Model): category_name = models.CharField(max_length=200,help_text="Enter business category") def __str__(self): return self.category_name class City(models.Model): city_name = models.CharField(max_length=200,help_text="Enter a city") def __str__(self): return self.city_name #views.py class citydetail(generic.ListView): model = City def get_context_data(self, **kwargs): context = super(citydetail, self).get_context_data(**kwargs) context['test'] = Type.objects.all() -
How to get all subclass of Territory Hierarchy in Django
I have this models: class Country(models.Model): name = models.CharField(max_length=80) class Meta: verbose_name = "Country" verbose_name_plural = "Countries" def __str__(self): return str(self.name) class Region(models.Model): name = models.CharField(max_length=100) state = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='children' ) class Meta: verbose_name = "Region" verbose_name_plural = "Regions" def __str__(self): return str(self.name) class Territory(models.Model): name = models.CharField(max_length=100) division = models.ForeignKey(Region, on_delete=models.CASCADE, related_name='children' ) class Meta: verbose_name = "Territory" verbose_name_plural = "Territories" def __str__(self): return str(self.name) class City(models.Model): name = models.CharField(max_length=100) region = models.ForeignKey(Territory, on_delete=models.CASCADE, related_name='children' ) class Meta: verbose_name = "City" verbose_name_plural = "Cities" def __str__(self): return str(self.name) class User(models.Model): name = models.CharField(max_length=50, default='') surname = models.CharField(max_length=50, default='') birthday = models.DateField(default='') country = models.ForeignKey(Country, related_name='children', on_delete=models.CASCADE ) region = models.ForeignKey(Region, related_name='children', on_delete=models.CASCADE ) city = models.ForeignKey(City, related_name='children', on_delete=models.CASCADE ) class Meta: verbose_name = "User" verbose_name_plural = "Users" def __str__(self): return str(self.name) I want the api in Hierarchy level { "id": 2, "country": Italy, "users": 350000 "region": { "id": 8, "region": Calabria, "users": 7000 "territory":{ "id": 25, "territory": Reggio Calabria, "users": 300 "city":{ "id": 95, "City": Reggio Calabria, "users": 100 }, { "id": 108, "City": Calabria, "users": 100 } }, { "id": 36, "territory": Cosenza, "users": 11000 "city":{ "id": 95, "City": Cosenza, "users": 6500 }, { "id": 108, "city":Province … -
Django REST: No primary key from Custom User model
I have implemented a CustomUser model in my Django REST project (version 2.2) with help from How to save extra fields on registration using custom user model in DRF + django-rest-auth. Signing up works, you can add CustomUsers and view them, it registers the custom fields as well. However when I do a GET request from my front end (React) I cannot access the primary key (pk), is it possible to add primary key to the received data? users/models.py class CustomUser(AbstractUser): custom_field = models.CharField(max_length=255, blank=True, null=True) class CustomRegisterSerializer(RegisterSerializer): custom_field = serializers.CharField(max_length=255, allow_blank=True, required=False) def get_cleaned_data(self): data_dict = super().get_cleaned_data() data_dict['custom_field'] = self.validated_data.get('custom_field', '') return data_dict users/adapter.py class CustomAccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=False): user = super().save_user(request, user, form, commit) data = form.cleaned_data user.custom_field = data.get('custom_field') user.save() return user users/views.py class CustomUserViewSet(viewsets.ModelViewSet): queryset = CustomUser.objects.all() serializer_class = CustomRegisterSerializer I do the GET request from my front end React project using Axios: axios .get(http://localhost:8000/api/customusers/) .then((response) => { handleResponse(response); }) .catch((error) => { console.log(error); }); -
How to set the defaultvalue as a parameter taking function in django where the parameter is the value of one of the fields?
I want to set the default value of image field as the getimg function. But when I run this code I get an error saying missing one required positional argument in getimg() 'self'. How do I approach this? class Products(models.Model): Code = models.CharField(max_length=10) Product_description = models.CharField(max_length=200,primary_key = True) Val_tech = models.CharField(max_length=5) Quantity = models.IntegerField(default=0) UOM = models.CharField(max_length=5) Rate = models.FloatField(default=0) Value = models.FloatField(default=0) def __str__(self): return self.Product_description class Forimg(models.Model): products = models.OneToOneField(Products, on_delete=models.CASCADE, primary_key = True) def getimg(self): item = self.products.Product_description page = requests.get(f'https://www.google.com/search?tbm=isch&q={item}') soup = BeautifulSoup(page.text, 'lxml') item_head = soup.find('img',class_='t0fcAb') return item_head['src'] image = models.ImageField(upload_to = 'img/', width_field= 30, height_field = 40,default=getimg) def __str__(self): return self.products.Product_description -
Django : Import static file inside a template doesn't work properly
It seems that my static file doesn't work properly in my django project. I'm not sure whether this is exactly related to js files or the whole static file. Checking related questions, I couldn't find how to solve this problem. So, I send what my template should look like and how it looks in my browser in the below screenshots: what my template should look:(when scrolling down, the background image also moves) But this is how my browser shows the template: (no background images, no padding adjustments) This is my base.html codes: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- Font Awesome --> <link rel="stylesheet" href="{% static 'css/all.css' %}"> <!-- Bootstrap --> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <!-- Custom --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- LightBox --> <link rel="stylesheet" href="{% static 'css/lightbox.min.css' %}"> <title>BT Real Estate</title> </head> <body> <!-- Top Bar --> {% include 'partials/_topbar.html' %} <!-- Navbar --> {% include 'partials/_navbar.html' %} <!--- Main Content --> {% block content %} {% endblock %} <!-- Footer --> {% include 'partials/_footer.html' %} <script src="{% static 'js/jquery-3.3.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.bundle.min.js' %} "></script> <script src="{% static 'js/lightbox.min.js' … -
How to automatically add lookup field based on request?
I have UserViewSet with based on viewsets.ModelViewSet. It is attached to url /users/. I want to create /user/ url with GET and PATCH methods. How to link /user/ to UserViewSet, so when doing GET or PATCH methods it automatically linked to /users/request.user.id/ views.py class UserViewSet(viewsets.ModelViewSet)): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (IsAuthenticated,) ... urls.py router = DefaultRouter() router.register(r'users', UserViewSet, basename='users') ??? urlpatterns = router.urls -
Two Django Forms - Html page with two submit buttons
models.py class ServiceRequest(models.Model): CATEGORY_CHOICES = ( (None, ''), ('aircraft_repair', 'Aircraft Repair'), ('backshop', 'Backshop'), ('documentation', 'Documentation'), ('other', 'Other') ) PRIORITY_CHOICES = ( (None, ''), ('1', 'Level 1 - Critical'), # <24 hours ('2', 'Level 2 - Urgent'), # 1-2 days ('3', 'Level 3 - Standard'), # 3-4 days ('4', 'Level 4 - Low') # 5+ days ) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, blank=True) updated = models.DateTimeField(auto_now=True) request_number = models.CharField(max_length=6, default=number) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() contact = models.CharField(max_length=14) category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default=None) due_date = models.DateField(verbose_name='Due Date', auto_now_add=False, auto_now=False, blank=True) priority = models.CharField(max_length=20, choices=PRIORITY_CHOICES, default='3') # default to standard priority aircraft = models.CharField(max_length=20) NrcWorkOrder = models.CharField(max_length=10, verbose_name='Work Order') NrcZone = models.CharField(max_length=10, verbose_name='Zone') NrcItem = models.CharField(max_length=10, verbose_name='Item') EgWorkOrder = models.CharField(max_length=10, blank=True) EgZone = models.CharField(max_length=10, blank=True) EgItem = models.CharField(max_length=10, blank=True) references = models.CharField(max_length=200) description = models.TextField() attachments = models.FileField(null=True, blank=True, upload_to=upload_location) def __str__(self): return self.request_number # show the request number in admin screen class Meta: ordering = ('-request_number',) # sort request number descending in admin screen class File(models.Model): files = models.FileField(verbose_name="Attachments", name="files", upload_to="files/", blank=True) def __str__(self): return self.files def get_absolute_url(self): return reverse('file_list') def delete(self, *args, **kwargs): self.files.delete() super().save(*args, **kwargs) forms.py class ServiceRequestForm(forms.ModelForm): class Meta: model = ServiceRequest fields = [ … -
Periodic task scheduling using clock process
I am trying to run periodic task every minute through clock and worker process. I am using Heroku for deployment. Here is what I tried till now: I have incldued this in my setings.py: from rq import Queue from worker import conn q = Queue(connection=conn) worker.py: import os import redis from rq import Worker, Queue, Connection listen = ['high', 'default', 'low'] redis_url = os.getenv('REDISTOGO_URL', 'redis://h:pa49c4c2c8cec01df7eed95d519e@ec2-54-17-81-217.compute-1.amazonaws.com:28419') conn = redis.from_url(redis_url) if __name__ == '__main__': with Connection(conn): worker = Worker(map(Queue, listen)) worker.work() utils.py: I have tried working the function as action in admin page and it works totally fine but the issue is with autmation. from django.apps import apps from Gala_Tasks.models import * from Gala_Checklist.models import * import datetime def task_delay(): queryset=Task.objects.all() for ob in queryset: ob.score=(timezone.now()-ob.deadline_fixed).days if ob.score>=ob.score_fixed and not ob.esc_csm: t1=Task_CSM.objects.create_Task(ob.task_name, ob.title, ob.deadline_fixed+timezone.timedelta(hours=ob.task_name.time_deadline), ob.deadline_fixed+timezone.timedelta(hours=ob.task_name.time_deadline), ob.esc_csm, ob.esc_csl, ob.task_type, ob.score, ob.c1, ob.c2, ob.c3, ob.vendor, ob.created) ob.esc_csm=True if ob.score>=9: ob.csl=True if ob.deadline_fixed<=timezone.now(): ob.status_curr="DELAYED" ob.save() return clock.py: import os from django.apps import apps os.environ['DJANGO_SETTINGS_MODULE'] = 'todo.settings' from apscheduler.schedulers.blocking import BlockingScheduler from utility_dir.utils import * sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=1) def timed_job(): result = q.enqueue(task_delay) sched.start() Procfile: worker: python worker.py clock: python clock.py web: gunicorn todo.wsgi Here is the structure of my project todo: todo Gala_Checklist … -
How do i prevent page refreshing the time i click button
How do I prevent page refresh when button clicked template.html <form action="{% url 'user_homeview:like_dislike_post'%}" > <input type="hidden" name='post_id' value="{{i.id}}"> {% if user not in i.liked.all%} <button type="submit" style="color: white;" >Like</button> {% else %} <button type="submit" style="color: white;" > liked</button> {% endif %} <strong>{{i.liked.all.count}}&nbsp;Likes</strong> </form> -
if statement and for loop problem in django html
I am trying to print all the orders related to a specific customer. I used a for loop to access my orders in the html file, and i used an if statement to make sure that the order is related to the customer. {% for order in orders %} {% if customer.name == order %} <a href="">{{ order }}</a> {% endif %} {% endfor %} in my views I gave my html file access to these variables. def orderss(request, pk): Customer = customer.objects.get(id=pk) orders = Order.objects.all() context = { 'customer':Customer, 'orders': orders, } return render(request, 'Inventory_Management/orders.html', context) to reach this page i used a button <a href="{% url 'orderss' customer.id %}">View Orders</a> the url is the one below path('orders/<str:pk>/', orderss, name="orderss") related models class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) order_head = models.ForeignKey(order_header, blank=False, null=True, on_delete=models.SET_NULL) items = models.ForeignKey(item, blank=False, null=True, on_delete=models.SET_NULL) Quantity = models.CharField(max_length=100) date_created = models.DateTimeField(auto_now_add=True, null=True) total = models.CharField(max_length=100) status = models.CharField(max_length=200, null=True, choices=STATUS) def __str__(self): return '{self.order_head.Buyer}'.format(self=self) class customer(models.Model): name = models.CharField(max_length=12, blank=False) phone = models.CharField(max_length=12, blank=False) email = models.CharField(max_length=50, blank=False) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class order_header(models.Model): date_created = models.DateTimeField(auto_now_add=True, null=True) User = … -
Django: passing a translated variable to Ajax does not work
I have a number of constants as a list of dicts, with the verbose names of these variables translated using pgettext_lazy (these are translated in their respective django.po and django.mo files): SORTING_SCHEMES = [ dict(name='by_date_added', verbose_name=pgettext_lazy('Type of sorting', 'By date added')), dict(name='by_alphabet', verbose_name=pgettext_lazy('Type of sorting', 'In alphabetical order')), ] Now, when I try to pass these lists to HTML templates, everything works fine. But as soon as I pass the verbose_name of the variable chosen by the user, it remains untranslated, regardless of the language chosen by the user in their locale. Here is how I pass the verbose_name parameter in the response: response['sorting_scheme'] = next(item for item in SORTING_SCHEMES if item['name'] == movies_list.last_sorting_scheme)['verbose_name'] In JavaScript: ........ $.ajax({ url: '/ajax/', type: 'POST', data: {movie: uid}, success: function (response) { prepareForNewMovie(); setMovieTitle(response.chosen_movie); setSortingScheme(response.sorting_scheme); ....... and var setSortingScheme = function (newScheme) { $('#chosen-sorting').text(newScheme); controlChosenSortingSize(); }; Within JavaScript, the verbose name of the sorting scheme is always in English: in the dropdown menu, I can see all sorting schemes options translated, but as soon as I choose one, it is displayed solely in English. How can this be solved? -
Bootstrap4 datepickerinput calender icon is not clickable
base.hmtl code {% block content %} {% endblock %} <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="//cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script> <script src="//cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="//cdn.bootcss.com/moment.js/2.17.1/moment.min.js"></script> new_as.html {% extends "base.html" %} {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {% block extrahead %} {{ form.media }} {% endblock %} {% block content %} <body> <div style="background-color:#0062cc;color:white"> <h1 style="padding-left:50px" class="gfont"><a href="{% url 'main_page'%}" style="color:white"> Assignments</a> <p class="title gt">{{ stu }}<a href="/logout" style="padding-left:10px;font-size:15px;color:orange">logout</a></p></h1><hr> </div> <span style="float:left;padding-left:20px"><button onclick="javascript:history.go(-1);" class="btn btn-primary">Back</button></span> <div class="box" align="center" style="margin-bottom:1cm"> <form action="new_assignment" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.media }} {% bootstrap_form form %} {% for error in form.non_field_errors %} <p>{{error}}</p> {% endfor %} <br> <button type="submit" name="True" class="btn btn-warning">Save and add another question</button> <button type="submit" name="False" class="btn btn-primary">Save and exit</button> </form> </div> </body> {% endblock %} forms.py pub_date = forms.DateField(label='Publish date', widget=DateTimePickerInput(format='%m/%d/%Y')) output enter image description here Can anyone help me see why the calendar icon is not clickable and provide a solution to make it work? -
How to save a Javascript variable to a file in Django media folder?
I have a canvas where I draw a rectangle and save their coordinates. The coordinates are saved in a Javascript dictionary. Using the following script, I can save / download a file with the dictionary in it. But it gets saved only in the Downloads folder. function myFunction() { var hiddenElement = document.createElement('a'); hiddenElement.href = 'data:attachment/text,' + encodeURI(JSON.stringify(dict)); hiddenElement.target = '_blank'; hiddenElement.download = 'dict.json'; hiddenElement.click(); } I want to save it on Django's media folder per user. media > {{user}} > dict.json Any help highly appreciated. -
How to send UPDATE request to Django Rest API with Redux
I'm beginner on Django Rest & React and I'm trying write a task manager application, Django Rest API on backend & react on frontend. How can I send an update request to Django Rest API from React-Redux? Which method I have to use? POST or PUT? I added a check button to leads. So when a lead is completed, I want to set is_completed: true & send an update request to Django rest API. There is how I send add tasks with post request: handleSubmit= e=>{ e.preventDefault(); const { task, tag1, tag2, tag3,is_completed } = this.state; const newTask = {task,tag1, tag2, tag3,is_completed} this.props.addTask(newTask) } addTask action export const addTask = (task) => (dispatch,getState) => { axios.post('/api/tasks/',task,tokenConfig(getState)) .then(res=>{ dispatch({ type : "ADD_TASK", payload : res.data, }); }) .catch(err=>console.log(err)) } //takenConfig function from another js file const tokenConfig = getState=>{ // Get token from redux state const token = getState().auth.token; // Set Headers const config = { headers: { 'Content-Type':'application/json' } } // Add headers config if there is token if (token) { config.headers['Authorization'] = `Token ${token}`; } return config; } my reducer else if (action.type ==='ADD_TASK') { return { ...state, tasks:[...state.tasks, action.payload] } } And its perfectly working. But I couldn't … -
How do I view joins in my raw sql in django?
I have a model that stores raw sql in one of its fields like: class MyModel(models.Model): raw_sql = models.TextField(blank=True) # other fields Now I want to see that on tables is the join being applied. I am doing this to prevent unnecessary joins while executing these queries. Is there any way, I can see the models from the raw_sql?