Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I fix a 400 error when sending data that uses nested relationships?
I'm currently working on a Django app that uses Django REST Framework as the backend for API, and I keep getting 400 errors when I try and send JSON data to the server. I've ensured all the field names in the JSON file match up with the field names in my API, but beyond that I'm not sure what else to try other than the small edits I've been making to my code (such as setting die field on the DieMeasurement model to allow blank and null entries). Here's the script I'm using to send the data: def post_die_measurement(): with open('file.json') as obj: data = json.load(obj) requests.post(api_url_base + 'api-page/', data=data, headers={'Authorization': 'Token ' + api_token}) Here are the two relevant models associated with the data: class DieMeasurement(models.Model): # ... # fields # ... die = models.ForeignKey(Die, on_delete=models.CASCADE, blank=True, null=True) class Result(models.Model): # ... # fields # ... die_measurement = models.OneToOneField(DieMeasurement, on_delete=models.CASCADE, related_name='results') Here are my serializers for these models: class ResultSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = views.Result fields = ('set_v', 'dmm_value', 'actual_v', 'actual_a', 'time') class DieMeasurementSerializer(serializers.HyperlinkedModelSerializer): results = ResultSerializer(many=False) class Meta: model = views.DieMeasurement fields = ('notes', 'tap', 'dmm_mode', 'laser_power', 'timestamp', 'die', 'results') def create(self, validated_data): results_data = validated_data.pop('results') measurement = … -
NoReverseMatch at /cart/add-to-cart/1/ Reverse for 'single_product' with arguments not found. 1 pattern(s) tried: ['products/(?P<slug>.*)/$']
am having a function add_to_cart wanted to reverse redirect to product detail page rendered by single_product function which has slug for product id , cant get a way to solve it .getting this error Reverse for 'single_product' with arguments '('s', 'l', 'u', 'g')' not found. 1 pattern(s) tried: ['products/(?P.*)/$'] def add_to_cart(request,**kwargs): product = Product.objects.filter(id=kwargs.get('item_id', "")).first() # check if the user already owns this product ---------------- ------------- messages.info(request, "item added to cart") return redirect(reverse('products:single_product',args=('slug'))) url for product detail view url(r'^(?P<slug>.*)/$',single, name="single_product"), -
django.template.exceptions.TemplateDoesNotExist
I'm learning django, and I have a problem, I'm doing a virtual store and when I click on add a product to the shopping cart you should redirect me to another page, but can not find it, this is my code and my error: django.template.exceptions.TemplateDoesNotExist: productos/carritocompras_form.html detalle.html <div class="fixed-action-btn" style="bottom:90px;"> <form action="{% url 'aniadir_carrito' %}" method="post"> {% csrf_token %} <input type="hidden" name="usuario" value="{{request.user.pk}}"> <input type="hidden" name="produto" value="{{object.pk}}"> <input type="hidden" name="precio" value="{{object.precio}}"> <button class="btn-floating btn-large red pulse"> <i class="large material-icons">add_shopping_cart</i> </button> </form> </div> <div class="fixed-action-btn"> <a class="btn-floating btn-large red pulse"> <i class="large material-icons">add_shopping_cart</i> </a> <ul> </ul> </div> -
How much can request.session store?
I'm new to learning about Django sessions (and Django in general). It seems to me that request.session functions like a dictionary, but I'm not sure how much data I can save on it. Most of the examples I have looked at so far have been using request.session to store relatively small data such as a short string or integer. So is there a limit to the amount of data I can save on a request.session or is it more related to what database I am using? Part of the reason why I have this question is because I don't fully understand how the storage of request.session works. Does it work like another Model? If so, how can I access the keys/items on the admin page? Thanks for any help in advance! -
How do I avoid Django's `|linebreaksbr` and Bootstrap style conflict?
I'm trying to store newline character inside model's CharField but it's not rendering correctly. <br/> and <br> both display as plain text, while |linebreaksbr is destroing bootstrap's styles in that text. 3 of my attempts to make it work: <p>{{ greetings.title_2 }}</p> <p><pre>{{ greetings.title_2 }}</pre></p> <p>{{ greetings.title_2 | linebreaksbr }}</p> And the result looks like this: I want both bootstrap's style (like in first line) and new line stored inside variable. There is a way to do that by deviding one model field in two and adding <br/> tag into html file, but I wonder if there is better and simpler way for that. Any ideas? -
getting error on using Bootstrap in django
I am trying to create a webapp using django, and it was working fine until i included bootstrap nav bar in the html file. after that i am getting the error on running "python manage.py runserver". Even on removing the navbar code from html code i am seeing this error. Thanks in advance. i am getting the follwing error, Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files (x86)\Python37-32\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Program Files (x86)\Python37-32\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run handler = self.get_handler(*args, **options) File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\core\servers\basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Program Files (x86)\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File … -
Javascript and Django Rest Framework - cannot read property
I'm trying to retrieve data from an API endpoint that i created with Django Rest Framework. At first, my code worked but now i keep getting this error: Uncaught TypeError: Cannot read property 'ticker' of undefined This is what the data i'm trying to retrieve looks like: [ { ticker: "TEST", price: 7876 } ] And this is the Ajax function that i built: function doPoll(){ $.getJSON('http://127.0.0.1:8000/tst/', function(data) { console.log(data[0]); $('#data').text(data[0].ticker + ' ' + data[0].Price); setTimeout(doPoll, 100); }); } doPoll(); And this is where the data should appear: <h3 id="data"></h3> The function should be supposed to place my data on my html page and refresh that data every second. http://127.0.0.1:8000/tst/ is the DRF API endpoint that i'm trying to call, from where i'm trying to retrieve the JSON DATA -
How do I interpret an HTTP status code of 400 73?
I'm currently trying to use the python requests library to send JSON data to my web application using an API built with the Django REST Framework, but I'm getting 400 errors which I don't know how to interpret. Authentication is working and I'm less concerned with how to fix the status codes as opposed to how to read them while I'm doing the debugging, since I'm getting an HTTP status code (such as 400) followed by a second number (73). Django's console log gives me the following when I try to post: Bad Request: /api/dieMeasurements/ [17/Jul/2019 13:04:31] "POST /api/dieMeasurements/ HTTP/1.1" 400 73 My script for sending the post request looks like this: def post_die_measurement(): with open('json/tap 1.json') as obj: data = json.load(obj) requests.post(api_url_base + 'dieMeasurements/', data=data, headers={'Authorization': 'Token ' + api_token, 'content-type': 'application/json'}) I haven't worked with HTTP status codes before and Google hasn't provided any relevant information on how to read the second number following the 400 error. Any information would be appreciated! -
what are the steps in learning python? can i get some homework please, thank you
I have started to study about this programming language and on my way in learning to code.. I have started watching video tutorials, and read ebooks and understand the basics and concepts of python.. now I do not no how to proceed further, I feel like I cannot keep watching the tutorials all time.. Steps I Tried : I have read some posts that suggests to start writing any basic programs to keep moving on the learning process.. so I went forward and wrote a code for calculator with the basic operations and the power calculation operation.. I have learnt some things like how a " while = True" loop helps us to keep the program running and not closing after just performing single operation..My calculator is good and I might try and learn how to add buttons etc.. Now I want to know am I going in the correct path? Can you help me by providing me some exercise programs for me to work out and also anything that you feel that I should know.. Thank you very much for all the timely help you people give out! Thanks, Regards.. -
Need a PK or ID for success_message in UpdateView (a class based view)
I want to send a success message in DetailView that has a link to allow the user to change his mind about the update. This means I need the primary key. I haven't been able to determine how to retrieve the primary key in DetailView. Everything else works, so you'll see in my code, that I have tenatively hard-coded the primary key as 434. I'm an extreme newb to all of programming, so I'm confident there's stupid stuff in here. I try to reduce my stupid stuff a little at a time. So mostly I want to focus in on how I can retrieve the PK (or ID). Thanks. The URLS: # CLASS BASED VIEWS # path('event/list', EventListView.as_view(), name='list'), path('event/detail/<int:pk>', EventDetailView.as_view(), name='detail'), path('event/create', EventCreateView.as_view(), name='create'), path('event/update/<int:pk>', EventUpdateView.as_view(), name='update'), The View: class EventUpdateView(SuccessMessageMixin,UpdateView): template_name = 'update.html' form_class = EventForm success_url = '../list' queryset = Event.objects.all() def get_object(self, queryset=None): # here we override the get_object method in UpdateView, don't need queryset #obj = Event.objects.get(id=self.kwargs['pk']) pk_=self.kwargs.get("pk") print("The pk is", pk_) return get_object_or_404(Event,pk=pk_) def form_valid(self, form): return super().form_valid(form) message_part_1 = "Record has been updated <a href='unupdate?recordtobeunupdated=" message_part_2 = '434' message_part_3 = "'>Undo</a>" undo_message = message_part_1 + message_part_2 + message_part_3 success_message = (mark_safe(undo_message)) The Model: … -
Problem creating initial Django migrations due to transactions
I am trying to write a custom migration for my app to create some initial data. One of the things I want to do is create a Group that has permissions based on the models that are created in the initial migration. The problem I am having is that it appears that Django is running both of the migrations (0001_initial.py and 0002_auto_20190717_0000.py) in a single transaction. I am trying to find a Permission object that should get created along with the Model, but it is not present. To troubleshoot, I put a breakpoint after trying to get a Permission object that is not found. In a separate terminal, I created a Django shell, and tried ran a query to find all ContentType objects, and it did not find any results. If I let the migration complete, then run the same query, it finds all of the content types. While the migration was paused, I tried to create a superuser, and the command failed with the exception django.db.utils.OperationalError: database is locked I tried renaming the second migration to a non-.py extension, and then running the initial migration. I then rename the second migration back to .py, and run migrate again, and … -
How can use Django with electron for offline desktop application
I am trying to create an electron offline desktop app with React as front-end and Django(python) as backend. But i am facing problem to create Django server inside electron package. please suggest how do i communicate from node.js to Django rest Api. I tried to do using below function which is placed inside electron.js file to start Djangoserver. function startDjangoServer() { DjangoServer=child_process.spawn([pythonRestApi/RestApi/],['manage.py','runserver'])} -
Scrapy integration with DjangoItem yields error
I am trying to run scrapy with DjangoItem. When i run crawl my spider, I get the 'ExampleDotComItem does not support field: title' error. I have created multiple projects and tried to get it to work but always get the same error. I found this tutorial and downloaded the source code, and after running it; I get the same error: Traceback (most recent call last): File "c:\programdata\anaconda3\lib\site-packages\twisted\internet\defer.py",line 654, in _runCallbacks current.result = callback(current.result, *args, **kw) File "C:\Users\A\Desktop\django1.7-scrapy1.0.3-master\example_bot\example_bot\spiders\example.py", line 12, in parse return ExampleDotComItem(title=title, description=description) File "c:\programdata\anaconda3\lib\site-packages\scrapy_djangoitem__init__.py", line 29, in init super(DjangoItem, self).init(*args, **kwargs) File "c:\programdata\anaconda3\lib\site-packages\scrapy\item.py", line 56, in init self[k] = v File "c:\programdata\anaconda3\lib\site-packages\scrapy\item.py", line 66, in setitem (self.class.name, key)) KeyError: 'ExampleDotComItem does not support field: title' Project structure: ├───django1.7-scrapy1.0.3-master ├───example_bot │ └───example_bot │ ├───spiders │ │ └───__pycache__ │ └───__pycache__ └───example_project ├───app │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ └───example_project └───__pycache__ My Django Model: from django.db import models class ExampleDotCom(models.Model): title = models.CharField(max_length=255) description = models.CharField(max_length=255) def __str__(self): return self.title My "example" Spider: from scrapy.spiders import BaseSpider from example_bot.items import ExampleDotComItem class ExampleSpider(BaseSpider): name = "example" allowed_domains = ["example.com"] start_urls = ['http://www.example.com/'] def parse(self, response): title = response.xpath('//title/text()').extract()[0] description = response.xpath('//body/div/p/text()').extract()[0] return ExampleDotComItem(title=title, description=description) Items.py: from scrapy_djangoitem import DjangoItem from … -
(Django) Send POST ID back to the Client
I'm new to Django and I'm trying to create a somewhat basic API. But one thing that has been bugging me is how to create a callback function for when certain (asynchronous) events occur. For example, one of my simplest cases is for when the client sends a POST request. I would like to send back to him the ID of that request in the DB. How would I do that? My code mostly follows William S. Vincent's Django for APIs book with minor modifications. The most important parts are: models.py: from django.db import models class SegmentcliApi(models.Model): request_id = models.AutoField(primary_key = True) database = models.CharField(max_length = 100) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return f'Pedido para Base de Dados {self.database}: criado em {self.created_at}' serializers.py: from rest_framework import serializers from .models import SegmentcliApi class SegmentcliApiSerializer(serializers.ModelSerializer): class Meta: fields = ( 'request_id', 'database', 'created_at', 'updated_at', ) model = SegmentcliApi views.py: from rest_framework import generics from .models import SegmentcliApi from .serializers import SegmentcliApiSerializer class SegmentcliApiList(generics.ListCreateAPIView): queryset = SegmentcliApi.objects.all() serializer_class = SegmentcliApiSerializer class SegmentcliApiDetail(generics.RetrieveUpdateDestroyAPIView): queryset = SegmentcliApi.objects.all() serializer_class = SegmentcliApiSerializer -
How do I get tuples of primary keys of models related to each other using the django orm?
Assuming I have four models, where two models define types and two models are instances of these types, which have a 1-to-n relationship: class SuperTypeA(Model): pass class InstanceofA(Model): definition = ForeignKey(SuperTypeA, null=False) class SubTypeB(Model): supertype = ForeignKey(SuperTypeA, null=False) class InstanceofB(Model): definition = ForeignKey(SubTypeB, null=False) related = ForeignKey(InstanceofA, null=False) In plain English, a SuperTypeA has n SubTypeB, and n InstanceofA. A SubTypeB has n InstanceofB. A InstanceofA has n InstanceofB. I would like to get the tuples of the primary keys of SuperTypeA, SubTypeB, InstanceofB given some constraints on InstanceofA. In SQL: SELECT SuperTypeA.id, SubTypeB.id, InstanceofB.id FROM SuperTypeA, SubTypeB, InstanceofB, InstanceofA WHERE InstanceofA.id IN (1, 2, 3, 4) How do I do that using the Django ORM, without using raw queries? -
Trouble accessing value on a python dictionary which values are also dictionaries whithin a django template
Dictionary passed to template wont yield any values. I have tried various methods of accessing dictionary values, and even custom filters and no luck. view.py def home_view(request, location): cards = Site.objects.get(sites=location.upper() ).site_cards.all().values('cards') # Convert query set to list of dictionaries, then to list of values of dictionaries, then to dictionary with same key,value pair vlans = json.load(open('allvendors/static/json/narf.json')) cards_dict = {c: vlans[location][c] for c in [d['cards'] for d in list(cards)]} home = { "site": location, "cards": cards_dict, } return render(request, 'allvendors/home.html', {"home": home}) cards_dict (alias home.cards in the template) { 'card1':{ 'vlan':'101' }, 'card2':{ 'vlan':'102' }, 'card3':{ 'vlan':'103' }, } home.html {% for card in home.cards %} <div class="card mb-4 box-shadow shadow"> <div class="card-header"> <h4 id="whatfor" class="my-0 font-weight-normal">{{ card|title }}</h4> </div> <div class="card-body"> <h1 class="card-title pricing-card-title">Vlan: <small class="text-muted"> <a href="#" target="_blank"> {{ card.vlan }} </a> </small> </h1> <a class="text-decoration-none" href="{{ card|lower }}/"> <button id="seedata" type="button" class="btn btn-lg btn-block btn-outline-primary">See Database</button> </a> </div> </div> {% endfor %} The issue is {{card}} by itself works and the loop creates a div for each card 1 thru 3, but {{card.vlan}} wont output anything. I feel im accessing it wrong but i cant figure out why or how. Any pointers are welcome. -
Is there a cmd command to stop running django python server on localhost?
I simply ran the server on local host using the simple cmd command, but I can't seem to find the command for stopping the service. Is it something really simple I missed? Thanks for help. python manage.py runserver -
Question about jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'endfor'. Jinja was looking for the following tags: 'endblock'
I am trying to build a website with Flask and I have been encountered a jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'endfor'. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block' error. When I try to log into my local webpage with localhost:5000 I get the above error. I have read through the traceback error and it seems to be occurring on line 21 of my index.html file. {% block content %} <h1>Hi, {{ current_user.username }}!</h1> {% if form %} <form action="" method="post"> {{ form.hidden_tag() }} <p> {{ form.post.label }}<br> {{ form.post(cols=32, rows=4) }}<br> {% for error in form.post.errors %} <span style="color: red;">[{{ error }}]</span> {% endfor %} </p> <p>{{ form.submit() }}</p> </form> {% endif %} { % for post in posts %} {% include '_post.html' %} {% endfor %} <p> {{ post.author.username }} says <b>{{ post.body }}</b> </p> {% endblock %}``` The expected result is that I am able to log into my local Flask website and see other users posts on the webpage. -
Save image file to Django Upon Submit Using CreateView CBV
Yesterday, using this solution View an Image Using Django CreateView Before Submitting I was able to figure out how to display an image when a user clicks on the choose file button in my Django project. However, I can't figure out how to now save the image when the user submits the form. I realize the solution I am using is leveraging the HTML URL to display the image using Javascript. When I am using an approach for the use to attach an image and then submit the form without displaying the image first, this works fine. However, when I use the solution referenced above, it is not capturing the image. This works... <div> <h2>Photo: </h2> </div> <div> {{ form.image }} </div> However, when I try to leverage this instead....from the prior solution... <input type='file' onchange="readURL(this);" /> <img id="blah" src="#" alt="your image" /> And using Javascript... function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#blah') .attr('src', e.target.result) .width(150) .height(200); }; reader.readAsDataURL(input.files[0]); } } The file displays, but I can't figure out how to save it to the database upon user submit. I tried to use various solutions documented here...Django: add … -
How to Handle When JSON Response Returns None
I have a RESTful API call cwObj.get_opportunities() to return a set of records in the form of a JSON response. From the response, I reference the ID in each record against a second API call cwObj.get_tickets_by_opportunity(). This call will return a second set of records. However, often times there is not record for a particular ID in the JSON response returned by the second API call. The API is expecting a record for each individual call, so when there is none, I am being thrown a KeyError for Owner. Additionally, when I hardcode the ID referenced in the second API call, I am able to retrieve the data I want without errors. note: cwObj is the basis for my API calls... opportunities = cwObj.get_opportunities() for opportunity in opportunities: temp = opportunity['id'] opportunity_id = str(temp) presales_ticket = cwObj.get_tickets_by_opportunity(opportunity_id) presales_engineer = presales_ticket[0]['owner']['name'] -
Django webapp not working on ipad(csrf_token) and IE(CORS) error
Sorry, I know this is kind of 2 quetions in one, but there may be a resource out there that can fix both my problems. I have a webapp that I have created with Django that I am loading into an iframe of a wordpress site that I have started testing. At the moment it works as designed on google chrome, my android phone, and iphones. However I am having a CSRF token issue when I 'POST' from the iframe only when using an ipad. I am also not able to load in internet explorer, getting a CORS error after going through the "django-cors-headers" documentation. I have both X-frame-options and Cors whitelist allowing the site to host the iframe. I am lost as to why the app can work fine in a couple of settings and not in others - or if the errors may just be due to individualized settings on the devices I am testing on. If anyone can help in any way it would be greatly appreciated! -
Is there a way to make inlines that obtains the foreignkey from a different field in the caller?
class Organization(admin.ModelAdmin): ... class Configuration(admin.ModelAdmin): organization = model.ForeignKey(Organization) team = model.ManyToManyField(Team) ... class Team(admin.ModelAdmin): organization = model.ForeignKey ... Is it possible to have an inline in Team to Configuration in a way that the organization field is already filled? As in with the inline in Team, the organization field is read-only since the Team object already has it in place (obviously this would only work with editing objects since adding a new team would not have the organization selected). I've tried using requests to modify the URL and prefill some fields in the configuration pop-up when it was just a foreignkey in Team, but that didn't work exactly like this scenario. Using an inline with this scenario just produced an error saying configuration has no foreignkey to Team. -
npm run dev " 'webpack' is not recognized as an internal or external command"
taking my first stab at using react frontend with a django backend. npm run dev works and renders the frontend on my mac but fails to on my windows pc I am running the same version of node & npm on both machines Have tried npm cache clean --force and reinstall npm, has previously when facing the white page issue on my mac. error code; > webpack --mode development --watch ./marketmaker/frontend/src/index.js --output ./marketmaker/frontend/static/frontend/main.js 'webpack' is not recognized as an internal or external command, operable program or batch file. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! fullstack-calc@1.0.0 dev: `webpack --mode development --watch ./marketmaker/frontend/src/index.js --output ./marketmaker/frontend/static/frontend/main.js` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the fullstack-calc@1.0.0 dev script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. -
Insert data from a modal form to DB
I'm trying to add some data to the DB from a modal form in django. After filling all the fields and click on submit it doesn't save on the DB. Here are the models, views and forms and the template. I think the problem it's on the views.py models.py class Buyer(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) phone_numbers = ArrayField(PhoneNumberField()) industry = models.IntegerField(null=True) credit_limit = MoneyField(max_digits=20, decimal_places=2, default_currency='MMK', null=True) is_active = models.BooleanField(default=True) datetime_created = models.DateTimeField(auto_now_add=True) datetime_updated = models.DateTimeField(auto_now=True) views.py class BuyerCreateView(AtomicMixin, View): template_name = 'add_buyer_modal.html' def get(self, request): form = BuyerForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = BuyerForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Buyer created!', extra_tags='alert alert-success') return HttpResponseRedirect(self.request.META.get('HTTP_REFERER')) messages.error(request, 'Unable create buyer. {}'.format(form.errors), extra_tags='alert alert-danger') return HttpResponseRedirect(self.request.META.get('HTTP_REFERER')) forms.py class BuyerForm(forms.ModelForm): class Meta: model = Buyer fields = ['name', 'phone_numbers', 'industry', 'credit_limit'] template <div class="modal fade" id="add-buyer-modal" tabindex="-1" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">New Buyer</h5> <button type="button" data-dismiss="modal" aria-label="Close" class="close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="col-md-12 modal-body"> <form id="buyer-form" method="post" class="submit-form" action="{% url 'buyers:add_buyer' %}"> {% csrf_token %} <div class="col-md-12"> <div class="form-group label-floating"> <label class="control-label">Name</label> <input autocomplete="false" type="text" name="name" class="form-control" required> </div> </div> <div class="col-md-12"> <div class="form-group label-floating"> <label class="control-label">Industry</label> <div class="input-group"> … -
Custom post view with form in Django Rest
I want to do the following: create a view that accepts only post, but that generates a form when I access something like "/ api / check_email /". So the only field will be email, and from that. I will check if there is a user with this email, and return the status as 200 or 404 depending on whether the user exists or not. I'm a bit lost on how to do this. currently my view looks like this: class CheckEmail(APIView): def post(self, request): email = "???" user = get_object_or_404(User, email=email) return Response({email: user.email}, status=200)