Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamically filtering fields in formset
I have a view: class SummaryListView(ListView): model = MyModel MyModelFormSet = modelformset_factory( MyModel, fields=('field1', ), formset=BaseMyModelFormSet, ) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) fields = get_fields(self) formset = self.MyModelFormSet(request=self.request) context['formset '] = formset return context def post(self, request, *args, **kwargs): formset = self.MyModelFormSet(request.POST, request=request) if formset.is_valid(): formset.save() return redirect('') I want to pass MyModelFormSet a list of fields to render which I generate with a function get_fields() which takes self as an argument. Now, I can place MyModelFormSet inside get_context_data, but then how do I access it from post? Or can I pass MyModelFormSet a variable from inside the get_context_data? -
Django: Add objects.all.count() to aggregate?
I've been searching how to add X.objects.all().count() result to an existing aggregate logic. I seen that Count() will only work with a foreign key relationship, so how can I add an 'additional field' with the .count() results to the aggregate with only writing it in one block. This is my custom action (Does not work): from django.db.models.functions import Coalesce from django.db.models import Min, Avg, Max, Value as Val, IntegerField @action(detail=False, methods=['get']) def get_stats(self, request, pk=None): total_ads = Ad.objects.all().count() stats = Ad.objects.aggregate( price_min = Coalesce(Min('price'), Val(0)), price_avg = Coalesce(Avg('price'), Val(0.0)), price_max = Coalesce(Max('price'), Val(0)), ads_total = Val(total_ads, output_field=IntegerField()), ) return Response(stats) Error: TypeError: ads_total is not an aggregate expression -
Refer to child class foreign key in base abstract model
I am trying to access the child model foreign key in base abstract model so I don't have to repeat the foreign key in each of the child model. Here is my code: class BaseModel(models.Model): child_field = models.ForeignKey(to='child_class_either_ModelA_OR_ModelB') class Meta: abstract = True class ModelA(BaseModel): .... class ModelB(BaseModel): .... I want to refer the child model in base abstract model. Is there a way to use an child model in base model? -
Django static images receive 404 error in windows production
I am trying to deploy a Django app on a Windows server. I am able to make the pages load and am using wgsi. I am also able to load pages with images when using runserver, just not when accessing via the webserver. I have DEBUG = False. My settings.py looks like this: STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] STATIC_ROOT = "/assets/" When I do collectstatic, my files are copied into the assets folder. But, when served, I receive: GET http://localhost:8000/static/js/main.js net::ERR_ABORTED 404 (Not Found) -
Django Link a submodel to the main model and display the sub-model widgets on my view with ModelForm
I need to link a "sub-model" with a "main model" to then display a form on my view For the moment I manage to display the form but not the fields of the form of the "sub-model" Here is what I have on my web page: You can see that the info field does not offer me to enter information but only selected among the one that exists outside I would like it to be like the others, that the user is free to indicate what he wants Here is the "main model" class Dispositif(models.Model): info = models.ForeignKey(Infos, on_delete=models.CASCADE) name = models.CharField(max_length=32, default="Nom du dispositif") place = models.CharField(max_length=128, default="Adresse du dispositif") Here is the "sub-model" class Infos(models.Model): comment = models.CharField(max_length=128) chef = models.CharField(max_length=32) and here the ModelForm: class DispositifForm(ModelForm): class Meta: model = Dispositif fields = ['name', 'place', 'info'] widgets = { 'info.comment': django.forms.TextInput(attrs={'placeholder': 'Comment'}), 'name': django.forms.TextInput(attrs={'placeholder': 'Nom du dispositif'}), 'place': django.forms.TextInput(attrs={'placeholder': 'Adresse du dispositif'}) } I tried to create a widget like this but it shouldn't be this way: 'info.comment': django.forms.TextInput(attrs={'placeholder': 'Comment'}), I could very well group everything in the same model but then I will add fields and I prefer to leave with a good organization from the … -
Strange ViewSet Behavior - Django Rest Framework
I set up a ModelViewSet and ModelSerializer for my model Dataset but noticed some strange behavior. When I create new dataset instances the rest-endpoint does not reflect the new additions. However, if I print out the count of dataset instances I can clearly see the new datasets reflected. Has anyone seen something like this before? class DatasetViewSet(viewsets.ModelViewSet): queryset = Dataset.objects.all().order_by('-created_at') serializer_class = DatasetSerializer def get_queryset(self): # correctly prints the number of instances print('new call: ', Dataset.objects.count()) # only prints the correct number when *one* new instance is added, # afterwards new instances are not recognized print('queryset: ', self.queryset.count()) return self.queryset The first print statement in the get_queryset method above will print out the correct number of instances (i.e. 5, 6, 7, 8, ... as I keep adding more instances). The second print statement only captures the first new instance and then remains constant (i.e. 5, 6, 6, 6, ... even as I keep adding more instances). Furthermore, in the example above, a GET request will only yield 6 instances even as I keep adding more. What is going on here and how I can begin to debug this situation? -
Unique Class or extend Class in Python Django
In the following situation, I have a feeling I need to ?extend? the Migration class instead of re-stating it in the second module. migrations/0001_initial.py: class Migration(migrations.Migration): initial = True dependencies = [('auth', '0012_alter_user_first_name_max_length'),] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, ...)), ('password', models.CharField(max_length=128, ...)), ... migrations/0002_venue.py: class Migration(migrations.Migration): dependencies = [('app', '0001_initial'),] operations = [ migrations.CreateModel( name='Venue', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,...)), ('name', models.CharField(blank=True, max_length=150, ...)), ('address', models.CharField(blank=True, null=True, ...)), ... Help? -
Can't get form to work for comment replies
I can't seem to get the post form to work for post replies (comments for a post). It works via the Django admin but I can't seem to display the form on the template which I think is due to my noobish backend. Layout of the "site": Front: Frontpage contains all posts which shows 3 latest comments for said posts (this part works). Posts: When you want to read a post it redirects you to another page which shows selected post (as normal) and here you can see all comments for the post (currently added directly via Django Admin). Here I want a form so the visitor can reply to the post. (This part does not work). Forms: from django import forms from django.forms import widgets, TextInput, ModelForm from .models import Comments, Post class PostForm(ModelForm): class Meta: model = Post fields = ['entry', 'post_image'] labels = { 'entry': "Post something spoopy:", } widgets = { 'entry': widgets.Textarea(attrs={'rows':10, 'cols':5}) } def __init__(self, *args, **kwargs): super(PostForm, self). __init__(*args, **kwargs) for name, field in self.fields.items(): field.widget.attrs.update({'class': 'input'}) class CommentForm(ModelForm): class Meta: model = Comments fields = ['comment_entry', 'comment_image'] labels = { 'comment_entry': "Answer!", } def __init__(self, *args, **kwargs): super(CommentForm, self).__init__(*args, **kwargs) for name, … -
Pythonanywhere - something went wrong - error running wsgi - modulenotfound error
I am new to django and I am doing a coursera course with little applications deployed on pythonanywhere, which has worked well so far. No I am stuck, because does not load at all. Pythonanywhere says that Something went wrong. This is the error log from pythonanywhere. Error running WSGI application ModuleNotFoundError: No module named 'django_extensions' This is my WSGI file """ WSGI config for mysite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() This is my settings.py file, not the entire one but the installed apps: DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'ads.apps.AdsConfig', # Extensions - installed with pip3 / requirements.txt 'django_extensions', 'crispy_forms', 'rest_framework', 'social_django', 'taggit', 'home.apps.HomeConfig', ] This is my urls.py, not the entire one, but the crucial part. import os from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls import url from django.contrib.auth import views as auth_views from django.views.static import serve urlpatterns = [ path('', include('home.urls')), # Change to ads.urls path('ads/', include('ads.urls')), path('admin/', admin.site.urls), … -
How to connect locally hosted Django app to Dockerized Postgres database
I'm learning Docker and after few time, I'm able to run a postgres database and a django app in two different container. The problem is that with docker, I can't use Pycharm's debugging tools. So I would like to run my code without docker but keep the database in its container. But I can't connect Dockerized postgres dabatase and locally hosted Django App. I always have this error : psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Program Files (x86)\Python37-32\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Program Files (x86)\Python37-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check_migrations() File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\core\management\base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\migrations\loader.py", line 53, in __init__ self.build_graph() File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\migrations\loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Nicolas Borowicz\Desktop\ProjetSolSol\PlateformeClient\env\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor return self._cursor() File … -
run two list same time on django template
how to run two list same time on Django-templates without using zip function. views.py l1=[1,2,3] l2=[4,5,6] return render(request,'home.html',{'l1':l1,'l2':l2}) I am passing list this type on my template page now need to run both list same time on template. how can I do this. Note---only I want do this on my template page -
How to add extra data to TextChoices?
How Can I add extra data to django.db.models.TextChoices? class Fruit(models.TextChoices): APPLE = ('myvalue', True, 'mylabel') such that: >>> Fruit.APPLE.is_tasty True >>> # And it still works otherwise >>> Fruit.APPLE.value 'myvalue' >>> Fruit.APPLE.label 'mylabel' -
Migrations in DJango
I am having DJango migrations problem while making migration following error is coming. enter image description here enter image description here enter image description here When I run my applications using python manage.py runserver it shows this :- enter image description here However running python manage.py makemigrations shows no changes detected And Above three images are result after running python manage.py migrate. what is the problem with this ? -
Nginx 502 bad gateway error when deploying django
I'm trying to set up a VPS Django server with nginx, however, I'm running into a 502 Bad Gateway error when I reload the nginx server with the following settings: sudo nano /etc/nginx/sites-available/project server { listen 80; server_name domainname.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/Slide-Hackers-Web/src/static; } location /media/ { root /home/ubuntu/Slide-Hackers-Web/src/static; } location / { include proxy_params; proxy_pass https://unix:/home/ubuntu/Slide-Hackers-Web/src/project.sock; } } I execute the commands in this order sudo nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful sudo ln -sf /etc/nginx/sites-available/project /etc/nginx/sites-enabled sudo systemctl restart nginx sudo ufw allow 'Nginx Full' If I exclude domainname.com from the server_name, then it responds with the classic "Welcome to nginx!" page, however, if I leave it, it responds with "502 Bad Gateway nginx/1.18.0 (Ubuntu)". I'm clueless as to what I'm supposed to do, any help? P.s, gunicorn runs in the background and is active: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: active (running) since Tue 2021-08-17 10:38:05 UTC; 1h 58min ago Main PID: 31290 (gunicorn) Tasks: 4 (limit: 2272) Memory: 90.0M CGroup: /system.slice/gunicorn.service ├─31290 /home/ubuntu/Slide-Hackers-Web/env/bin/python /home/ubuntu/Slide-Hackers-Web/env/bin/gunicorn --access-logfile - --workers 3 … -
How do Django authorization decorators (such as: login required) work?
I am trying to better understand "behind the scenes" of the Django authorization decorators. Although I think I understand decorators in general, I find it difficult to understand the authorization decorators code. Is there any "line by line" explanation of the code (https://docs.djangoproject.com/en/2.2/_modules/django/contrib/auth/decorators/)? -
How to group results into array based on multiple similar values, Django Model
I have array as follows [ { "WarehouseId": 1, "ShippingCarrierId": 1, "PostalCodeType": "ShipToCustomer", "TimeStart": "1970-01-01T06:00:00.000Z", "TimeEnd": "1970-01-01T15:59:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 1, "PostalCodeType": "ShipToCustomer", "TimeStart": "1970-01-01T16:00:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 1, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 1, "PostalCodeType": "ShipToCustomer", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T05:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 0, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 2, "ShippingCarrierId": 2, "PostalCodeType": "ShipToCustomer", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T15:59:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 2, "ShippingCarrierId": 2, "PostalCodeType": "ShipToCustomer", "TimeStart": "1970-01-01T16:00:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 1, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 3, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T15:59:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 3, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T16:00:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 1, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 2, "ShippingCarrierId": 4, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T15:59:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 2, "ShippingCarrierId": 4, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T16:00:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": 1, "PickupTime": "1970-01-01T11:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 5, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T00:00:00.000Z", "TimeEnd": "1970-01-01T16:22:00.000Z", "PickupTimeSlot": "PM", "DaysToAdd": 0, "PickupTime": "1970-01-01T17:00:00.000Z" }, { "WarehouseId": 1, "ShippingCarrierId": 5, "PostalCodeType": "ShipToDS", "TimeStart": "1970-01-01T16:23:00.000Z", "TimeEnd": "1970-01-01T23:59:00.000Z", "PickupTimeSlot": "AM", "DaysToAdd": … -
Problem updating the values of a table in django
In the bast_tag.py file I fetch the information from the site settings table which has only one row and then display it in the template. When I want to update the values in this row in the admin panel, the information is not updated, in order for the values to be updated, I have to stop the server and run the command 'py manage.py runserver' again! please guide me. Thank You base_tag.py: _site = Settings.objects.first() @register.simple_tag def title_site(): return _site.title @register.simple_tag def description_site(): return _site.description @register.simple_tag def five_icon_site(): return _site.five_icon.url @register.inclusion_tag("wooden/partials/footer.html") def footer_tag(): context = { 'about': _site.about, 'logo': _site.logo_ftr.url, } return context footer.html: <div class="d-flex justify-content-around align-items-center flex-column ftr_center wow fadeInUp"> <img src="{{logo}}"> <p class="text-center"> {{about}} </p> </div> head tag in index.html: <title>{% title_site %}</title> <meta name="description" content="{% description_site %}"> -
How to retrieve the user's url logged in with google on django
archive.html : <div class="img-description"> <img src="{{ user.urlprofile }}" class="avatar-url" alt=""> {% if user.get_full_name != '' %} <span id="helloUser-des" class="mr-2 d-none d-lg-inline text-gray-600 small">{{ user.first_name | title }}!</span> {% else %} <span id="helloUser-des" class="mr-2 d-none d-lg-inline text-gray-600 small">{{ user.username | title}}!</span>!</span> {% endif%} </div> Thank you very much in advance -
Django TestCase with Postgresql brokes PrimaryKeys
I have setted up postgresql at my django application, and after that my TestCases had broken. It always throwed ObjectDoesNotExists at any test method after first one. I have narrowed down the issue, and each time test method is called, all objects created at setUp, get their primary keys + 1. Maybe you don't understand but see my code: class ProfileTestCase(TestCase): def setUp(self): user1 = User.objects.create(username="Unit1", email="testuser1@gmail.com", password="123456") user1_profile = Profile.objects.create(user=user1, first_name='User1', last_name='User1') def test_smth0(self): print(Profile.objects.all()) print(Profile.objects.filter(first_name='User1')[0].id) def test_smth1(self): print(Profile.objects.all()) print(Profile.objects.filter(first_name='User1')[0].id) def test_smth2(self): print(Profile.objects.all()) print(Profile.objects.filter(first_name='User1')[0].id) And here is console output for this tests Why this is happening and how to fix this. Here is my connections settings to postgresql database in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myapp_db', 'USER': 'admin', 'PASSWORD': 'MYPASSWORD', 'HOST': '127.0.0.1', 'PORT': '' } -
What happens when an object is created in Django admin?
I am new to Django. When we learn Python it was taught that when an object is created, the init function is initialized and all the variables that are passed are saved using self keyword. For eg: class Movie: def __init__(self,name,caption,budget): self.name = name self.caption = caption self.budget = budget obj1 = Movie('Taken',"Fight movie",250) obj2 = Movie('Wanted','Comedy movie',300) print(obj1.name) print(obj2.name) Here, in the above example when I clicked the run, two objects are initialized and saved. Hence when I print both the movies names are printed. Now when I read the documentation in Django, it says that when we create an object of a model in Django admin, it calls the save function to save the instance. Until now I was in the assumption that, the dunder init will be called just like in plain Python. The Django model looks like this: class Employee(models.Model): name=models.Charfield() dept=models.Charfield() def__str__(self): return self.name Also, here I don't see any init function explicitly defined. But when I ctrl + click on the Model, I can see a number of functions defined and there is init as well as save function defined. Now I want to know which function is called when we save any object … -
Django - Searchbar in Listview | How to define and process it
i'm totally new to django and python. I would like to add a search bar working on my Listview page as I've seen on the Django admin-site. I've seen a lot of django docs, many explainations and plenty of tutorials on the web but i have to say that I'm confused and could not find a solution for my problem. What i want to do: I have a page with a (class-based)ListView that presents 5 fields from my table. I would like to add a search bar working on 2 of these 5 fields (object id and description) as i've seen on the Django admin-site. Looking at the Docs and web these are a lot of different propositions to do that(queryset, filter, context, Q...). Personally I would like to work with the context. I tried to recover info from my searchbar but what I have implemented and tried since now is not working. Could someone help me on this matter? What is the best practice and approach? Indications on how to manage this with some code exemple? Thanks in advance! #HTML <form method="GET"> <input type="text" name="q" value="" id="searchbar" autofocus> <input class="button" type="submit" value="Search"> </form> #View class AircraftListView(ListView): model = Aircraft … -
Select related rows from different databases
There is table A (located in the default database) and table B (located in the logs database). Table B has a_id field, which contains the ID for the corresponding record from table A, which is mapped to another database. Are there any native Django ways to join the list of records from table B to the corresponding records from table A? -
how to return multiple file html in render request django?
I would like to return multiple values in multiple html files in a django view i tried that but it was a mistake def my_view(request): #bla bla bla... context ={ 'value_1':value, #.... } return render(request,{'file_1.html','file_2.html','file_2.html'},context) I have already separated it into 3 different views but the problem is that they have the same source and if I separate them I had 4 min of execution time, then the best is to combine them -
fa fa toggle icon is not changing when liked
I am building a small social media app . I made a like dislike button in django (JsonResponse). I am trying to fill the color in icon when clicked (liked) BUT it is not chaning when liked. views.py def post_like_dislike(request, user_id): post = get_object_or_404(Post, pk=user_id) # Like if request.GET.get('submit') == 'like': if request.user in post.dislikes.all(): post.dislikes.remove(request.user) post.likes.add(request.user) return JsonResponse({'action': 'undislike_and_like'}) elif request.user in post.likes.all(): post.likes.remove(request.user) return JsonResponse({'action': 'unlike'}) else: post.likes.add(request.user) return JsonResponse({'action': 'like_only'}) # Dislike elif request.GET.get('submit') == 'dislike': if request.user in post.likes.all(): post.likes.remove(request.user) post.dislikes.add(request.user) return JsonResponse({'action': 'unlike_and_dislike'}) elif request.user in post.dislikes.all(): post.dislikes.remove(request.user) return JsonResponse({'action': 'undislike'}) else: post.dislikes.add(request.user) return JsonResponse({'action': 'dislike_only'}) else: messages.error(request, 'Something went wrong') return redirect('mains:all_stories') template.html <form method="GET" class="likeForm d-inline" action="{% url 'post_like_dislike' post.id %}" data-pk="{{ post.id }}"> <span id="id_likes{{post.id}}"> {% if user in post.likes.all %} <p style="color:#065FD4;display: inline">{{post.likes.count}}</p> {% else %} <p style="color:black;display: inline">{{post.likes.count}}</p> {% endif %} </span> <button class='likeForm' value="like" type="submit"><i class="btn fal fa-sort-up fa-6x fa-lg post-buttons "></i></button> </form> <script> document.addEventListener('DOMContentLoaded', function () { window.addEventListener('load', function () { // Like $('.likeForm').submit(function (e) { e.preventDefault(); let thisElement = $(this) $.ajax({ url: thisElement.attr('action'), data: { 'submit': 'like', }, dataType: 'json', method: 'get', async: false, // Have a look into this success: function (response) { let likes = … -
How to use clear checkbox for ajax fileupload with modelform django
i am quite a noob on django and ajax so please excuse me if there is some big mistake or ugly code in my work. So I am working on an app where the user must upload different documents in a modelForm (linked to another model in 1:1). The user will probably not upload all the documents at once. I am using ajax to have a progress bar for the user. So far, the upload works fine, replacing document with another works too, but i have a problem when it comes to using the clear checkbox that django provides when a document has already been uploaded. Using submit and standard Post, the clear checkbox works fine. Using ajax it doesnt work. models.py (not posting everything since there is over 25 FileFields) class MandatVenteUpload(models.Model): mandat= models.OneToOneField('mandat_vente.MandatVente', on_delete=models.CASCADE, primary_key=True) acte_propriete = models.FileField(upload_to=content_file_name, max_length=60 ,null=True, blank=True) carte_identite= models.FileField(upload_to=content_file_name, max_length=60 ,null=True, blank=True) diagnostic_amiante= models.FileField(upload_to=content_file_name, max_length=60 ,null=True, blank=True) diagnostic_assainissement= models.FileField(upload_to=content_file_name, max_length=60 ,null=True, blank=True) diagnostic_electricite= models.FileField(upload_to=content_file_name, max_length=60 ,null=True, blank=True) [...] views.py (using exception since if no document has been uploaded yet, the model does not exist) @login_required def mandat_vente_upload_view(request, num_mandat_upload): mandat_upload=get_object_or_404(MandatVente, id = num_mandat_upload) if mandat_upload.createur == request.user or request.user.is_staff: try: form_upload = MandatVenteUpload.objects.get(mandat=mandat_upload.id) form=MandatVenteUploadForm(mandat_upload, request.POST …