Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create get or create object from serializer data
I'm passing two serializer with one view. On creating object I want to first create CaseId object which is why I'm poping out CaseObject from validated data. I want to get or create an object with the given data. Because I want to pass that to the CaseMessage object as a reference. class CaseMessageSerializer(serializers.ModelSerializer): case_id = serializers.IntegerField(required=False) case_object = CaseIdSerializer(required=False) message_type = ChoicesFieldSerializer(choices=CaseMessage.MESSAGE_TYPE) body_format = ChoicesFieldSerializer(choices=CaseMessage.BODY_FORMAT) class Meta: model = CaseMessage fields = "__all__" depth = 1 def create(self, validated_data): raw_case_object = validated_data.pop('case_object', None) # Not Getting or creating object with the given data. case = CaseId.objects.get_or_create(**raw_case_object) case_message = CaseMessage(**validated_data) case_message.caseid = case case_message.save() if not CaseAudience.objects.filter(case_id=case).exists(): case_audiance = CaseAudience( case_id = case, source_message = case_message, ) case_audiance.save() return validated_data The Errors are as follows: -
show/hidden field forms with condition in django
I have trouble when trying to hide and show form field in django. My code works well when showing form field <label class="col-md-8" id="sotien">{{form.so_tien}}</label> However I failed when trying hide the field with condition. If ma_code=="ptp", form.so_tien is hidden and vice versa my forms: class AddReportForm(forms.Form): list_ma_code=( ("skipcall","SKIP CALL"), ("ptp","PTP"), ) ma_code=forms.ChoiceField(label="Mã code",choices=list_ma_code,widget=forms.Select(attrs={"class":"form-control"})) so_tien=forms.IntegerField(label="Số tiền",widget=forms.NumberInput(attrs={"class":"form-control", "type":"number"}),required=False, initial=0) my html <label class="col-md-8" id="id_ma_code">{{ form.ma_code }}</label> <label class="col-md-8" id="sotien">{{form.so_tien}}</label> my js <script> function Hide() { if(document.getElementById('id_ma_code').options[document.getElementById('id_ma_code').selectedIndex].value == "ptp") { document.getElementById('sotien').show(); } else { document.getElementById('sotien').hide(); } } window.onload = function() { document.getElementById('id_ma_code').onchange = Hide; }; </script> There was not any error, but the code didnt work. Even if I change all to hide, it didnt hide anything I read some questions but fail to resolve my issue https://stackoverflow.com/questions/15136657/show-and-hide-dynamically-fields-in-django-form https://stackoverflow.com/questions/55893040/how-to-hide-fields-in-django-form-depending-on-the-selected-category Thanks for your reading and supporting me -
How to return data from two different models in django?
class RateList(core_models.TimestampedModel): centre = models.ForeignKey( Centre, null=True, on_delete=models.CASCADE, related_name="c_centre_rate_list" ) rate_type = models.ForeignKey( RateType, on_delete=models.CASCADE, related_name="c_rate_type_rate_list" ) test = models.ForeignKey("package.Test", on_delete=models.CASCADE, related_name="c_test_rate") class TestProcessingLab(core_models.TimestampedModel): centre = models.ForeignKey(Centre, on_delete=models.CASCADE, related_name='source_centre') test_category = models.CharField(max_length=50, null=True) test = models.ForeignKey("package.Test", on_delete=models.CASCADE, related_name='test') outhouse_centre = models.ForeignKey(Centre, on_delete=models.CASCADE, null=True, related_name='test_outhouse_centre') outsource_centre = models.ForeignKey("OutSourceLab", on_delete=models.CASCADE, null=True, related_name='test_outsource_source') I'm trying to get the desired output but i'm really stuck. The problem is RateList models contains all the tests. And In TestProcessingLab Model only those tests are there which are mapped means whether the tests is outhouse or outsource. [![TestProcessingLab Data][1]][1] [1]: https://i.stack.imgur.com/20ooR.png In this image only those tests are there which are mapped but I want all those tests also which are not mapped which are in RateList. How to achieve this? Any help would be really appreciated. -
how to fix connection refuse error using mail_sent function in Django
Hlo I m New in Django I Making a blog Project. I want to add sharing feature in my project via Email I m Having A Error Called Connection Refuse Error .Error Look Like that ConnectionRefusedError at /URL/ [Win Error 10061] No connection could be made because the target machine actively refused it Setting.py smtpserver = smtplib.SMTP("smtp.gmail.com", 587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo() smtpserver.login('xxyz, 'xyz') EMAIL_USE_TLS=True where I defined my views function my views file look like that views.py from django.core.mail import send_mail from Blog.forms import EmailsendForm def email_send_view(request,id): post=get_object_or_404(Post,id=id,status='published') sent=False if request.method=='POST': form=EmailsendForm(request.POST) if form.is_valid(): cd=form.cleaned_data send_mail('hello','how are you','xyz.d@gmail.com',[cd['to']]) sent=True else: form=EmailsendForm() return render(request,'blog/emailshare.html',{'form':form}) -
Foreign key field not rendering in serializers django
I am trying to show up the foreign key fields name instead of object id but not able to get through it. Tried using the related_name and then binding that to the serializer but still no luck, models.py class Employee(base_models.BaseDateModel): """ DB model to store employee data """ name = models.CharField(max_length=50) level = models.SmallIntegerField(choices=LEVEL_CHOICES, default=L1) def __str__(self): return f'{self.name} - {self.get_level_display()}' class Room(base_models.BaseDateModel): """ DB model to store available rooms in the building """ name = models.CharField(max_length=15) def __str__(self): return f'{self.name}' class Seat(base_models.BaseDateModel): """ DB model to store available seats in a given room """ room = models.ForeignKey('seating.Room', on_delete=models.CASCADE) def __str__(self): return f'{self.room} - {self.id}' class EmployeeSeating(base_models.BaseDateModel): """ DB model to store the seating details of any employee """ name = models.ForeignKey('seating.Employee', on_delete=CASCADE, related_name='emp_name') room = models.ForeignKey('seating.ROOM', on_delete=CASCADE, related_name='emp_room') seat = models.ForeignKey('seating.SEAT', on_delete=CASCADE, related_name='emp_seat') def __str__(self): return f'{self.name} - {self.room} - {self.seat}' serializers.py class EmployeeSeatingSerializer(serializers.ModelSerializer): emp_name = serializers.StringRelatedField() emp_room = serializers.StringRelatedField() emp_seat = serializers.StringRelatedField() class Meta: model = EmployeeSeating fields = ('id', 'emp_name', 'emp_room', 'emp_seat') views.py def listemp_api(request, pk=None): """ Method to return the list of employee in a given room """ if request.method == 'GET': room_id = pk if room_id: employee_data = EmployeeSeating.objects.filter(room_id = room_id) serializer = EmployeeSeatingSerializer(employee_data, many=True) … -
Django: Generating multiple similar tables and link them with another table
I want to store the historical stock price data in a database. E.g. I want a table which will contain the historical data of AAPL stock. In this table I'll have columns like date, open_price, close_price, etc. and this table will be linked to another table which will hold the fundamental information of the stock. Now, I want to do this for multiple stocks. As there are thousands of stocks, it'll be a very time consuming process to create a model for each stock. So, I want something like the following: class StockData(models.Model): date = models.DateField() open_price = models.DecimalField() close_price = models.DecimalField() high_price = models.DecimalField() low_price = models.DecimalField() adj_close_price = models.DecimalField() volume = models.PositiveIntegerField() class StockInfo(models.Model): stock_name = models.CharField(max_length=30) # other fundamental information # How to do this: link the instance of StockData here, which will hold the data of particular stock with name 'stock_name' How should I go about doing this in django? -
In Django, how does passing in a reference to the views function eventually get called by the path function?
I know my question is very similar to what is "request" in Django view but I can't make sense of the answers provided. I have also read the documentation that is related to my question, but still don't understand. I would greatly appreciate any elaboration to the other answers in addition to anything I ask that isn't covered in that question. In views.py, we can have something like this: from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse("Hello, World") And in urls.py we have something like this: from django.urls import path from . import views urlpatterns = [ path('', views.home, name='hello-world-home'), ] My question involves views.home being passed in as a parameter to path. Based on one of the answers to a similar question, views.home is passing the "function object" as a parameter to path. If it's not calling the function, don't we need pass it like this: views.home()? How does it eventually get called by path? If there is some documentation about being able to pass in a reference to a function in Python, I would appreciate it if you could link it. Is being able to pass in a reference to a function exclusive to … -
Django list_select_related gives me this error
#app/admin.py @admin.register(models.Product) class ProductView(admin.ModelAdmin): list_display = ['title', 'unit_price', 'inventory_status', 'collection_title',] list_editable = ['unit_price'] list_per_page = 10 list_select_related = ['collection'] #app/models.py class Collection(models.Model): title = models.CharField(max_length=255) featured_product = models.ForeignKey( 'Product', on_delete=models.SET_NULL, null=True, related_name='+') class Meta: ordering = ['title'] ''' def __str__(self) -> str: return self.title ''' class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField() unit_price = models.DecimalField(max_digits=6, decimal_places=2) inventory = models.IntegerField() last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT) promotions = models.ManyToManyField(Promotion) #Error I got: SystemCheckError PS - I know I can use 'collection' in list_display directly as it is already a field in my product model, but I want to preload a related field/table using list_select_related and use 'collection_title' in list_display. Please help. Thank You. ERRORS: <class 'store.admin.ProductView'>: (admin.E108) The value of 'list_display[3]' refers to 'col lection_title', which is not a callable, an attribute of 'ProductView', or an attribute or method on 'store.Product'. -
Setting up OSRM on Heroku
Making a new thread for this post Setting up OSRM (Open Source Routing Machine) on Heroku because it's been 6 years and the older buildpacks don't seem to work, at least for me. Has anyone had recent success setting up OSRM in their Heroku apps? I've tried several different ways over the last couple days but nothing has worked. My situation may be specific because I already have a django heroku app and want to run OSRM inside so I can access it from the local host. I've tried using the following buildpacks separately, and they each fail when I try to push my code. I think they're just not maintained and outdated by now. https://github.com/chrisanderton/heroku-osrm-buildpack https://github.com/jpizarrom/osrm-heroku I currently already use the two below buildpacks and have added the osrm ones on top: https://github.com/heroku/heroku-geo-buildpack.git heroku/python [one of the osrm buildpacks] I was thinking that maybe there's no recent literature on setting up OSRM on Heroku because Heroku Docker is much easier to use now. But I've also tried setting up OSRM with Heroku Docker and failed. I would like to run the docker image inside my current app, but my app doesn't use Heroku's container stack. And I've also been … -
How to show data from cluster done by using k means on website
I have categoriesed cricket player using k-means clustering but now not able to show that particular player belongs to which category in my Website using html and django can anyone help -
In Django bootstrap project toast messages showing for the first card in loop element
I want to toast messages for all those cards. but it is showing for the first card only. I have attached a view of my page where I want to add a toast message to view the details of the card if a user is not logged in. ![Text]https://i.stack.imgur.com/cYSPW.jpg) document.getElementById("toastbtn").onclick = function() { var toastElList = [].slice.call(document.querySelectorAll('.toast')) var toastList = toastElList.map(function(toastEl) { return new bootstrap.Toast(toastEl) }) toastList.forEach(toast => toast.show()) } <section class="details-card"> <div class="container"> <div class="row"> {% for homes in home %} <div class="col-md-4 mb-4"> <div class="card-content"> <div class="card-img"> <img src="{{ homes.coverImg.url }}" alt="Cover Image"> <span><h4>{{ homes.pricePerMonth }}Taka</h4></span> </div> <div class="card-desc"> <p class="small mb-1"> <i class="fas fa-map-marker-alt mr-2"></i>{{homes.address}}</p> <h3>{{ homes.title}}</h3> {% if request.user.is_authenticated %} <a href="{% url 'HomeDetails' homes.id %}" class="btn btn-md btn-primary hover-top">Details</a> {% else %} <button type="button" class="btn btn-primary" id="toastbtn">XDetails</button> {% endif %} </div> </div> </div> {% endfor %} </div> </div> </section> <!-- Alert Message Popup--> <!--bottom-0 end-0 p-3--> <div class="position-fixed top-50 start-50 translate-middle p-3" style="z-index: 11"> <div id="liveToast" class="toast hide" role="alert" aria-live="assertive" aria-atomic="true"> <div class="toast-header"> <img src="({% static 'img/icon.png' %})" class="rounded me-2" alt="..."> <strong class="me-auto">My Second Home</strong> <small>0.1s ago</small> <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button> </div> <div class="toast-body"> Hello!<br>You need to login first to see details. <div class="mt-2 … -
Ajax with knockout form is not working in django
productscreate.html <form> <table border="1"> <tr> <td>Title: <input type="text" name="title" id="title" data-bind="value: title"></td> <br> </tr> <tr> <td>Description: <textarea name="description" id="description">Description</textarea></td> <br> </tr> <tr> <td>Image: <input type="file" name="image" id="image"></td> <br> </tr> <tr> <td><button type="button" id="submit" data-bind="click: mySubmit">Submit</button></td> </tr> </table> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script> <script> var formData1 = new FormData(); $(document).on('click', '#submit',function(e){ e.preventDefault() var viewModel = { title:ko.observable(),description:ko.observable(), mySubmit : function(formElement) { var formData = { 'title' : viewModel.title() , 'description' : viewModel.description(), }; formData1.append('image', $('#image')[0].files[0]) $.ajax({ type: "POST", url: '{% url "productscreate" %}', data: formData,formData1, cache: false, processData: false, enctype: 'multipart/form-data', contentType: false, success: function (){ window.location = '{% url "productslist" %}'; }, error: function(xhr, errmsg, err) { console.log(xhr.status + ":" + xhr.responseText) } }); } }; ko.applyBindings(viewModel); </script> views.py class ProductsList(ListView): model = products context_object_name = 'products' template_name = "productslist.html" class ProductsCreate(CreateView): model = products fields = ['title','description','image'] template_name = "productscreate.html" success_url=reverse_lazy('productslist') class ProductsDetailView(DetailView): template_name = "productsdetail.html" queryset = products.objects.all() context_object_name = 'products' model = products Ajax with knockout is not working in this project I want to submit the form with help of ajax with knockout js code Now when i click submit button form value is not submitting. I want to submit form with ajax I don't know … -
how can we add data into database using migration files in django?
I am currently using Django 3.2 i wanted to add data to Database using migration files. from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sbimage', '0001_initial'), ] operations = [ migrations.CreateModel( name='AuthNumberR', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('auth_number_r', models.CharField(max_length=64)), ], ), migrations.RunSQL("INSERT INTO AuthNumberR (id, auth_number_r) VALUES (2, 'c');"), ] is this the proper way to insert data? -
Is there a proper design pattern for this situation?
I'm building a simple crud app in Django which is basically enhanced reporting for commerce related software. So I pull information on behalf of a user from another software's API, do a bunch of aggregation/calculations on the data, and then display a report to the user. I'm having a hard time figuring out how to make this all happen quickly. While I'm certain there are optimizations that can be made in my Python code, I'd like to find some way to be able to make multiple calculations on reasonably large sets of objects without making the user wait like 10 seconds. The problem is that the data can change in a given moment. If the user makes changes to their data in the other software, there is no way for me to know that without hitting the API again for that info. So I don't see a way that I can cache information or pre-fetch it without making a ridiculous number of requests to the API. In a perfect world the API would have webhooks I could use to watch for data changes but that's not an option. Is my best bet to just optimize the factors I control to … -
when creating a record an error is declared: NOT NULL constraint failed: faq.user_id but the user was declared in views
As you can see form.user = request.user is declared after p fom.save(commit=false), but the error persists. can anybody help me? either with request.user or without request.user the error persists. remembering that I'm logged in as admin, and in /admin the functionality works correctly, inserting null=True creates the record but the functionality is not correct. models.py from django.db import models from django.utils import timezone from .. import settings class Faq(models.Model): CAT_FAQ_CHOICES = ( (0, 'Selecione'), (1, 'FAQ Todos'), (2, 'FAQ Psicologo'), (3, 'FAQ Paciente'), (4, 'FAQ Empresa'), ) idfaq = models.AutoField(primary_key=True) titulo = models.CharField( verbose_name='Titulo da Dúvida', max_length=100, null=False, blank=False) descricao = models.TextField( verbose_name='Descrição', null=True, blank=True) data_cadastro = models.DateTimeField( verbose_name='Data de Cadastro', auto_now=True) is_active = models.BooleanField('Ativado | Desativado', default=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) tipofaq = models.IntegerField(choices=CAT_FAQ_CHOICES,default=0) def __str__(self): return self.titulo class Meta: db_table = 'faq' verbose_name = 'faq' verbose_name_plural = 'faqs' views.py @login_required def criar_faq(request): if request.user.is_paciente: form = FaqForm(request.POST or None, initial={ 'user': request.user.paciente, 'tipofaq': 3}) custom_template_name = 'area_pacientes/base_paciente.html' if form.is_valid(): form = form.save(commit=False) form.user = request.user form.save() return redirect('faq:listar_faq') else: print(form.errors) return render(request, 'area_administrativa/faq/novo-faq.html', {'form': form, 'custom_template_name': custom_template_name}) elif request.user.is_psicologo: form = FaqForm(request.POST or None, initial={ 'user': request.user.psicologo, 'tipofaq': 2}) custom_template_name = 'area_psicologos/base_psicologo.html' if form.is_valid(): form = form.save(commit=False) form.user … -
Django model with a type field and lots of custom logic
I have a Django model that has a type field: class MyModel(models.Model): type = models.CharField(choices=MyModelTypes.choices) ... def some_func(self): if self.type == "TYPE_1": do_something_1() elif self.type == "TYPE_2": do_something_2() This is getting really complicated and is causing conditionals to be littered everywhere, so I'm wondering if there's some way to cast my model into some specific object that has a specific implementation of that some_func() function for the type.: class MyModelTypeA: ... class MyModelTypeB: ... class MyModel(models.Model): type = models.CharField(choices=MyModelTypes.choices) ... def some_func(self): # Obviously this won't work, but I want something that allows me to turn # MyModel into the right type then call the `some_func()` (which has logic # specific to the `type`). MyModelType(self).some_func() Or maybe that's the wrong approach. Any ideas? -
When Django Form is Invalid, why only file type input is rest?
If there is an invalid field after submitting my Django Form, the other fields have input values when submitted, but only the inputs of the file type will be emptied. I don't think there's anything to change in Dajngo. Perhaps this is a characteristic of html file type input? For example, my form compresses video files uploaded by users. And it takes quite a bit of time. If something goes wrong after submitting the form, the user must select the file again and proceed with the compression process. This is not good. Forms.py class VideoArtUploadForm(forms.ModelForm): class Meta: model = models.VideoArt fields = ( "video", "thumbnail", "poster", "title", "year", "artist", "description", ) widgets = { "video": forms.FileInput(attrs={"accept": "video/mp4"}), "title": forms.TextInput(attrs={"placeholder": "Il titolo del video"}), "year": forms.TextInput( attrs={"placeholder": "l'anno in cui il video è uscito"} ), "artist": forms.TextInput(attrs={"placeholder": "Il nome di artista"}), "description": forms.Textarea( attrs={"placeholder": "una descrizione del video "} ), } def clean_thumbnail(self): thumbnail = self.cleaned_data.get('thumbnail') if thumbnail: if thumbnail.size > 10*1024*1024: raise forms.ValidationError("Thumnail si deve essere meno di 10MB") return thumbnail else: raise forms.ValidationError("Thumnail è necessario") def clean_poster(self): poster = self.cleaned_data.get('poster') if poster and (type(poster) != str): if poster.size > 10*1024*1024: raise forms.ValidationError("Cover image si deve essere meno di 10MB") … -
How best to validate number of total reverse relationships before saving
I have an Item model that is reverse-related to two other models (ItemComponent and or ItemComponentCategory). The idea is I'd like to be able to validate that Items have no more than 4 relations to the two other models, combined, before being saved. class Item(models.Model): name = models.CharField(max_length=40, unique=True) class ItemComponent(models.Model): parent_item = models.ForeignKey(Item, related_name='components') class ItemComponentCategory(models.Model): parent_item = models.ForeignKey(Item, related_name='categories') I'd like to create a validation that raises an error before saving either the Item, ItemComponent, or ItemComponentCategory objects if the saved objects will result in > 4 object relations between them. I have tried adding something like this to the clean methods for all three: def clean(self): if (self.parent_item.components.count() + self.parent_item.categories.count()) > 4: raise ValidationError(_(f'Items can have no more than 4 components and/or component categories')) This seems to work as long as the Items and their relations are already saved and you're trying to add more relations. However, if I create a TabularInline in the ItemAdmin to add these 'sub types,' if you will.. I can create a new Item and add as many of these sub types and save it no problem. What am I missing here? -
Django SelectDateWidget
date_range = 100 this_year = date.today().year birth_date= forms.DateField(label='What is your birth date?', widget=forms.SelectDateWidget(years=range(this_year - date_range, this_year+1))) I would like to only select dates 100 years from today. But I currently can get values like Dec 31 2021 where sometimes the months and days don't match the correct values. -
Convert text to list of Strings Python
How can i convert these lines in a .txt file into a list of strings (each list item is a row in the text file): great dane saint bernard, st bernard eskimo dog, husky malamute, malemute, alaskan malamute siberian husky the code I did does the split , but make no consideration for the comma! Meaning , I want to split based on the comma , not only the line. This is the code I did. with open(dogfile) as file: lines = file.readlines() dogs_list = [line.rstrip() for line in lines] -
Django returning "CSRF verification failed. Request aborted. " behind Nginx proxy locally
I'm running a simple Django application without any complicated setup (most of the default, Django allauth & Django Rest Framework). The infrastructure for running both locally and remotely is in a docker-compose file: version: "3" services: web: image: web_app build: context: . dockerfile: Dockerfile command: gunicorn my_service.wsgi --reload --bind 0.0.0.0:80 --workers 3 env_file: .env volumes: - ./my_repo/:/app:z depends_on: - db environment: - DOCKER=1 nginx: image: nginx_build build: context: nginx dockerfile: Dockerfile volumes: - ./my_repo/:/app:z ports: - "7000:80" ... # db and so on as you see, I'm using Gunicorn the serve the application and Nginx as a proxy (for static files and Let's Encrypt setup. The Nginx container has some customizations: FROM nginx:1.21-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d And the nginx.conf file is a reverse proxy with a static mapping: server { listen 80; location / { proxy_pass http://web; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /app/my_repo/static/; } } Running this on the server after setting up let's encrypt in the Nginx container works without any issue, but locally I get the "CSRF verification failed. Request aborted." error every time I submit a form (e.g. create a dummy user in Django Admin). I … -
Updating admin/staticfiles with Django
I am having trouble with updating the css, img, fonts, and js admin files when I upgrade Django. I first noticed this when I upgraded to Django 2.0 (see here), and now the problem is worsening as I upgrade to 4.0. The backend functionality is working perfectly well. But now when I access the admin console, the homepage remains on the top of the browser page, even when I navigate to different models. I noticed that none of the /static/admin/ files (css, js, img, fonts) were updated on my local machine when upgrading from Django 2.2.24 to 4.0. Should I have expected these files to update along with Django? Am I missing a step to ensure that the admin static files are updated to reflect the newest version of Django? -
How to create a dynamic dependent form select options data model in django
I am new to django. I'm trying create an ecommerce application in which the user will select from a category of options [automobile, property, electronics, phones, clothes etc], and upon selecting an option (say automobile), the next select field options will be populated asking for model [Honda, Toyota, Chrysler etc], if user select say Toyota, a list of Toyota models comes up [Camry, Highlander, Corolla, etc.], upon selecting say Camry, another set of options comes up asking for year, and so on. How do I implement (generate and/or store) this type of data using django models? I'll be very grateful for a swift response to this. Thank you. -
Why DRF shows Forbidden (CSRF cookie not set.) without @api_view(['POST'])?
I'm using django-rest-framework(backend) and react(frontend). In react i created a login form ,when i submite the form it sends an axios.post to my view function. The problem is django raise a error and the message: Forbidden (CSRF cookie not set.) My axios: axios({ method:'post', url: url, data:{email:email, password1:senha}, headers: {'X-CSRFTOKEN': token}, withCredentials: true }) .then((response)=>{ console.log(`Reposta: ${response.data}`) }) .catch((error)=>{ console.log(`Erro: ${error.data}`) }) My django view: def login_usuario(request): if request.method == 'POST': return HttpResponse('Something') Obs1:If i include de @api_view(['POST']) decorator works, but i want to know if is possible make the request without it. Obs2: When my react form render, a function that creates a csrf_token was called, so the csrf_token its being sent but django isn't reading it -
Python - "cannot unpack non-iterable int object" when importing json data into database
I'm working on an importer to import a list of facilities from a json file into my database. The importing works. But when i added some extra conditions to update existing facilities (whenever i run the script again and there is updated data inside the json) it stopped working the way it originally did. The updating works if i only have 1 facility inside the json file but if i add more than one i get the following error: cannot unpack non-iterable int object Also: Instead of updating it will just create two additional copies of one of the facilities. Been trying to figure this out for a couple of days now but so far no luck. import_facility_from_file.py import os import json from data_import.models import Facility, FacilityAddress, FacilityInspectionInfo, FacilityComplaints from django.core.management.base import BaseCommand from datetime import datetime from jsontest.settings import BASE_DIR, STATIC_URL class Command(BaseCommand): def import_facility_from_file(self): print(BASE_DIR) data_folder = os.path.join(BASE_DIR, 'import_data', 'resources') for data_file in os.listdir(data_folder): with open(os.path.join(data_folder, data_file), encoding='utf-8') as data_file: data = json.loads(data_file.read()) for key, data_object in data.items(): UUID = data_object.get('UUID', None) Name = data_object.get('Name', None) IssuedNumber = data_object.get('IssuedNumber', None) Capacity = data_object.get('Capacity', None) Licensee = data_object.get('Licensee', None) Email = data_object.get('Email', None) AdministratorName = data_object.get('AdministratorName', None) TelephoneNumber = …