Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django select field with thousands of choices creating thousands of database queries
I have two models, model B and model C, which both extend model A. In a form I have a model select field for model A - this obviously loads all instances of model B and C which was my intention. So this dropdown is over 1000 'A Objects'. I am using hasattr() to determine if they're B or C, which then uses the unicode method from those classes to display the object in string from in the dropdown. This creates thousands of SQL queries which takes around a minute to process. Right now my solution is to query the database 3 times (to get all A, B and C objects, and then loop over A and decide if each oject is of type B or C and push the correct unicode string into a list which is used in the dropdown. I then clean the data and select the right object when saving the form. This is hackey (to me). I was wondering if anyone knows of an efficient way of populating a dropdown with thousands of model object choices when that model is a Base Model for other models. Cheers, Dean -
Django filter ManyToManyField contains multiple
I have a model UserProfile which has ManyToManyField languages. class UserProfile(models.Model): ... languages = models.ManyToManyField('Language',...) For two languages -( lang_one, lang_two ), I want to filter UserProfiles which has both of these languages in languages_set. Is it possible to do it using one filter or should I filter already filtered QuerySet. This isn't possible: UserProfile.objects.filter(languages__contains=lang_one, languages__contains=lang_two) since I used two equal keyword arguments. Only thing except iterating is to filter result like this: UserProfile.objects.filter(languages__contains=lang_one).filter(languages__contains=lang_two) but I'm not sure about it's efficiency. -
Deploying a Django App to App Engine Flexible Environment
I am trying to deploy a sample app to the Google App Engine Flexible Environment based on this tutorial. The deployment works, however, the application cannot start up. I get the following error message: Updating service [default]...failed. ERROR: (gcloud.app.deploy) Error Response: [9] Application startup error: [2017-01-21 17:01:14 +0000] [5] [INFO] Starting gunicorn 19.6.0 [2017-01-21 17:01:14 +0000] [5] [INFO] Listening at: http://0.0.0.0:8080 (5) [2017-01-21 17:01:14 +0000] [5] [INFO] Using worker: sync [2017-01-21 17:01:14 +0000] [8] [INFO] Booting worker with pid: 8 [2017-01-21 17:01:14 +0000] [8] [ERROR] Exception in worker process Traceback (most recent call last): File "/env/lib/python3.5/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker worker.init_process() File "/env/lib/python3.5/site-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/env/lib/python3.5/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi self.wsgi = self.app.wsgi() File "/env/lib/python3.5/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/env/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/env/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/env/lib/python3.5/site-packages/gunicorn/util.py", line 357, in import_app __import__(module) ImportError: No module named 'mysite' [2017-01-21 17:01:14 +0000] [8] [INFO] Worker exiting (pid: 8) [2017-01-21 17:01:14 +0000] [5] [INFO] Shutting down: Master [2017-01-21 17:01:14 +0000] [5] [INFO] Reason: Worker failed to boot. As you can see on GitHub (see link above), the /app.yaml file looks like this: # [START runtime] runtime: … -
Reverse error in Django 1.10
I'm new to Django and slowly learning how it works. I just upgraded to 1.10 and part of my app stopped working. I know it is related to the changes made into Reverse. I have been reading and I cannot find exactly what I'm doing wrong. Almost everything works as it should with a couple of exceptions. The behavior is as follows: 1) On my app I load reservations/create, it works perfectly I can create my reservation 2) When I click create, the reservation is actually created and saved into the database, but the browser is sent to the wrong address. It gets sent to reservations/create instead of reservations/reservation number (for example reservations/2 where it shows its details) and shows a Reverse error (included in this post) 3) If I test reservations/2 for example, it shows that it was actually created. 4) Also if a go straight to reservations/ it should show a list of all the ones already create, but instead shows a Reverse error too. I would really appreciate any help in understanding what I'm doing wrong. Models.py class Reservation(models.Model): res_number = models.AutoField(primary_key=True) date = models.DateField(default=datetime.date.today()) status = models.CharField(max_length=10,default="Created") reservation_type = models.CharField(max_length=11,choices=shced_type_choices, default="rental") aircraft = models.ForeignKey('aircraft.Aircraft') renter = … -
ValueError: needs to have a value for field "" before this many-to-many relationship can be used
Django Version: 1.10.4 Exception Type: ValueError Exception Value: "<SchoolBook: 0 test1 Test2 Test3 2011 122>" needs to have a value for field "schoolbook" before this many-to-many relationship can be used. PLease help to avoid this error: class Subject(models.Model): name = models.CharField(max_length=256) slug = models.SlugField(max_length=256, blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.name, separator='_') return super(Subject, self).save(*args, **kwargs) class SchoolBook(models.Model): parent_subject = models.ManyToManyField(Subject) year = models.SmallIntegerField() name = models.CharField(max_length=256,blank=True) autors = models.CharField(max_length=256) slug = models.SlugField(max_length=256, blank=True, unique=True) f_file = models.FileField(upload_to=directory_path) def __str__(self): return '{0} {1} {2}'.format( self.name, self.autors, self.year) def save(self, *args, **kwargs): if not self.id: subject_name = [self.parent_subject.values()[i]['name'] for i in range(len(self.parent_subject.values()))] self.name = ' '.join(subject_name) self.slug = slugify("{} {} {} {} {}".format(self.name, self.autors,self.year, self.pages, self.c_class)) return super(SchoolBook, self).save(*args, **kwargs) the issue is when i am trying to save the object. -
axios request to django REST framework causes error "Error: Permission denied to access property Symbol.toPrimitive"
I have a django REST app and I'm using react+redux for my UI. I tried to get these working together by the way explained in this article! everything is working as expected but not requests made by axios. I have commented out all my requests to DRF and everything else works fine. anywhere in my react app, when I reach an axios request, it causes this error in my console: Error: Permission denied to access property Symbol.toPrimitive I actually had this error when I started making my react app seperately and had problems with sending requests as an external domain to DRF, and I ended up with this solution and using django-cors-headers fixed it. But now I'm sending my request from within a django template to my own django server so it does not make any sense. any clue on this? btw this is my config files in case it helps figuering it out. webpack.config.js var path = require("path") var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') module.exports = { context: __dirname, entry: './assets/js/index', // entry point of our app. assets/js/index.js should require other js modules and dependencies it needs output: { path: path.resolve('./assets/bundles/'), filename: "[name]-[hash].js", }, plugins: [ new … -
Chain queries in parent Models
I have a bunch of different Models that access different tables in a database and are chained to each other by inheritance as follows: class Food(models.Model): # Some unique fields and properties # Meta class Meta: abstract = True # Inherited by two "food groups" with different tables class FoodGroup(Food): # Some unique fields and properties # Meta class Meta: db_table = 'foodgroup' class Fruit(FoodGroup): # Some unique fields and properties # Meta class Meta: db_table = 'vors' class Apple(Fruit): # Some unique fields and properties # Meta class Meta: db_table = 'ndbs' class Seed(Apple): # This is a placeholder to collect all of the data # under a name that makes sense rather than just "Apple" # One unique field # Meta class Meta: managed = False # Doesn't have a table I would like to be able to create an instance of the Seed class that then has all of the parent class fields from their respective tables and allows me to access it simply through the one Seed object. The issue is that I need data from the fields in the Food class for the queries in the Fruit, and Apple classes. How can I run all … -
How to write Nested DRF Serializer with two foreign key fields
Suppose I have Django Models as follows: class Car(models.Model): name = models.CharField() model = models.CharField() type = models.CharField() class Scooter(models.Model): name = models.CharField() model = models.CharField() type = models.CharField() class User(models.Model): name = models.CharField() car = models.ForeignKeyField() scooter = models.ForeignKeyField() and the serializers as follows: class CarSerializer(serializer.ModelSerializer): class Meta: model = Car fields = ( 'name', 'model', 'type' ) class ScooterSerializer(serializer.ModelSerializer): class Meta: model = Scooter fields = ( 'name', 'model', 'type' ) class UservehicleCreateSerializer(serializer.ModelSerializer): car = CarSerializer() scooter = ScooterSerializer() class Meta: model = User fields = ( 'name', 'car', 'scooter' ) So the scenario is something like this: The car data and scooter data is already created let's assume both have pk=1. and I want to create the User data using the serializer respectively. But struggling to find the actual resource for same in my case . The data for car and scooter is already there I need not create it again. have Tried what's here in DRF Documentation for writing serialized nested. and Data for Api post requestis as follows: { 'name': "Nikhil", 'car': 1, 'scooter': 1 } Need help on this thing. Thanks! -
How to display specific navbar when logged in?
I have created 2 navbars, one for when user is logged in and one for when they are not. I need to display the correct navbar dependending upon if the user is logged in or not. I know i need to check in Django with something like this, {% if user.is_authenticated %} {% return navbarLogged %} {% else %} {% return navbarsignup %} But I'm confused on what i should include in my return and where exactly to put this in my code. Should I add this to my base.html? Or, can i just create a function in my models and then call the function at the beginning of base.html? New to programming, thanks again in advance! -
custome user serializer giving error on is_valid() - django
For some reason I am not using form model to create the user form and so on so I am not using the form.is_valid() I went through online and was taught to create a serializer like this from django.contrib.auth.models import User from rest_framework import serializers class UserModelSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'password'] I tried creating a new user object in python shell then use the serializers on the object then uses the is_valid() but it gives me false instead of true, also the password being created is not hashed too, it was just a string I did something like this in python shell. (also tried one that has id too but the result is the same so I didn't bother pasting it again) user1 = User.objects.create(username='username', email='email@email.com', password='password') user1_s = UserModelSerializer(user1) when I run user1_s this came up UserModelSerializer(<User: username>): id = IntegerField(read_only=True) username = CharField(allow_blank=True, max_length=150, required=False) email = EmailField(max_length=254, required=True) password = CharField(max_length=128) run user1_s.data {'username': u'username', 'password': u'password', 'id': 4, 'email': u'email@email.com'} run user1_s = UserModelSerializer(data=user1) run user1_s.is_valid() and False is returned run user1_s.errors {u'non_field_errors': [u'Invalid data. Expected a dictionary, but got User.']} ----------------------------------- Can someone please let me know how … -
How to create nested comment system with django-mptt
I'm working on simple blog and I'm trying to implement a nested comment system for each post. I created model for comments and it's works fine via Django Admin Page. I don't know how to create form for posting new comment and replying. Here is what I have so far: models.py (...) class Post(models.Model): author = models.ForeignKey('Author', on_delete=models.CASCADE) title = models.CharField(max_length=250) slug = models.SlugField(unique=True, blank=True, max_length=250) created = models.DateTimeField(auto_now=False, auto_now_add=True) modified = models.DateTimeField(auto_now=True, auto_now_add=False) tags = TaggableManager(blank=True) image = models.ImageField(upload_to="images/%Y/%m/", blank=True, null=True) content = models.TextField() def get_absolute_url(self): return reverse('post_detail', kwargs={'slug': self.slug, }) # create slug def save(self, *args, **kwargs): if not self.id: self.slug = slugify(unidecode(self.title)) super(Post, self).save(*args, **kwargs) def __str__(self): return str(self.title) class Comment(MPTTModel): post = models.ForeignKey("Post", on_delete=models.CASCADE, null=True, related_name='comments') parent = TreeForeignKey('self', null=True, blank=True, related_name='replies', db_index=True) name = models.CharField(max_length=250) email = models.EmailField(max_length=250, blank=True, null=True) website = models.CharField(max_length=250, blank=True, null=True) created = models.DateTimeField(auto_now=False, auto_now_add=True) content = models.TextField() def __str__(self): return str("{}: {}...".format(self.name, self.content[:50])) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = [ "name", 'email', 'website', 'content'] views.py class PostDetailView(DetailView): model = Post def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context['form'] = CommentForm() return context class PostCommentView(SingleObjectMixin, FormView): template_name = 'blog/post_detail.html' form_class = CommentForm model = Post def post(self, … -
Django store original file name and generate new name
I have a 'beginner' problem with Django. In my models.py file I have the following class: class File(models.Model): user = models.ForeignKey(User) uploaded_file = models.FileField(upload_to = 'documents/%Y/%m/%d/', null=True, blank=True) real_name = models.CharField(max_length=255) generated_name = models.CharField(max_length=255, unique=True) is_deleted = models.BooleanField(default=False) extension = models.CharField(max_length=255) size = models.FloatField(max_length=255) password = models.CharField(max_length=255, null=True, blank=True) download_link = models.URLField(null=True, blank=True) uploaded_at = models.DateTimeField(auto_now=False, auto_now_add=True) def __unicode__(self): if len(self.real_name) > 15: return self.real_name[:12] + '..' return self.real_name the idea is that real_name holds the original name of the file (the name of the file when the user uploads it) and that generated_name is some random string such as "asnfu5315nf9cy0024". The reason for that is because I want to restrict direct access to the media folder, so that the user can't access the file directs through /media/documents/2017/01/21/real_name.extension . Is it possible to add a restriction in addition to that, because it is pretty simple to inspect an image for example and get the correct path ? So that when /media/documents/... is called the user gets an error ? I read some posts about it, but didn't get it completely. I will most probably need both, since it is possible that two files have the same name and when they … -
ModelForm doesn't manage instance model as I need
My problem is that I want to manage dialogue attributes using ModelForm. Now I need to realize adding in dialogue participants and changing name of dialogue. I tried to do it using code below but when I add participants dialogue name is becoming empty string. Changing name simply doesn't work. This dialogue model contains methods which I use for changing name - (def change_name) and adding participants (def add_participants): class Dialogue(models.Model): name = models.CharField(max_length=30, blank=True) is_conference = models.BooleanField(default=False) notifications_on = models.BooleanField(default=True) creator = models.ForeignKey( Person, related_name='+', null=True, ) participants = models.ManyToManyField( Person, related_name='dialogues', ) def __str__(self): return self.name or str(self.pk) def add_participants(self, *args): new_participants = args for new_participant in new_participants: self.participants.add(new_participant) return self def remove_participants(self, *args): participants = args for participant in participants: self.participants.remove(participant) return self def change_name(self, new_name): self.name = new_name return self In this ModelForm I create Dialogue with is_conference attribute which always equals true. I divided two opportunities: when I create conference and when I manage existing conference. So I have problems with second part. I tried to remove part where I call function change_name but anyway dialogue name is becoming empty after I add new participants. class CreateConferenceForm(forms.ModelForm): class Meta: model = Dialogue fields = ['name', … -
how to smart update a value based on heavy calculation every n seconds (performance)
In django we have a Task model that contains a 'progress' Float field. This progress float field is calculated based on some calculation of related outputs (Output model). We use a trigger (using django signals (on save of the Output) that recalculate the progress Float field each time the value of the outputs changes. This does not scale well and when bulk updating the Output the progress re-calculation is triggered many times (blocking, not async) which is only needed at the end of the bulk update sequence. I am looking for performance improvements and and came up with the following solution options save a 'dirty' flag in the Task object and let a async runner (on a beat) scan for these dirty flags and recalculate the property when needed, or only update the progress if it was updated > n seconds ago (a TTL), or Delay (put in async queue) by n seconds and if in the meantime another progress recalculation task is put in the queue, delete the original one. I am looking for a proper implementation pattern that does not recalculate the progress every trigger, but maximum every n seconds, and after n seconds I do have a … -
Updating deployed django project
If I need to update deployed Django Project, can I just only delete old app_name folder and paste new app_name folder from local development, or migrations will crash in this case, therefore I am only able to delete and copy all files(init.py, views.py, modals.py and etc) except migrations in production? -
Embed an interactive Bokeh in django views
I want to make interactive plot in django views (or model ?). I think Bokeh fit my needs because, I have matplot/seaborn that I can reuse and I'm not pretty good at javascript. There was no problem for me to follow this example : how to embed standalone bokeh graphs into django templates. As I understand, I need to run a bokeh server and make some proxy using nginx How can I embed a interactive bokeh plot into a django view ? Any helps will be appriciated. Regards -
Django default value
If I create a field as typed below, will the default value be saved to the object, when the field on the form leaved blank? field_name = models.FloatField(default=100.0, blank=True) -
Getting error: type object 'x' has no attribute 'objects', while defining custom queryset and model
I am facing difficulty in integration of custom manager and queryset for django models with django-rest. I have defined a custom manager named 'manager'. But rest_framework requires that manager must be available as 'objects' in the model. Following is my django code :- custom queryset and manager class ActivableQuerySet(QuerySet): def all(self, return_all=False): if return_all: return super(ActivableQuerySet, self).all() else: return self.get_active() def get_active(self): return super(ActivableQuerySet, self).filter(is_active=True) @transaction.atomic def delete(self): for obj in list(self): obj.delete() class ActivableModelManager(Manager): _queryset_class = ActivableQuerySet def all(self, *args, **kwargs): return self._queryset_class(self.model, using=self._db, hints=self._hints).all(*args, **kwargs) models.py class DictStrModelMixin(Model): class Meta: app_label = 'generic_models' abstract = True def __str__(self): return str(model_to_dict(self)) class ActivableModel(DictStrModelMixin): is_active = BooleanField(editable=False, null=False, default=True) manager = ActivableModelManager() class Meta: abstract = True _default_manager = "manager" def delete(self, *tupargs, **kwargs): pre_delete.send(sender=self.__class__, instance=self) self.is_active = False self.save(force_update=True) post_delete.send(sender=self.__class__, instance=self) class ActiveSerializer(ModelSerializer): class Meta: model = ActivableModel fields = 'all' Now, invoking ActiveSerializer.save() gives me the following error :- type object 'ActivableModel' has no attribute 'objects' Following is the line of code in rest_framework, which gives me this error Why is it so ? Doesn't django provides default manager 'objects' for all the models ? I have also tried setting _default_manager option in Meta class, but it doesn't … -
Autodoc Sphinx with django error
I get an error when I try to make html with autodoc. Here is my project structure : projet --- app1 ------ models.py ------ views.py --- app2 --- app3 docs --- modules ------ models.rst --- conf.py --- index.rst __init__.py manage.py My conf.py import os import sys sys.path.insert(0, os.path.abspath('..')) from django.conf import settings settings.configure() import django django.setup() # -- General configuration extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage'] And my model.rst Models ====== .. automodule:: projet.app1.models :members: :undoc-members: And I het this error : D:\Agrome\Agrome bitbucket\agrome-backend\docs\modules\models.rst:3: WARNING: autodoc: failed to import module u'agrome.boxes.models'; the following exception was raised: Traceback (most recent call last): File "c:\python27\lib\site-packages\sphinx\ext\autodoc.py", line 547, in import_object __import__(self.modname) File "D:\Agrome\Agrome bitbucket\agrome-backend\agrome\boxes\models.py", line 5, in <module> from django.contrib.auth.models import User File "c:\python27\lib\site-packages\django\contrib\auth\models.py", line 6, in <module> from django.contrib.contenttypes.models import ContentType File "c:\python27\lib\site-packages\django\contrib\contenttypes\models.py", line 161, in <module> class ContentType(models.Model): File "c:\python27\lib\site-packages\django\db\models\base.py", line 102, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. If I type .. automodule:: projet.app1 (whitout .models), it works but the doc is empty. Do you have any idea ? Thanks a lot -
Post with CSRF protected cookie, Jsoup
I would like to scrape the following web-site using Jsoup. As far as I understood, its back end is written using Django and the CSRF protection is enabled. In order to load more elements, the user must issue the POST request using the following URI https://jobs.dou.ua/vacancies/xhr-load/?category=Java. The request headers are (looked at the Chrome dev. tools): cookie:_ym_uid=_YM_UID; _ym_isad=1; sessionid=SESSION_ID; _gat=1;csrftoken=CRSF_TOKEN; _ga=_GA referer:https://jobs.dou.ua/vacancies/?category=Java user-agent:USER_AGENT x-requested-with:XMLHttpRequest Form-data: csrfmiddlewaretoken: CRSF_MIDDLE_WARE_TOKEN The CSRF token is obtained by performing GET request to the following URI: https://jobs.dou.ua/vacancies/?category=Java But, when I do perform the POST request with the obtained cookies, then I recieve the 403 response from the server that the CRSF token is invalid. How I do it in JSOUP Connection.Response response = Jsoup.connect("https://jobs.dou.ua/vacancies/?category=Java").execute(); Map<String, String> cookies = response.cookies(); Document doc2 = Jsoup.connect("https://jobs.dou.ua/vacancies/xhr-load/?category=Java") .cookie("content-type", "application/x-www-form-urlencoded; charset=UTF-8") .cookie("csrftoken","OBTAINED_FROM_MAP_OF_COOKIES") .userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36") .post(); I suspect that the problem might be connected with the crsfmiddlewaretoken. If that is true then how can I pass crsfmiddlewaretoken in post request using Jsoup? What are the other possible options to fix the 403 error? -
Will prefetch and select work for the following database
I have the two following models: class Table1(models.Model): locker_id = models.IntegerField(primary_key=True) locker_name = models.CharField(db_column='Locker_name', max_length=45, blank=True, null=True) # Field name made lowercase. city = models.CharField(max_length=45, blank=True, null=True) state = models.CharField(max_length=45, blank=True, null=True) pincode = models.CharField(max_length=45, blank=True, null=True) locker_capacity = models.CharField(max_length=45, blank=True, null=True) and: class Table2(models.Model): key = models.AutoField(primary_key=True) locker = models.ForeignKey(Table1) empty_slots = models.CharField(max_length=45, blank=True, null=True) Now using django and python I want to make the following query and return a new tuple structure. The SQL analogy is as follows: SELECT * FROM Table1 INNER Table2 ON Table1.locker_id=Table2.locker_id; Can anyone help me out with the syntax, or any reference. Thankyou. -
Django apache Python3.5
I use a bunch of Ubuntu 16.04 + Apache 2.4 + Django 1.10 + Python3.5 + wsgi + virtualenv. Everything works but for some reason, use Python 2.7.12, and I need 3.5 On the page of the site is written Python Version 2.7.12 The apache configuration ordered following WSGIDaemonProcess myproject python- path=/home/admin/web/domen.com/private:/home/admin/web/domen.com/private/myprojectenv/lib/python3.5/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/admin/web/domen.com/private/myproject/wsgi.py wsgi.py standard import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") application = get_wsgi_application() -
django ajax javascript not working
1. I'm trying to add ajax to my django web application... The code i've written is given below... for testing i wanted to display a text in the html element whose id="id_ajax1"... the code successfully displays the text, but it automatically reloads the page again... 2. when I write the 1st one from the code given below this line, the behaviour is as mentioned above... when I write the 2nd one from the code below, it shows broken pipe ('127.0.0.1', 46958) return HttpResponse("text to be returned asynchronously") return HttpResponse("text to be returned asynchronously", mimetype="application/javascript") The code: ajax.html <form action onsubmit="ajax1()"> <span id="id_ajax1"></span> <button class="col-5" type="submit">click</button> </form> ajax.js function ajax1() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("id_ajax1").innerHTML = this.responseText; } }; var url = "test/ajax1"; xhttp.open("GET", "/profile/ajax1", true); xhttp.send(); } urls.py urlpatterns = [ url(r'^test/ajax1/$', views.ajax1, name='ajax1'), ] views.py def ajax1(request): return HttpResponse("You have successfully written your first ajax code") -
redifine method delete or destroy in modelviewset of Django Rest Framework
I have a special delete, so I cannot just use DELETE method. this is the model: class PersonalDetail(models.Model): icon = models.URLField(_('icon'), max_length=500, blank=True, default='') date = models.DateTimeField(_('date'), auto_now_add=True) checked = models.BooleanField(_('checked'), blank=True, default=False) priority = models.CharField(_('priority'), blank=True, max_length=1) preview_title = models.CharField(_('preview_title'), blank=True, max_length=100) preview_text = models.TextField(_('preview_text'), blank=True) preview_name = models.CharField(_('preview_name'), blank=True, max_length=100) type = models.CharField(_('type'), choices=PERSONAL_DETAILS_INFO, default='Info', max_length=100, blank=False) content = JSONField(_('content')) user_id = models.ForeignKey(User, related_name='userId', on_delete=models.CASCADE) The point is, when the "type" is message, facebookpost or info, then I have to delete except icon, id and preview_title. Until now, I could use some kind of PUT. But... when the "type" is userdefined then I gotta delete everything, like a normal delete. So, I don't have idea how I can do it. I thought that maybe I could use something like .destroy() and override it. For example, I know how to override perfom_create() or get_queryset(), but nothing with delete. My view looks so: class PersonalDetailViewSet(viewsets.ModelViewSet): queryset = PersonalDetail.objects.all() serializer_class = PersonalDetailSerializer def get_queryset(self): return PersonalDetail.objects.filter(Q(user_id=self.request.user)) def perform_create(self, serializer): serializer.save(user_id=self.request.user) # Not delete icon, id, preview_title Maybe someone knows how to do it. -
Django Rest Framewrok api how to add Authecation permission for all
I've followed tutorial provided here exactly. http://www.django-rest-framework.org/tutorial/1-serialization/ But all my snippets are being viewed even there is no log in. How to prevent this? I've user this in the settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } And now the Users api is not giving access. But snippets are getting viewed. I'm new to Django, how can I add permission for snippets to, to act like user. Also I want admin to be able to edit, delete snippets. how to accomplish these?