Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'invalid file' error when using python-magic for file identification
I was told python-magic is the best way to identify a file type. So I installed it as i'm trying to determine whether a FileField is an image or video, when a user makes a Post. Here's my model: class Post(models.Model): ... image = models.FileField(null=True, blank=True) video = models.BooleanField(default=False) And my view: import magic def post(request): if request.user.is_authenticated(): form_post = PostForm(request.POST or None, request.FILES or None) if form_post.is_valid(): instance = form_post.save(commit=False) instance.user = request.user mime = magic.Magic(mime=True) f = mime.from_file(instance.image) print(f) instance.save() I copied the magic code from the top answer of this question :How to find the mime type of a file in python? However when I submit a Post, I get an error saying: invalid file: <FieldFile: uploadedImage.png> Any idea why it doesn't work? -
how to add M2M and FK into search_fields in admin? django
I know that by default adding search_fields in admin.py and register then I am able to add the fields in the model to search in admin page for that certain model. BUT I know that if I try to add searchable fields that's a foreign key or manyToManyField I would get error saying only ****** fields are available and those fields are just regular fields which doesn't have any relations. Can someone give me a hand? Thanks in advance -
CBV overrides django-filter context
I'm trying to implement django-filters in my project but I've hit a roadblock :/ Somehow filter instance is getting removed from context.. class ListReservations(LoginRequiredMixin, FilterView): template_name = 'reservations/homepage.html' paginate_by = 25 model = Reservation filterset_class = ReservationFilter def get_context_data(self, **kwargs): ctx = super(ListReservations, self).get_context_data() ctx['today'] = datetime.datetime.now().strftime('%d/%m') return ctx Results are still getting filtered, but don't have access to {{filter.form}} -
Not able to load proper content in Django + React/Redux project -- Target container is not a DOM element
I have my django project setup where the I can go to '/' using django urls and that will load a React component. However, when I try to navigate to another url such as '/test', the browser spits out Target container is not a DOM element. The component that is to be rendered on '/test', targets by ID an element of <div id='test'></div> on the respective .html template (served from django). I can even see that <div> element being populated. Is this error occurring because the React component is loading even before the django template? Is there a better way to set this up? This is what my setup looks like: index.js: ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <Router history={browserHistory}> {routes} </Router> </Provider> , document.getElementById('root')); app.js: export default class App extends Component { render() { return ( <div> <h1>Django React Redux Starter</h1> <Button bsStyle="primary">Click me!</Button> </div> ); } } ReactDOM.render( <App/> , document.getElementById('root')); test.js: export default class Test extends Component { render() { return ( <div> <h1>This is the Test page</h1> <h3>The routes are working now</h3> </div> ); } } ReactDOM.render( <Test/> , document.getElementById('test')); routes.js: export default( <Route path="/" component={App}> <Route path="test" component={Test} /> </Route> ); base.html (django): {% load staticfiles %} {% … -
How can I get data from a form model into a database in Django
I am trying to get data from a model form and then put it into a database. I have figured out how to make the form, but when clicking the submit button it doesn't seem to be put anywhere in my database. Am I doing anything wrong or am I not looking in the correct place in the database. forms.py from django import forms from sxsw.models import Account class AccountForm(forms.ModelForm): class Meta: model = Account fields = ['firstName', 'lastName', 'email'] views.py from django.shortcuts import render from django.shortcuts import redirect from .forms import AccountForm from .models import Account def sxsw(request): if request.method == 'POST': form = AccountForm(request.POST) if form.is_valid(): form.save() else: print form.errors else: form = AccountForm() return render(request, 'sxsw/sxsw.html', {'form': form}) def formSubmitted(request): return render(request, 'sxsw/formSubmitted.html',{}) models.py from __future__ import unicode_literals from django.db import models # Create your models here. class Account(models.Model): firstName = models.CharField(max_length = 50) lastName = models.CharField(max_length = 50) email = models.EmailField() def __unicode__(self): return self.firstName class Module(models.Model): author = models.ForeignKey(Account, on_delete = models.CASCADE) nameOfModule = models.CharField(max_length = 150) #arbitrary number moduleFile = models.FileField(upload_to = 'uploads/')#Not exactly sure about the upload_to thing public = models.BooleanField() def __unicode__(self): return self.nameOfModule sxsw.html {% extends "base.html" %} {% block content … -
Query Django Object Lists of ForeignKey
I have a MenuSection model and a Product model. The Product model has MenuSection set as a ForeignKey. Everything works fine, except I am having difficulty figuring out how to query the Product model and listing out a list of objects unique to the ForeignKey, but print the ForeignKey value once at the top of the template. Example of how I would like the Products printing to the template: Salads (FK) <= Only printed once Cobb (product.name) Ceasar (product.name) Pizza (FK) Supreme (product.name) Veggie (product.name) ... Tag @register.inclusion_tag('tags/_starters.html', takes_context=True) def products(context): product = Product.objects.all() return { 'product': product, 'request': context['request'], } Tag Template {% for p in product %} <div class="menu-wrapper"> <div class="menu-description"> <h1>{{ p.section.name }}</h1> <======= This is the (FK) that I need to print once. <div class="menu-list"> <h5>{{ p.name }}</h5> <p class="price"> {% if p.price_b %} {{ p.price_a }}/ {{ p.price_b }} {% else %} {{ p.price_a }} {% endif %} </p> <span class="menu-dot-line"></span> </div> <p class="menu-ingredients">{{ p.description }}</p> </div> </div> {% endfor %} Model @register_snippet class Product(ClusterableModel): section = models.ForeignKey(MenuSection, verbose_name='Menu Section') name = models.CharField(max_length=255, verbose_name='Menu Item Name') ... -
Django user appears as if not logged in
I have created some seperate views and corresponding templates with django. They all extend a base.html template, and just now I have added some buttons to the header of base.html so I can navigate between the different views. My site also has a user model implemented. In the header I make a quick check to see if a user is logged in. When it I display his / her name and when he / she isn't it shows a register and login link. {% if request.user.is_authenticated %} <p class="top-menu" style="font-size:17px">Logged in as: {{ request.user.name }} (<a href="{% url 'logout' %}" class="top-menu">Logout</a>)</p> {% else %} <a href="{% url 'registration' %}" class="top-menu">Register</a> / <a href="{% url 'login' %}" class="top-menu">Login</a> {% endif %} Now my problem is that for all pages this actually works as expected, except for one. It's a page with a form(set) on it. The GET looks like this: if request.method == 'GET': form_submission = SubmitForm() formset_authors = formset_factory(SubmitAuthorForm) c = { 'form_submission': form_submission, 'formset_authors': formset_authors } c.update(csrf(request)) return render_to_response('journal_submit.html' ,c , RequestContext(request)) The weird thing is that when I add a login_required decorator it does let me pass. So it knows I'm logged in. I'm guessing that the user … -
Connecting Django to Postgres using docker compose
I am trying to connect a Django container to a Postgres container. I read in the documentation how the settings.py file should be set in order for the application to use postgres and it is as follow: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db_name', 'USER': 'db_user', 'PASSWORD': 'db_user_password', 'HOST': 'postgres', 'PORT': '5432', } } My docker-compose.yml, which is used to start and connect both of the containers looks as follow: web: restart: always build: . ports: - "80:8080" links: - postgres volumes: - /usr/src/app - /usr/src/app/static postgres: restart: always image: postgres:latest ports: - "5432:5432" environment: POSTGRES_PASSWORD: db_user_password POSTGRES_DB: db_name POSTGRES_USER: db_user volumes: - ./dbdata:/var/lib/postgresql/data The problem is that both containers build and start without any noticeable errors. The only thing I get is: postgres_1 | LOG: incomplete startup packet and when I visit localhost:80 I get Internal Server Error. -
How to detect if a FileUpload is an image or video
I have a FileField like this: class Post(models.Model): file = models.FileField(null=True, blank=True) video = models.BooleanField(default=False) I'm then able to look at the object when it goes past my views: def post(request): if request.user.is_authenticated(): form_post = FileForm(request.POST or None, request.FILES or None) if form_post.is_valid(): instance = form_post.save(commit=False) if ?something?: instance.video = True instance.save() So in my view is it possible to check whether the Post.file is a video or image? -
AJAX response not rendering in JavaScript template
I have the following jQuery AJAX request, that returns the correct JSON response, as expected (which is a youtube ID). However, when I try to insert ytid into framecode using rendered = Mustache.render(framecode, {ytid: ytid}); I am left with an empty space where {{ytid}} should be replaced with the contents of ytid. In the firefox debugger, ytid shows as a string as expected, and when I run the above line in the debugger, {{ytid}} is replaced with the youtube id as expected. Very strange. Also, when I print ytid to console, it also prints correctly, so I'm sure the variable is not empty. $(document).on("click", ".movlist_youtubebutton", function() { console.log("Youtube Button Clicked"); var ytid = $(this).data('ytid'); var movid = $(this).data('movid'); function isEmpty(str) { return (!str || 0 === str.length); } if (isEmpty(ytid)) { $.ajax({ url: "/gettrailer/", method: "GET", data: {movid: movid}, dataType: "json", success: function (result) { console.log(result); ytid = result.ytid; window.ytid = ytid; console.log(ytid); } }); } framecode = '<iframe width="560" height="315" src="https://www.youtube.com/embed/{{ytid}}" frameborder="0" allowfullscreen></iframe>'; rendered = Mustache.render(framecode, {ytid: ytid}); console.log(rendered); // window.ytid = 'test3' console.log(ytid); popup = $('#popup' + movid); popup.popup({ opacity: 0.3, transition: 'all 0.3s' }); popup.popup('show'); popup.html(rendered); }); -
GAE - Trouble Deleting Entity from key
I am having trouble deleting entities from keys in the GAE using python/ndb. I am able to retrieve the entity (problem) key from the page, but cannot figure out how to get it to delete. The GAE support page says it's as simple as retrieving the key and then deleting it, as seen below. problem = problem_key.get() problem.key.delete() But this is not working. I'm pretty sure the key is being obtained correctly. The HTML looks like {%for problem in problems %} <tr> <td>{{ problem.tags }}</td> <td><script type="math/tex">{{ problem.content }}</script></td> <td>{{ problem.answer }}</td> <td>{{ problem.quiz }}</td> <td>{{ problem.id }}</td> <td>{{ problem.date }}</td> <form action="/deleteProblem" method="POST"> <td><button type="submit" name="problem_key" value="{{ problem.key }}">Delete Problem</button></td> </form> </tr> {% endfor %} And my python code looks like: class deleteHandler(BaseHandler): def post(self): prob_key = self.request.get('problem_key') problem = prob_key.get() problem.key.delete() self.redirect("/") I'm getting: problem = prob_key.get() AttributeError: 'unicode' object has no attribute 'get' My best guess is that prob_key is getting assigned the actual unicode and so of course there is no get() method for it but I don't understand how to fix the problem based on Google's explanation of how it should function. -
django serialize missing fields
I have one model I can grab everything for, it serializes fine. I have another model I can grab everything for and it only serializes two fields: created_at updated_at The first model which, This works: object_list = CesiumEntity.objects.filter(sensor__in = sensor) #the __in because it is a list To which this passes the right object_list back: jdata= serialize('geojson', object_list, geometry_field='mpoly', fields=('name','file_name', 'id', 'dzi_location', 'country_code', 'corner_coords', 'sensor', 'targetName', 'collection_date')) Javascript object: data : "{"type": "FeatureCollection", "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}, "features": [{"geometry": {"type": "Polygon", "coordinates": [[[101.090860622, 1.29979532276], [100.796657363, 2.65773131268], [102.123191431, 2.94911750556], [102.416301014, 1.59362344826], [101.090860622, 1.29979532276]]]}, "type": "Feature", "properties": {"file_name": "77749", "country_code": "cc", "collection_date": "2010-04-17", "corner_coords": "CoordsNA", "sensor": "RADARSAT-2", "dzi_location": "dzi", "name": "77749"}}, {"geometry": {"t But if I do this: object_list = ZoneEntity.objects.filter(cesiumentity__sensor__in=sensor).distinct('zone_number') I can even print out the field I want verifying it is there: (zone_number) l = dir(object_list[0]) print object_list[0].zone_number But when I serialize it the front end sees so much less jdata = serialize('geojson', object_list); Tried diff versions too: jdata =serialize('geojson', object_list, geometry_field = 'mpoly'); none of these work on serializing the data. Resulting javascript object: data : "{"type": "FeatureCollection", "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}, "features": [{"geometry": {"type": "Polygon", "coordinates": [[[-76.7711677399, 0.191788350274], [-76.8355934471, 0.488658291123], [-76.5785549909, 0.545964899334], [-76.5140894777, 0.249182514026], … -
how compare type in template django
Got code: {% for type in foodtypesmain %} {{ type_id }} {{ type.id }} {% if type.id == type_id %} ........... {% else %} ........... {% endif %} ......... answer in template: 1 1 1 2 1 3 1 4 But! 1 not = 1 WTF? I think that problem in anoter types str and ind how i can compare type.id with type_id -
Django Dictsort by __str__
I have a project where one of the models is "Chassis". I want to sort these chassis in django templates by the value returned by __str__. If I write |dictsort:"__str__" it crashes. I'm currently getting around this by writing a function getIP that returns the same thing as __str__ and passing |dictsort:"getIP". Is there a way to do this without simply rewriting the exact same code in a different function? -
Save PIL edited image to Django ImageField
So i've got a Django submission system, and i would like to take database Submission Image instances, resize them and create Display instances, as goes the models: class Submission(models.Model): def __str__(self): return self.title title = models.CharField(max_length=20) signature = models.CharField(max_length=20) pickoff = models.ForeignKey('Pickoff', on_delete=models.CASCADE) sub_date = models.DateField() s1_vote_count = models.IntegerField(null=True) finals_vote_count = models.IntegerField(null=True) img = models.ImageField(upload_to='MEDIA_ROOT') repcount = models.IntegerField() and the Display model: class DispImg(models.Model): sub = models.ForeignKey('Submission', on_delete=models.CASCADE) img = models.ImageField(upload_to="MEDIA_ROOT") and the display image dimensions are told by the Type tableclass Type(models.Model): def __str__(self): return self.name name = models.CharField(max_length=30) min_w = models.IntegerField() max_w = models.IntegerField() min_h = models.IntegerField() max_h = models.IntegerField() disp1_width = models.IntegerField() disp1_height = models.IntegerField() disp2_width = models.IntegerField(null=True) disp2_height = models.IntegerField(null=True) disp3_width = models.IntegerField(null=True) disp3_height = models.IntegerField(null=True) The function i use to create the DispImg def getFinalDisplay(sub): po = sub.pickoff t = po.type img = sub.img l = [t.disp1_height, t.disp1_width] if t.disp2_height > 1: l.append(t.disp2_height) l.append(t.disp2_width) if t.disp3_height > 1: l.append(t.disp3_height) l.append(t.disp3_width) for h, w in zip(l, l): size = w, h disp = Image.open(img) disp = disp.resize(size) img = DispImg( sub=sub, img=disp ) img.save() And it all works out fine until the save part, where i get this error: AttributeError: 'bytes' object has no attribute '_committed' … -
Auto Generated Slugs in Django Admin
I have an app that will one day allow front-end crud, which will create the slug with slugify. Right now though, all the object creation is being done in the admin area and I was wondering if there is a way to auto generate slugs while creating and saving an object from within admin? Here is the method for slugify for the front-end; not sure if its even relevant. Thank you. def create_slug(instance, new_slug=None): slug = slugify(instance.title) if new_slug is not None: slug = new_slug qs = Veteran.objects.filter(slug=slug).order_by('-id') exists = qs.exists() if exists: new_slug = '%s-%s' % (slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug -
Django: "django.http.request.RawPostDataException: You cannot access body after reading from request's data stream"
I keep getting an error every time I try to log this user in. Here are the relevant tracebacks: AttributeError: 'Request' object has no attribute 'body' During handling of the above exception, another exception occurred: raise RawPostDataException("You cannot access body after reading from request's data stream") django.http.request.RawPostDataException: You cannot access body after reading from request's data stream This is inside my views.py: @api_view(['POST']) def login(request): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user is not None: login(request) print("Breakpoint") return Response(status=status.HTTP_200_OK) print('something went wrong') return Response(status=status.HTTP_401_UNAUTHORIZED) -
Django - Model objects created from one user visible to all other users
I have a site using Django that has a model named 'CampaignProfile' - and authenticated (logged in) users can create a CampaignProfile object through a form. Once created, the model object can be viewed on the authenticated users personal dashboard. However, when I log in to other user accounts then the same model objects are viewable on their personal dashboard when they shouldn't be. How would I specify that only the objects created by any given user can only be seen by that user (with the exception of the Django Admin)? dashboard.views.py: def dashboard_main(request): if request.user.is_authenticated: all_campaigns = CampaignProfile.objects.all() return render(request, 'dashboard-main.html', {'all_campaigns': all_campaigns}) else: return redirect('/users/login/?next=') I've already tried 'user.CampaignProfile.objects.all()' when I create variable 'user=request.user.id' so that the user requesting the objects can only see their own; but this leads to errors saying that user does not have attribute CampaignProfile. Though I've set the ForeignKey for my CampaignProfile model to be related to UserModel (the following model)... Here's my custom user model accounts.models.py: class UserModel(AbstractBaseUser): user_email = models.EmailField(max_length=255, unique=True, verbose_name='Email Address') user_fname = models.CharField(max_length=30, verbose_name='First Names') user_lname = models.CharField(max_length=30, verbose_name='Last Name') dt_joined = models.DateTimeField(auto_now_add=True) dt_updated = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'user_email' … -
Django tutorial part 2 - app does not show up on admin after registering
Following the Django tutorial (part 2), I can't seem to see my Polls app in my django admin panel after registering it. My screen looks a bit like this, with a distinct lack of a section for the Polls app: I've registered my app in the admin.py file, added it to INSTALLED_APPS in settings.py in my project folder, and restarted my nginx (following this answer), and I'm still hazy as to what the problem is or, for that matter, how to debug it. -
Django POST request issue with model
I have a model Condition that has a field symptoms, which takes multiple different Symptoms objects. Whenever, I make a POST request to create a Condition object, I get the following error: 'Condition: epilepsy' needs to have a value for field "condition" before this many-to-many relationship can be used. The above 'Condition: epilepsy' is nested between <>, but theres a formatting issue with posting that. Here is my Condition model: class Condition(models.Model): class Treatment(): SURGERY, NON_INVASIVE, PRESCRIPTION_MEDICINE, NONE = range(4) CHOICES = ( (SURGERY, 'Surgery'), (NON_INVASIVE, 'Non-Invasive Treatment'), (PRESCRIPTION_MEDICINE, 'Prescription Medicine'), (NONE, 'None') ) class Medicalfield(models.Model): ONCOLOGY, CARDIOLOGY, NEPHROLOGY, PEDIATRICS, ENDOCRONOLOGY, PSYCHOLOGY = range(6) CHOICES = ( (ONCOLOGY, 'Oncology'), (CARDIOLOGY, 'Cardiology'), (NEPHROLOGY, 'Nephrology'), (PEDIATRICS, 'Pediatrics'), (ENDOCRONOLOGY, 'Endocronology'), (PSYCHOLOGY, 'Psychology') ) name = models.CharField(max_length=200) contagious = models.BooleanField() treatable = models.BooleanField() treatment = models.IntegerField(choices=Treatment.CHOICES, null=True) severeity = models.IntegerField(default=0) symptoms = models.ManyToManyField('Symptom', blank=True) medicalfield = models.IntegerField(choices=Medicalfield.CHOICES, null=True) new = ConditionManager() def __unicode__(self): return u"%s" % ( self.name ) Here is my Serializer class ConditionSerializer(serializers.ModelSerializer): def create(self, validated_data): attrs = validated_data request = self.context['request'] return Condition.new.create_condition(**attrs) class Meta: model = Condition fields = ('id', 'treatment', 'name', 'contagious', 'treatable', 'treatment', 'severeity', 'symptoms', 'medicalfield') Here is the Manager class ConditionManager(models.Manager): use_in_migrations = True use_for_related_fields=True def create_condition(self, … -
MySql django error
I keep getting the following error when try7ing to set up mySql with Django?????? File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 28, in raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb Here is my settings.py DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test_database', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT':'8889', } } -
Bokeh Charts Legend - legend.legends not declared
I am trying to embed a chart using Bokeh Charts using data from pandas DataFramework to Django. The strange thing is the chart display just fine on a html file when I run the method but it fails to load in the Django framework, posting error: Bokeh Error property Legend.legends wasn't declared Once I remove legend then everything works fine. Either way, the chart works well in the html output file when I just run the function by itself. Any idea? -
django many to many join table move from one app to another
I want to separate Fat models.py of one Django App to another Django App with same database table names. Because lakhs of data present in the production server. My first models.py is below from django.db import models class LineItem(models.Model): workorder_reference_id = models.CharField(max_length=20, default=0) class WorkOrder(models.Model): lineitem = models.ManyToManyField(LineItem, related_name="line_item") then while going for new App. I commented above code and the new models.py like below from django.db import models # Create your models here. class LineItem(models.Model): class Meta: managed = True db_table = "forkey_lineitem" workorder_reference_id = models.CharField(max_length=20, default=0) class WorkOrder(models.Model): class Meta: managed = True db_table = "forkey_workorder" lineitem = models.ManyToManyField(LineItem, related_name="line_item", through="Wayjoin") class Wayjoin(models.Model): class Meta: managed = True db_table = "forkey_workorder_lineitem" workorder = models.ForeignKey(WorkOrder) lineitem = models.ForeignKey(LineItem) When I am trying to access lineitem using below code. from waykey.models import * wo = WorkOrder.objects.last() wo.lineitem.all() I am getting below error. FieldError: Cannot resolve keyword u'line_item' into field. Choices are: id, workorder_reference_id I am in middle of commitment. Kindly provide me solution as soon as possible. -
How do you use include tags correctly?
I don't understand why I am getting this error "Invalid block tag on line 29: 'includes', expected 'endblock'. Did you forget to register or load this tag?" Line 29 being the line where I have put the {% include %} tag in the INDEX.HTML file. Both of the html files below are in the same directory. INDEX.HTML FILE {% extends './base.html' %} {% load staticfiles %} {% block head_js %} {% endblock %} {% block content %} <!-- Page Content --> <div> <!-- Header/Home --> <header class="w3-container w3-padding-32 w3-center w3-black" id="home"> <h1 class="w3-jumbo"><span class="w3-hide-small">Cricket Scorer</span></h1> <p>A Simple Cricket Scoring Web App</p> </header> <!-- Selection Menu --> <div class="w3-content w3-justify w3-text-grey w3-padding-64"> <!--button type="button" class="btn btn-default btn-lg btn-block" data-toggle="modal" data-target="#match-details" onclick="alert('here');">Start Scoring</button><br--> <button type="button" class="btn btn-default btn-lg btn-block" data-toggle="modal" data-target="#select-home-team">Start Scoring</button><br> <button type="button" class="btn btn-default btn-lg btn-block">Players</button><br> <button type="button" class="btn btn-default btn-lg btn-block">Teams</button> </div> </div> {% include "start_scoring_modal.html" %} {% endblock %} START_SCORING_MODAL.HTML {% extends './index.html' %} {% load staticfiles %} <!-- Modal Boxes --> <div class="modal fade" id="select-home-team" role="dialog"> <div class="modal-dialog modal-bg"> <div class="modal-content"> ... ... ... ... -
Django rest framework - Delete model objects from HTML
So i'm developing an app using Django framework, and i need HTML forms to insert/delete and update data from the database. I was able to make the form to Update the data, but i can't seem to find any info on how to make a Create form and a delete button. I tried this, with no success: HTML <form action="{% url 'conta_details_html' conta.id %}" data-method="delete"> <input type="submit" value="delete"> </form> Views: def delete(self,request,pk): """Deletes a transaccao""" user = request.user if not user.is_authenticated: return Response(status=status.HTTP_403_FORBIDDEN) conta = get_object_or_404(Conta, pk=pk, user=user) serializer = ContaDetailsSerializerHTML(conta,many=False) if conta: conta.delete() return Response(status=status.HTTP_200_OK) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) Maybe im not getting the syntax correct on the html, but the update form was pretty easy, like this: <form action="{% url 'conta_details_html' conta.id %}" method="POST"> {% csrf_token %} {% render_form serializer %} <input type="submit" value="Save"> </form> any idea ?