Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django | REST | Add of top level JSON field breaks filtering option
I have to work ListAPIView view, via which I can filter via django-filter values. But I need to add an object in JSON (because AMP HTML needs that) and when I add this, It will break this filtering. When I use this view, filtering is works great: class TypeAPIView(generics.ListAPIView): permission_classes = (AllowAny, ) queryset = Type.objects.all() serializer_class = TypeSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ('code', ) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) But when I want to add a top level JSON object, it will breaks a filtering option: class TypeAPIView(generics.ListAPIView): permission_classes = (AllowAny, ) queryset = Type.objects.all() serializer_class = TypeSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ('code', ) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset, many=True) # --- modified from here --- custom_data = { 'vehicles': serializer.data } return Response(custom_data) # --- END modified from here --- Is possible to add a top-level JSON object and keep the filtering of django-filter working? Thank you! -
Django bulk_update with select_for_update in rows lock
Is that be locked for all users rows with last_name='Smith' one time? or lock only one row every time? Will bulk_update work in this lock? with transaction.atomic(): users = list(urs.select_for_update().filter(last_name='Smith').only('updated')) for user in users: user.updated = '2020-12-01' UserReceiver.objects.bulk_update(users) -
django-datatable-view==0.9.0 Django 3.1.3: ImportError: cannot import name 'FieldDoesNotExist'
I am using the latest package django-datatable-view 0.9.0 in django 3.1.3 (upgrading from django 1.8.6) When a I run manage.py run server I get the following error: File "/usr/local/lib/python3.6/site-packages/datatableview/__init__.py", line 3, in <module> from .datatables import Datatable, ValuesDatatable, LegacyDatatable File "/usr/local/lib/python3.6/site-packages/datatableview/datatables.py", line 12, in <module> from django.db.models.fields import FieldDoesNotExist ImportError: cannot import name 'FieldDoesNotExist' Upgrading the package is not an option as I am already using the latest package. What can I do to fix the error? Thank you for your help -
How do I find active directory information for ldap?
I was tasked with implementing Django LDAP and I'm lost. For one, I'm trying to search for users anonymously with: AUTH_LDAP_BIND_DN = "" AUTH_LDAP_BIND_PASSWORD = "" AUTH_LDAP_USER_SEARCH = LDAPSearch( "ou=??,dc=something,dc=somethingelse,", ldap.SCOPE_SUBTREE, "(uid=%(??)s)" ) What should I put for the organizational unit? I know it's a container of the active directory, but how do I find that out - what our organization uses? -
Reverse for 'action' with arguments '('',)' not found
I have error that seemed to happen to some other people, still I didn't figure out what am I doing wrong, so asking you all for help. Can you please support me with my code? views.py: def index(request): context = {'cards': Card.objects.all()} return render(request, 'mtg/index.html', context) def lookup(request, card_name): context = {'card_lookup': Card.objects.all()} return render(request, 'mtg/index.html', context) def action(request, card_name): card = get_object_or_404(Card, pk=card_name) # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('mtg:tmpl', args=card_name)) urls.py: app_name = 'mtg' urlpatterns = [ path('', views.index, name="index"), path('<str:card_name>/img', views.lookup, name='img'), path('<str:card_name>/action', views.action, name='action'), ] index.html: <body> <form class="wrap" action="{% url 'mtg:action' card.name %}" method="post"> <input class="searchTerm"/> <button class="center" name="search">Search for synergy</button> <button class="center" name="lookup">Lookup a card</button> </form> {% if lookup_card %}<div>{{ card_lookup }}</div>{% endif %} </body> -
Database error conection using django-mssql-backend
I have to update an old django proyect that use django 1.8, pyodbc 3.0.10 and django-pyodbc-azure 1.8.3.0 with python 2.7.11. For the new version I need to use django 3.1.3, pyodbc 4.0.30 and django-mssql-backend 2.8.1 with python 3.9.0 the main difference is the use of django-mssql-backend 2.8.1 instead of django-pyodbc-azure 1.8.3.0, my settings.py have this configuration: 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'dn_name', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'host\instance', 'PORT': '1433', 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0', 'unicode_results': True, }, }, Using the old version the connection works correctly but when I update the proyect gives me this error: ('08001', '[08001] [Microsoft][SQL Server Native Client 11.0]TCP Provider: No connection could be made because the target machine actively refused it. (10061) (SQLDriverConnect); [08001] [Microsoft][SQL Server Native Client 11.0]Login timeout expired (0); [08001] [Microsoft][SQL Server Native Client 11.0]Invalid connection string attribute (0); [08001] [Microsoft][SQL Server Native Client 11.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (10061)') For what I know I have the correct … -
Django understanding uniq constraint on nested models
Having the following model class Department(models.Model): name = models.CharField(max_length=10) class Person(models.Model): name = models.CharField(max_length=10) class Position(models.Model): name = models.CharField(max_length=10) person = models.ForeignKeyField(to=Position) department = models.ForeignKeyField(to=Department) I would like to assure that a person is unique in one department (means can only have one position in one department). My aproach would be to use a constraint on position, but I cannot figure out What Q statement to use for condition. class Position(models.Model): name = models.CharField(max_length=10) person = models.ForeignKeyField(to=Position) department = models.ForeignKeyField(to=Department) class Meta: constraints = UniqueConstraint(fields=['person'], condition=Q(???)) I would expect there to be something like Q(<all_departments>) which i could not find -
How to accept a django.http.HttpResponse object containing a csv file in Ajax?
When I click a button on the html page, I want to trigger a query in backend database, creating a csv file specific to the request and then download it. I managed to pass data to django, however, I cannot find a way to trigger download as I click the button and I don't know how to make ajax accept django.http.HttpResponse containing csv. Meanwhile I find everything is ok if I visit the url directly, but when I use ajax it's not the case. For illustration, My urls.py is: url('export/',views.export) My views.py is: def export(request): if request.method == 'GET': export_list = json.loads(request.GET['id_list']) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' writer = csv.writer(response) writer.writerow(['column_1','column_2']) for id in export_list: item = Item.objects.get(id=id) witer.writerow([item.attr_1,item.attr_2]) return response And my html is <a class="btn btn-primary" id="export" rel="external nofollow" role="button" style="margin-left: 30px;">export to csv</a> $("#export").click( function(){ data.id_list = JSON.stringify(paperids); data.csrfmiddlewaretoken = '{{ csrf_token }}'; $.ajax({ url: '/export/', type: 'GET', data: data, dataType: "text/csv", headers:{ 'Accept': 'text/csv','Content-Type': 'text/csv' }; success: function(result){ console.log(result); }, error: fucntion(){ console.log("why"); } }) How can I manage to download the csv when clicking the button? -
Django 3.1.3 Field 'id' expected a number but got '{{ \r\nchoice.id }}'
I'm stuck at Django's official tutorial (see Writing your first Django app, part 4). https://docs.djangoproject.com/en/3.1/intro/tutorial04/ I get the following error: In this Django project, inside the poll app I'm making, we're supposed to make a vote() view in views.py which should process the POST request data of the poll and redirect us to the results() view (there's no template for the vote()view, it's just in charge of processing the data we send through the poll). At first I thought I had a typo error, but I then copy-pasted everything directly out of the documentation tutorial (which I linked at the beginning of this question) and the error persisted. Results.html <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }} </li> {% endfor %} </ul> <a href="{% url 'polls:detail' question.id %}">Vote again?</a> Index.html {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} Detail.html <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice … -
Django form is not submitting, form valid method not working
Not sure why my form is not submitting. When i click the submit button nothing happens and there is no POST request. I've tried changing the button and the html with no real avail. Perhaps the form valid method is not working? Any help would be appreciated, also if anyone knows how to properly prevent multiple form submissions in django that would help me a lot! heres my view from forms.py import SignUpForm class RegisterKeyView(CreateView): form_class = SignUpForm template_name = 'accounts/RegisterKeyView.html' def get(self,request,*args,**kwargs): ... return render(request, self.template_name, {'form': self.form_class }) def form_valid(self,form, **kwargs): ... form.instance.save() ... login(self.request, self.request.user) return redirect('user-dashboard') heres my form class SignUpForm(UserCreationForm): username = forms.CharField(max_length=30) email = forms.EmailField(max_length=200) class Meta: model = User fields = ('username', 'email','school', 'password1', 'password2', ) heres my template {% extends "accounts/base.html" %} {% load crispy_forms_tags %} {% block content %} <form method = "POST" class="form-signin border rounded "> {% csrf_token %} {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Profile Info</legend> {% crispy form %} </fieldset> <div class="form-group"> <button class="mt-4 btn btn-lg btn-primary btn-block" type="submit">Login</button> </div> </form> {% endblock content %} -
Why Django Form is not empty but invalid?
I fill the form then submit and see that it's invalid but when I print my form after submit I see that it's not empty. I don't understand why it's invalid. I tried using forms.ModelForm then forms.Form both of them ended up in the same result. print result of field_errors in my view at below: FIELD_ERRORS: [('İsim', []), ('Cins', []), ('Yeni Cins Ekleme', []), ('Cinsiyet', []), ('Ağırlık', []), ('Boyut', []), ('Yeni Boyut Ekleme', []), ('Renk', []), ('Yeni Renk Ekleme', []), ('Doğum Tarihi', []), ('Fotoğraflar', ['Bu alan zorunludur.'])] My forms.py from django import forms from .models import NewBorn,Size,Color,Breed class NewDogForm(forms.Form): name = forms.CharField(label='İsim',widget=forms.TextInput(attrs={'class':'form-control'})) breed = forms.ModelChoiceField(queryset=Breed.objects.all(),required=False,label = 'Cins',widget=forms.Select(attrs={'class':'form-control'})) yeni_cins_ekleme = forms.CharField(required=False,label = 'Yeni Cins Ekleme') gender = forms.CharField(label = 'Cinsiyet',widget=forms.TextInput(attrs={'class':'form-control'})) weight = forms.CharField(label = 'Ağırlık',widget=forms.TextInput(attrs={'class':'form-control'})) size = forms.ModelChoiceField(queryset=Size.objects.all(),required=False,label = 'Boyut',widget=forms.Select(attrs={'class':'form-control'})) yeni_boyut_ekleme = forms.CharField(required=False,label = 'Yeni Boyut Ekleme') color = forms.ModelChoiceField(queryset=Color.objects.all(),required=False,label = 'Renk',widget=forms.Select(attrs={'class':'form-control'})) yeni_renk_ekleme = forms.CharField(required=False,label = 'Yeni Renk Ekleme') date_of_birth = forms.DateField(label='Doğum Tarihi',widget=forms.DateInput(format='%d-%m-%Y')) photo = forms.CharField(label = 'Fotoğraflar',widget=forms.TextInput(attrs={'class':'form-control','type':"file",'multiple accept':'image/*'})) My views.py def yavruKopeklerDuzenleme(request): title = "Minik Patiler - Yavru Köpekler Düzenleme Sayfası" print("POST ÜSTÜ") if request.method == 'POST': form = NewDogForm(request.POST, request.FILES) print("IS_VALID ÜSTÜ") print("FORM: ",form) field_errors = [ (field.label, field.errors) for field in form] print('FIELD_ERRORS: ',field_errors) if form.is_valid(): print("I'm HERE") … -
Placeholder not coming in django forms
When I'm trying to build out a django form, the placeholder for the input field that I'm specefiying does not come. Here is my forms.py code: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('username','email','password1','password2') widgets = { 'username':forms.TextInput(attrs={'placeholder':'SamyakJain2509'}), 'email':forms.EmailInput(attrs={'placeholder':'youremail@example.com'}), 'password1':forms.PasswordInput(attrs={'placeholder':'not-crackable'}), 'password2':forms.PasswordInput(attrs={'placeholder':'not-crackable'}), } I should get a placeholder for all my form fields, but I only get the placeholder for my username field. Here is the output: What is the problem? -
Form Field Calculations in Template
I am creating a stock market site and would like to show the total purchase value live as the user is typing rather than as an error during form clean. The calculation involves multiplying two fields. The first is a quantity field which is just a number the user inputs. The second is the stock which is a drop down for a foreign key. The user selects a stock and an attribute of the stock is the price. I would like to multiply these fields and display the result each time a user alters a field. I would also like to do this with a model form if possible. I have tried using {{ form.field.value }} within the template to get one the fields but I cannot get it to update for a change. For the stock field, I think my best bet is to create a matching array in javascript and once I can get a live updating form value match it to the stock price from the array. Another possibility may be using getElementById with the field id but I have been unable to get that to work so far as well. Here is an example not made … -
Prometheus setup for a load balanced Django application
I have a doubt with respect to Prometheus setup for Django applications. If we have a load balancer which redirects to three application servers where the Django applications are running. Which of these setups will work and is optimally correct? Having Prometheus installed in one of the application servers and then having a job for every Django application that needs to be monitored. In this case, should we provide the host application details for all the application servers? Basic Prometheus setup Idea? Will installing Prometheus on any server and mentioning all the Django applications details in the targets entry in prometheus.yml file work? - Do we need to have ssh trust set up in this case when the setup has to be done like this? It will be very helpful if you guys please give some insights on this. If there is any other better way to configure Prometheus, please mention that as well. -
Email Problem Django: SMTP AUTH extension not supported by server
I'm currently making a Django website want to make sure that my user gets the email I sent but I get it in the console. Nothing is working. I'm using Django version 2.1.5 if it helps. Please help me!! Here is my code: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TDS = False EMAIL_HOST_USER = 'email' EMAIL_HOST_PASSWORD = 'password' Just saying, this happens if I use the EMAIL_BACKEND = 'django.core.mail.backends.smpt.EmailBackend' method: SMTPNotSupportedError at /reset/ SMTP AUTH extension not supported by server. Again, please help!!!! -
NoReverseMatch at /api/users/request-reset-email/
This is not duplicate issue, I have already referred old question, but no answer was found. I am trying to implement rest password functionality using Django rest framework. But I am getting below error.. Reverse for 'api/password_reset_confirm2' with arguments '('uidb64', 'token')' and keyword arguments '{}' not found. 0 pattern(s) tried: [] If you look the patters searched error shows, it was unable read any url patters that are configured in URL.py. That is the worry. Reset Password Class: class RequestPasswordResetEmailAPIView(GenericAPIView): serializer_class = ResetPasswordEmailSerializer def post(self,request): serializer = self.serializer_class(data=request.data) email = request.data.get('email','') if User.objects.filter(email=email).exists(): user = User.objects.get(email=email) uidb64 = urlsafe_base64_encode(smart_bytes(user.id)) token = PasswordResetTokenGenerator().make_token(user) current_site = get_current_site( request=request ).domain relativeLink = reverse('api/password_reset_confirm2' ,args={'uidb64':uidb64, 'token': token} ) absurl = 'http://'+current_site+relativeLink email_body = 'Hello'+absurl data = {'email_body': email_body, 'to_email': user.email, 'email_subject': 'Reset password link' } Util.send_email(data) return Response('Success') My url.py for authentication app looks like this urlpatterns = [ url(r'^user/?$', UserRetrieveUpdateAPIView.as_view()), url(r'^users/?$', RegistrationAPIView.as_view()), url(r'^users/login/?$', LoginAPIView.as_view()), url(r'^users/request-reset-email/',RequestPasswordResetEmailAPIView.as_view(), name='users/request-reset-email'), url(r'^users/password-reset-confirm/(?P<uidb64>[-\w]+)/(?P<token>[-\w]+)/$', PasswordResetTokenCheckAPIView.as_view(), name='password_reset_confirm2'), # path('password-reset/<uidb64>/<token>/', RequestPasswordResetEmailAPIView.as_view(), name='api/password_reset_confirm'), ] And in Main url.py, urls are connfigured like this url(r'^api/', include('apps.authentication.urls', namespace='authentication')), Please advice, Thank you -
MapBox marker Cluster in Django
help, please I have used Django Mapbox for my project and after adding all the marker I was unable to use Marker Cluster like this plugin in the link https://docs.mapbox.com/mapbox.js/example/v1.0.0/markercluster-with-mapbox-data/ this is my code to export the marker on the map mapboxgl.accessToken = MKey; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v11?optimize=true', center: [6.83, 42.12], zoom: 4 }); {% for r in resto %} // dish of the day var today = new Date(); var thisday = today.getDay(); var weekend = "{{ r.date_de_fin|date:'m-d-Y'}}"; var end = moment(new Date()).format("M-DD-y"); var week = weekend>=end; console.log(thisday); console.log(weekend); console.log(end); console.log(week); if(week && thisday==0){ dish = '{{ r.dimanche }}'; price = '{{ r.prix_de_plat_D }}'; }else if(week && thisday==1){ dish = '{{ r.lundi }}'; price = '{{ r.prix_de_plat_L }}'; }else if(week && thisday==2){ dish = '{{ r.mardi }}'; price = '{{ r.prix_de_plat_M }}'; }else if (week && thisday==3) { dish = '{{ r.mercredi }}'; price = '{{ r.prix_de_plat_ME}}'; }else if(week && thisday==4){ dish = '{{ r.jeudi }}'; price = '{{ r.prix_de_plat_J}}'; }else if(week && thisday==5){ dish = '{{ r.vendredi }}'; price = '{{ r.prix_de_plat_V}}'; }else if(week && thisday==6){ dish = '{{ r.samedi }}'; price = '{{ r.prix_de_plat_S}}'; }else{ dish = "Désolé, il n'y a pas … -
How to get the whole data of the requesting users in Django Friendship
So I am using Django Friendship in order to make the friendship stuff in my web app. Everything is based on the documentation and set up properly. The app works properly but the problem is that I can see only the id of the users. In other words I cannot get access to the whole data of the users. from django.shortcuts import render from django.contrib.auth.models import User from friendship.models import Friend, Follow, Block def AddFriend(request, pk): other_user = User.objects.get(id=pk) Friend.objects.add_friend( request.user, other_user, message='Hi! I would like to add you') return render(request, 'friendshipapp/add_friend.html') def FriendsList(request): friends_list = Friend.objects.friends(request.user) return render(request, 'friendshipapp/friends_list.html', {'friends_list': friends_list}) def RequestsList(request): requests = Friend.objects.unread_requests(user=request.user) users_list = [] for request in requests: requesting_user = User.objects.filter(id=request) users_list.append(requesting_user) return render(request, 'friendshipapp/requests_list.html', {'requesting_users':users_list}) the urls file is set up properly in the requests_list.html I can only see the id of the users. As you can see I tried to loop through the id of the request dispatchers and get access to the user but "request" gives me object of user. How can go around this problem? Thanks in advance -
Django Reactjs object Object
While passing array of fields from reactjs - it is being passed as an object of array while getting the same in django converts it into string of Object Object. So unable to parse the object and get the values of the form fields. Example: We have a html array of fields price[] tags[], when it is passed from Reactjs it is going as addon [ {price:20, tags:"tag1"},{price:25, tags:"tag2"} ,{price:200, tags:"tag3"}] but in django restframework we get as "[ object Object, object Object]" hence unable to access the values. Any help how to solve is highly appreciated. -
How to query in python mongo where I need to get data between certain dates, where the date is stored in ISO format in Database?
Example of how date stored in db: "CreatedAt" : ISODate("2020-11-19T07:10:03.673Z") And i need query where my start date and end date is in following format: start_date = 2020-11-10 end_date = 2020-11-20 -
'a user with that username already exists' is not in Django UserCreationForm anymore?
I'm studying Django and have come across a question. In several of the Django Youtube Tutorials, I see the Youtuber using the UserCreationForm to create teh signup page and then experimenting with the form to show the viewers about the page. And there comes a time when they signups a user with perhaps a username "test1" and then tries to signup a user with the same username as "test1" and they get the error message 'a user with that username already exists' However, when I've followed these tutorials, I see that there is no error message appearing anymore and it just pops up the original UserCreationForm again in the webpage. Is this error message removed? And I've been looking through the Django Github files and the Django Documentation, but it doesn't mention anything about the username error, so... I'm thinking that it's removed, but I want to be sure. -
Django: Is it possible to add fieldset to ModelForm?
I've read Django doc and post here but could not find how to add fieldset in Django? It is possible in Django admin but doesn't seems to be the case for ModelForm (and other Django forms)... Is there an easy way? -
How and where to deploy deep learning models, as an Webapp or API ? Need complete suggesion for a beginnier
I have created a deep learning model using TensorFlow/PyTorch, and now I want to deploy it both as an Webapp and API(I guess The webapp will also use the API) To explain, suppose I have a model that detects cars, in images, and returns the co-ordinates, around the bounding box.Or it might might return the image I sent, but after drawing bbox around the cars. What things do I need to learn, better if they are related to python.(I know the webapp part would need JavaScript, but apart from that, for the backend work what do I need to learn)? I don't have clear idea about where to host the model, or how to keep it running, can I do it using Flask or Django? Where can I deploy the model? How much will it cost? Is there any free service for the deployment? I have heard about HeRoku, but not sure if its free tire will cover my requirements. Can you provide any good source(free) , where I can learn machine learning model deployment in detail.(Video or blog, both are welcomed) I believe the question is quite popular for those who want to move from playing with deep learning … -
Django ModelForm how to remade a datetime after splitdatetime before saving data
I am trying to make a beautiful form with Modelform on django. My model have three datetime. I would like the user to be able to fill them in easily on the form. I managed to get the desired display but I can't save the data as I wanted to, an error occurs. I know that this error comes from the SplitDateTimeWidget which gives me two data (date and time). I can combine both in the model but I don't know how to do it. This is my form in Frenchglish: my form This is my error in general terms: my big horrible error This is my model: DEVICE_CHOICE=[("Lucas Nuelle","Lucas Nuelle"),("Objet260 Connex3","Objet260 Connex3"),("uprintp51225","uprintp51225"),("Yumi","Yumi")] class Delay(models.Model): delayDevice=models.CharField(max_length=100,choices=DEVICE_CHOICE) orderRef=models.CharField(max_length=100,default="not known",blank=True) orderDate=models.DateTimeField(blank=True) predictedDate=models.DateTimeField() deliveryDate=models.DateTimeField() delayComment=models.CharField(max_length=500,default="no comment",blank=True) submitDate=models.DateTimeField(auto_now_add=True) ``` This is my views.py: ``` from .models import Delay,Breakdown,NonComplyingProduct from .forms import ReportDelay,ReportBreakDown,ReportNonComplyingProduct def index(request): if request.method=="POST": form=ReportDelay(request.POST).save() return redirect("/report") else: form=ReportDelay return render(request,'delayForm.html',{'form':form}) and so finally my form.py: from .models import Delay, Breakdown, NonComplyingProduct import datetime as dt class ReportDelay(forms.ModelForm): class Meta: model = Delay fields = ['delayDevice', 'orderRef', 'orderDate', 'predictedDate', 'deliveryDate', 'delayComment'] labels = { 'delayDevice': 'Appareil', 'orderRef': 'Reference de la commande', 'orderDate': 'Date de la commande', 'predictedDate':'Date de livraison prévue', 'deliveryDate':'Date de … -
"Media" folder not being created with Django's FileSystemStorage. Files don't get saved if made manually either
So, I always test out new things in a separate project and the example that I used to test this out worked. However, trying to integrate the same in my project doesn't give me the results I need. I've spent close to 4 hours on this now and nothing so far. First off, here's the code: index.html <form id="data" enctype="multipart/form-data"> <div class="col-md-4"> <label class="file"> <input type="file" id="file1" name="document" multiple> <span class="file-custom">Documents</span> <button type="button" onclick="enterdata()">Submit</button> </div> </form> <script> function enterdata(){ if ($"data")[0].checkValidity(){ alert('validity success'); var token = ''{{ csrf_token }}; alert('csrf generated'); $.ajax({ type:'POST', url:'/user', data: { doc1:$('file1').val() }, header: {'X-CSRFToken': token}, success: function(){ alert("Added"); $('#data').trigger("reset"); } }) }else{ $('data')[0].reportValidity() } } </script> views.py def testing_data(request): if request.method == 'POST': doc11 = request.POST['doc1'] request_file = request.FILES['document'] if 'document' in request.FILES else None if request_file: # save attatched file # create a new instance of FileSystemStorage fs = FileSystemStorage() file = fs.save(request_file.name, request_file) # the fileurl variable now contains the url to the file. This can be used to serve the file when needed. fileurl = fs.url(file) landform.objects.create ( mutdoc=doc11, ) return HttpResponse('') models.py class landform(models.Model): mutdoc = models.CharField(max_length=255) urls.py urlpatterns = [ path('user', testing_data), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root …