Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect non relational database with django
I was trying to connect mongodb with django but its keep on trowing error can some one helps me with accurate answer or suggestion. -
Tastypie ToOneField not working
My Models: class UserDetails(models.Model): user=models.ForeignKey(User) email=models.CharField(max_length=30) name=models.CharField(max_length=30) class Problem(models.Model): user=models.OneToOneField(UserDetails) onset_time=models.CharField(max_length=20) symptoms=models.CharField(max_length=50) Resources: class ProblemResource(ModelResource): class Meta: queryset=Problem.objects.all() resource_name="hypo" class UserResource(ModelResource): hypo=fields.ToOneField(ProblemResource,'hypo') class Meta: queryset=UserDetails.objects.all() resource_name="user" I want to fetch the problem of a particular user using '/user' api call but I am getting this error:- {"error": "The model '<UserDetails: UserDetails object>' has an empty attribute 'hypo' and doesn't allow a null value."} I've been through the data and there are no null values . -
How to create instance
Q:-3 Create a class named ‘Animal’ which includes methods like eat() and sleep(). Create a child class of Animal named ‘Bird’ and override the parent class methods. Add a new method named fly(). Create an instance of Animal class and invoke the eat and sleep methods using this object. Create an instance of Bird class and invoke the eat, sleep and fly methods using this object. -
Django: reverse accessor for clashes with reverse accessor for
Following are two fields in a class of models.py. These are two keys refereed as foreign key from same key of another table. Code: permenantpincode = models.ForeignKey(Pincodemap, models.DO_NOTHING, db_column='PermenantPincode') localpincode = models.ForeignKey(Pincodemap, models.DO_NOTHING, db_column='LocalPincode') # Field name made lowercase. This is showing following error while migration. ERRORS: NssAdmin.Volunteer.localpincode: (fields.E304) Reverse accessor for 'Volunteer.localpincode' clashes with reverse accessor for 'Volunteer.permenantpincode'. How could I fix this ? -
django class page view not rendering template code
I wanted to use class based views and went through the django documentation and I get noerror messages but wind up with an empty template. I had it working with the non-classed based views. How do I reformat the code so that it renders the template? The template consists of a title, some headings, a navigational menu, flags for selecting instructions in different languages, followed by a form which shows a flag, policy name char field, and a check box control. I think the initial = {'key': 'value'} in the view forms incorrect but I don't know what to replace it with. Thanks in advance. forms.py from django import forms from policytracker.models import Flag, Label_Links class PolicyStartForm( forms.Form ): flags = Flag.objects.all() policy = Label_Links.objects.all().filter(iso_language='en')[0] frm_policy1_name=[] for flag in flags: frm_policy1_name.append(forms.CharField(max_length=40)) policy_dict = { 'new_policy_link' :policy.nav_section_new_policy_link, 'new_policy_label' :policy.nav_section_new_policy_label, 'graphs_link':policy.nav_section_graphs_link, 'graphs_label' :policy.nav_section_graphs_label, 'account_link' :policy.nav_section_account_link, 'account_label' :policy.nav_section_account_label, 'policy_list_link':policy.nav_section_list_policies_link, 'policy_list_label':policy.nav_section_list_policies_label, 'login_link' :policy.nav_section_login_link, 'login_label' :policy.nav_section_login_label, 'new_policy1_heading' :policy.new_policy1_heading, 'new_policy1_title_label':policy.new_policy1_title_label, 'policy_needs_translation_label':policy.new_policy1_needs_trans_label, 'policy1_submit_label': policy.new_policy1_submit_button_label, 'policy1_tip_msg' :policy.new_policy1_tip_msg, 't_logged_in' :True, 'frm_policy_name' :frm_policy1_name, 't_flags' :flags } </code> <code> views.py # coding=utf-8 from django.shortcuts import render from django.http import HttpResponseRedirect from policytracker.forms import LoginForm, PolicyStartForm from policytracker.models import Flag, Label_Links from django.views import View class PolicyStartView(View): template_name = 'policystart.html' initial = … -
DRF Serializer validation by database column
I have a custom serializer like this-- class customSerializers(serializers.Serializer): token = serializers.CharField(max_length=12) And I have a model like this class UserToken(models.Model): user = models.ForeignKey(User) token = models.CharField(max_length=12) Now I want to validate my customSerializers token field. The token value has to exists in the UserToken model and belongs to the current user. ** I Don't want to use model serializer. -
Uwsgi disables django.request logging
If I start application using uwsgi I don't see logs related to django.requests. But If I start the same code on the same machine using manage.py runserver 8080 it works perfectly. Any ideas why it might happen? I run uwsgi by this command /home/gs/python-env/bin/uwsgi --ini /etc/uwsgi.d/uwsgi.ini --static-map /static=/home/gs/api/static/ uwsgi.ini [uwsgi] http-socket=:8080 home=/home/gs/python-env chdir=/home/gs/api module=server.wsgi env=server.settings processes=1 enable-threads=true My logging configuration from settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(process)d %(threadName)s %(module)s %(funcName)s %(message)s' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': '/var/log/gs/api.log', 'formatter': 'verbose', 'maxBytes': 1024 * 1024 * 16, # 16Mb }, 'elasticsearch': { 'level': 'DEBUG', 'class': 'api.common.elasticsearch_log_handler.ElasticSearchHandler', 'hosts': [{'host': cluster.ES_HOST, 'port': 443}], 'es_index_name': 'logstash', 'es_additional_fields': {'type': 'api', 'cluser': cluster.CLUSTER_NAME}, 'auth_type': ElasticSearchHandler.AuthType.NO_AUTH, 'use_ssl': True, } }, 'loggers': { 'django': { 'handlers': ['file', 'elasticsearch', 'console'], 'level': 'INFO', 'propogade': True }, 'django.request': { 'handlers': ['file', 'elasticsearch', 'console'], 'level': 'DEBUG', 'propogade':False } } } If I change info to debug for 'django' I will see my logs from django logger but not from django.request. -
Django - global name error when authenticate with multiple database
I need really help over here, I have a basic app for login system, very very basic works ok, but now I'm trying to make it work with another database, at this it's not that easy as I thought. I was reading and I found I need a db router to make it work with my second database so I tried that. Here's what I got : settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'db2':{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'login.db'), } } MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'myapp.middleware.CustomerMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] DATABASE_ROUTERS = ['myapp.routers.MultiCustomerRouter'] routers.py from middleware import my_local_global class MultiCustomerRouter(object): def db_for_read(self, model, **hints): return my_local_global.db2 middleware.py from threading import local my_local_global = local() class CustomerMiddleware(object): def process_request(self, request): my_local_global.db2 = get_db2(request) # my database name is db2 I was following this Django Authenticate Backend Multiple Databases after I run python manage.py runserver I got this error: NameError at / global name 'get_db2' is not defined How can I handle this to make it work as expected with my database db2? views.py def login_view(request): print(request.user.is_authenticated()) title = 'login' form = UserloginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") … -
How to access row data in before_save_instance for Django Import Export
I'm trying to use django-import-export to load data into my Django site admin interface. During the input I want to do some complicated data validation which involves creating and/or modifying other models related to the one being uploaded into with django-import-export. It seems like the before_save_instance hook is the time in the import workflow that I want to perform this complicated validation. before_save_instance's input parameters include only the object for the model being updated, which does not contain all the data from the row being imported. In particular I don't see the read only fields from the row being imported anywhere (and I need them for my validation logic). How can I get access to the entire row being imported from inside of before_save_instance? -
Get rid of Help Text in reset password form
Django offers an simple and fast option for "Forget password" by overriding the default templates. Some of these forms come with help text The password_reset_form which I get the reset link from the email, I don't know how to get rid of the help text messages. It is displayed in the password_reset_form.html, by using {{ form.as_p}} Is there any way to remove the help text, without extending the ResetPasswordForm in forms.py to set the help text to none. It's complicated as the url for this form takes token. I tried this, but I'm almost sure it wouldn't work. forms.py class ResetPassword(PasswordResetForm): class Meta: fields = ("new_password1", "new_password2") model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["new_password1"].help_text = None views.py class resetpassword(LoginRequiredMixin, generic.UpdateView): template_name = "registration/password_change_form.html" success_url = reverse_lazy('password_reset_complete') form_class = forms.ResetPassword def get_object(self, queryset=None): return self.request.user def get_form_kwargs(self): kwargs = super(resetpassword, self).get_form_kwargs() kwargs['user'] = kwargs.pop('instance') return kwargs -
NameError at /accounts/scoreresults
I got an error , NameError at /accounts/scoreresults global name 'ImageAndUser' is not defined . I wanna show data from my database (which is ImageAndUser model) in results.html,but it did not work. I wrote in results.html, <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Score</title> </head> <body> <h1>Score</h1> <h2>Your score is {{ scoreresults.result }}</h2> </body> </html> But now, this part {{ user.result }} of Your score is {{ user.result }} is blank in my browser. I wrote in models.py from django.db import models from django.contrib.auth.models import User class ImageAndUser(models.Model): user = models.ForeignKey("auth.User", verbose_name="imageforegin") result = models.CharField(max_length=64, null=True) def __str__(self): return '{} {}'.format(self.user,self.id) I wrote in views.py def scoreresults(request): d = { 'scoreresults': ImageAndUser.objects.result(), } return render(request, 'registration/accounts/results.html', d) in urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^scoreresults$', views.scoreresults,name='scoreresults'), ] Traceback says 'scoreresults': ImageAndUser.objects.result(), ... ▼ Local vars is wrong. How can I fix this? -
Bitnami Django Stack 500 Internal Server Error
I was trying to install Bitnami Django Stack with PostgreSQL but I encountered a problem while just trying out the Demo page. I have been trying to fix it and read the documentation but it seems that the documentation is outdated. When I open the Demo page, it shows the following error: Here are the errors found in the log: [Sun Feb 19 11:00:21.679338 2017] [ssl:warn] [pid 2172] AH01909: localhost:8443:0 server certificate does NOT include an ID which matches the server name [Sun Feb 19 11:00:21.711930 2017] [ssl:warn] [pid 2173] AH01909: localhost:8443:0 server certificate does NOT include an ID which matches the server name [Sun Feb 19 11:00:21.725126 2017] [mpm_prefork:notice] [pid 2173] AH00163: Apache/2.4.23 (Unix) mod_wsgi/3.5 Python/2.7.12 OpenSSL/1.0.2j configured -- resuming normal operations [Sun Feb 19 11:00:21.725224 2017] [core:notice] [pid 2173] AH00094: Command line: '/Applications/djangostack-1.10.5-0/apache2/bin/httpd.bin -f /Applications/djangostack-1.10.5-0/apache2/conf/httpd.conf' [Sun Feb 19 11:00:24.877912 2017] [mpm_prefork:notice] [pid 2173] AH00169: caught SIGTERM, shutting down [Sun Feb 19 11:00:27.484248 2017] [ssl:warn] [pid 2208] AH01909: localhost:8443:0 server certificate does NOT include an ID which matches the server name [Sun Feb 19 11:00:27.509850 2017] [ssl:warn] [pid 2209] AH01909: localhost:8443:0 server certificate does NOT include an ID which matches the server name [Sun Feb 19 11:00:27.519223 2017] [mpm_prefork:notice] … -
Passing form input data to post request
very new to python/Django and trying to create search box which grabs the data from api and returns the result on html. Just like any other search engine does. :| I have to pass token via header. For starters this is my code. url.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',views.search, name='search'), ] views.py from django.shortcuts import render from django.http import HttpResponse from django import forms def search (request): data = form.getvalue('searchbox') return render(request, "main/search.html",{'message':'Search Companies'}) search.html <div class="container"> <h2 class="text-center">{{message}}</h2> <div class="search"> <form name="search" action="search" method="post"> Search <input type="text" name="searchbox"> <input type="submit" value="submit"> </form> </div> </div> this is my error in console Internal Server Error: / Traceback (most recent call last): File "/home/lucy/work/homebase/venv/HomeBase/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/home/lucy/work/homebase/venv/HomeBase/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/lucy/work/homebase/venv/HomeBase/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/lucy/work/homebase/metaphor/views.py", line 6, in search data = form.getvalue('searchbox') NameError: name 'form' is not defined [19/Feb/2017 02:19:44] "GET / HTTP/1.1" 500 72406 I am not sure how to proceed ahead. -
django rest-farmework nested relationships to use filter
Using django rest-farmework to implement the API,There is a problem has been unable to solve: How to filter the associated tables?, the specific code is as follows: models.py class Category(models.Model): name = models.CharField(max_length=30) amount = models.IntegerField() class Source(models.Model): name = models.CharField(max_length=50) rss_link = models.URLField() amount = models.IntegerField() # ForeignKey category = models.ForeignKey(Category) views.py class CategoryListView(APIView): def get(self, request): category = Category.objects.all() serializers = CategorySerializers(category, many=True) return Response(serializers.data) serializers.py class SourceSerializers(serializers.ModelSerializer): class Meta: model = Source fields = ("id","name","amount") class CategorySerializers(serializers.ModelSerializer): source_set = SourceSerializers(many=True, read_only=True) class Meta: model = Category fields = ("id","name","amount","source") Program running results: [ { "id": 1, "name": "study", "amount": "0", "source": [ { "id": 34, "name": "java", "amount": "0" }, { "id": 35, "name": "python", "amount": "0" }, { "id": 36, "name": "css", "amount": "2" } ] } ] Now I only need to query "source" of the "amount" of 0 data, I tried to write this code: serializers.py class SourceSerializers(serializers.ModelSerializer): class Meta: model = Source fields = ("id","name","amount") class CategorySerializers(serializers.ModelSerializer): #Modified the following code source_set = SourceSerializers(Source.objects.filter(amount=0),many=True, read_only=True) class Meta: model = Category fields = ("id","name","amount","source") But the result is the same, I hope the result is: [ { "id": 1, "name": "study", "amount": "0", "source": … -
'module' object is not iterable
My Django project is returning a TypeError: 'module' object is not iterable. I know this type of question is already being asked in community, but none of previous questions could fixed my issue. perhaps I don't understand something basic, as I'm a novice who freshly learning Python and Django. does anyone can help me to solve this issue? I created a model as following. from django.db import models # Create your models here. class Article(models.Model): content = models.CharField(max_length=200) written_date = models.DateTimeField('date written') def __unicode__(self): return self.content Following is view.py # Create your views here. from blog.models import Article # Article data models from django.shortcuts import render # shortcuts to call template from django.http import HttpResponseRedirect # Redirection Module from django.template import context from django.utils import timezone # time Module # blog.views.index # retrive all content and display in reverse of order of written_date # call the template after sorting. def index(request): all_articles = Article.objects.all().order_by('-written_date') return render({'all_articles' : all_articles, 'message' : 'Write something!'}, 'blog/index.html', context) # blog.views.submit # Receive POST request submitted from user FORM, save the request # redirect user to index.html def submit(request): try: cont = request.POST['content'] except (KeyError): return render({'all_articles' : all_articles, 'message' : 'Failed to read content'}, … -
Shell script to restart django runserver inside the screen
how to restart django runserver using a shell script? i ran the django server inside a screen. this is my shell script restartpython.sh: killall -9 python screen -r sleep 5 exec python manage.py runserver 0.0.0.0:8000 ctrl+a d # how to make this into shell script?? when i execute this script, i enter the screen and the python server is killed. but the script didn't run this line: exec python manage.py runserver 0.0.0.0:8000 Also, how to run ctrl+a d in shell script (to exit from the screen)?. Thank you. -
Ajax Jquery Request of xml data need to run in back end in django
I am trying to download the top stories of the BBC website. and display them on a HTML web page. previously I tried to do this through ajax in javascript.However, I get the error that: "XMLHTTPRequest cannot load my page as no 'Access-Control-Allow-Origin' header is present on the requested resource.cso is therefore not allowed access." I did some more research and found that as I am doing this in Django, I need to request the object from the URL using my views.py file, not ajax. Ive been reserching most of today, with no sucess, so was wondering if someone could help me or forward me to some links which can! My current code is as follows: News.js: $(document).ready(function(){ function an(){ $("#TopNews").append("<ul></ul>"); $.ajax({ type: "GET", url: "http://rss.cnn.com/rss/cnn_topstories.rss", dataType: "xml", success: function upon_success ( xml ) { if(response.status === "success"){ $(xml).find('item').each(function(){ var Titles = $(this).find('title').text(); $("<li></li>").html(Titles).appendTo("#TopNews ul"); }); } else if (response.status === "error"){ alert("The XML File could not be processed correctly."); } } }); }; $("#btn").click(an); }); Html: <!DOCTYPE html> <head> <title>My Cool Savings Calculator</title> <style> h1 { padding-bottom: 0em; margin-bottom: 0em; } table { padding-top: 0em; margin-top: 0em; } </style> </head> <body> <h1>Savings Calculator</h1> {% if error_message %} <b style="color:#FF0000";>{{ … -
Django call class child method in template
I've looked at the docs, but what I am doing doesnt seem to output the any data at all. I am trying to render to the template and use a class method that uses no parameters Here is my model: # video status for a particular user class VideoStatus(models.Model): video = models.ForeignKey(Video, related_name='name') user = models.ForeignKey(User, related_name='status') rating = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)], default=None, null=True, blank=True) completed = models.BooleanField(default=False, blank=True) class Meta: unique_together = ("video", "user") def __str__(self): return 'VideoStatus(video:' + self.video.title + ', user:' + self.user.username + ')' def completed_videos(self): return self.video.title Trying to render the data to the html template: {% for user in users %} {{ user.email }},{{ user.status.completed_videos }} <br> {% endfor %} The data that is outputted: admin@gmail.com, ryan@gmail.com, I am wanting to be able to output the titles for VideoStatus how would I properly go about that? Thanks -
NoReverseMatch at / error in django after url template tag usage
I am having this error after using the template {% url %} tag, NoReverseMatch at /index/ Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] this happened I changed href="index" to href="{% url 'index' %}" my url is url(r'^index/$', views.index, name='index'), I tried to remove $ but still the same error? -
(TypeError: expected string or bytes-like object) when calling function in Django
I'm trying to create a website that takes user text input via a form and returns only the questions from the input. I want to save both the initial user input and the questions to my database each time some input is submitted. I have basically everything taken care of, except I am stuck on this TypeError each time I test the submission of text in the form. Here are the details of the error: TypeError at /input/ expected string or bytes-like object Request Method: POST Request URL: http://127.0.0.1:8000/input/ Django Version: 1.10.5 Exception Type: TypeError Exception Value: expected string or bytes-like object Exception Location: /Users/joshuablew/Projects/HW/env/lib/python3.6/site-packages/nltk/tokenize/punkt.py in _slices_from_text, line 1289 Python Executable: /Users/joshuablew/Projects/HW/env/bin/python Python Version: 3.6.0 Here is the function I am running on the text: import nltk from nltk.tokenize import sent_tokenize from v1 import models from v1.models import TextInput def Question_Init(user_input_obj): Beginning_Question_Prompts = ("Who","Whom","What","Where","When","Why","Which", "Whose","How","Was","Were","Did","Do","Does","Is") Ending_Question_Prompts = ("?",":","...") questions = [] TextInput = models.TextInput text1 = TextInput.user_input textList = sent_tokenize(text1) for sentence in textList: if sentence.startswith(Beginning_Question_Prompts): questions.append(sentence) if sentence.endswith(Ending_Question_Prompts): questions.append(sentence) #Prints questions return questions Here is my view I'm using to save the input to my database and run my function on the input. def text_input(request): form = forms.TextInputForm() if … -
How can I use django forms to assign values to multiple different objects
I am new to django. I am making a teacher utility website that will help keep track of student's grades for different classes and assignments. Currently I have made a page for one class and I am displaying the information in a table, where students are the rows and each assignment is the column. I would like to make an 'edit' page where I can modify the student's grades for each assignment in the same format as the main class page. So that instead of the grades in each 'cell' of the table there will be an input field with a save button at the bottom of the page. And I'm not sure how to accomplish that. How can I make a form assign a value to a specific student/assignment pair? And how can I have multiple of those forms for each student/assignment pair? I tried using (unsuccessfully) using formsets but I wasn't able to make much progress with that. Here are my models class Student(models.Model): name = models.CharField(max_length=40) section = models.ForeignKey(Section, blank=False, on_delete=models.PROTECT) subjects = models.ManyToManyField(Subject) def __str__(self): return self.name class Assignment(models.Model): section = models.ForeignKey(Section, blank=False, on_delete=models.PROTECT) subject = models.ForeignKey(Subject, blank=False, on_delete=models.PROTECT) assign_date = models.DateField('date assigned', primary_key=True) def __str__(self): … -
Django - the effect on page load speed of using include tag inside for loop
The odds are that this question will be banned, because this forum seems to me a site for "why it doesn't work"-type of questions, rather than "is it a good idea to do what I do" ones. And yet, I am very much concerned about preserving DRY-ness in my code. I have a Django template which looks like this: <ol id = 'task_list'> {% for item in qs %} {% include 'list_item.html' with item=item %} {% endfor %} </ol> list_item.html: <li> {{item}} </li> The advantage (at least, for me) of this code: it positively affects DRYness when I have a ajax code which posts a request for creating new items of the list and renders them on the client side subsequently: JS: $.post('my_view_url', function(response) $('container').append(response); Django view: def my_view(response) #... return render_to_response('list_item.html',....) This way, list_item.html helps me use the same HTML code for both initial rendering of existing elements and client-side rendering of newly created items. The disadvantage is that {% include %} is known to be rather slow. The question: Is this code pattern not a performance killer in case of paginated rendering of large arrays of data ? -
AttributeError at / 'tuple' object has no attribute 'get' in Django
I am having a AttributeError at / 'tuple' object has no attribute 'get', below is the trace path what could be wrong in Django? AttributeError at / 'tuple' object has no attribute 'get' Request Method: GET Request URL: http://www.example.com/ Django Version: 1.10.5 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'get' Exception Location: /home/admin/env/lib/python3.5/site-packages /django/middleware/clickjacking.py in process_response, line 32 Python Executable: /home/admin/env/bin/python Python Version: 3.5.2 -
serializing a dictionary with datetime.time as value to json in django
as the title explains I'm trying to serialize a dict to json using pythons json module but I can't figure out where is my mistake: from what i gather you can use json.dump like this : json.dumps({'foo':3}) (I ran this code and got results) now when I run this code : json.dump({'friday': datetime.time(0, 0)}) i get this error : TypeError: dump() missing 1 required positional argument: 'fp' this part confuses me. apparently fp is the file you want your json to be written into and you have to pass that argument, if is that so, why wasn't that the case when i was serializing another dictionary and what do i do if i don't want to write the json into a file. this is probably a simple mistake on my side but I did days of research and i came up with nothing so i would really appreciate any kind of help. thanks in advance -
User dependent field as many to many relationship in Django Rest Framework
In my application I have some products, and a logged in user should be able to mark these products as favorites. I modeled them as a many to many relationship in my models.py, like this: class Product(models.Model): product_name = models.CharField(max_length=200) # ... def __unicode__(self): return self.product_name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) favorites = models.ManyToManyField(Product) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.get_or_create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() What I'd like to achieve now is that on a product detail view the user can see if the product is already a favorite of his, and should be able to check a box to make it his favorite. On the model level this is a many to many relationship, but on the view it is more of a boolean relationship (favorite yes/no for current user). I already managed to have the favorite status displayed in the detail view, with a SerializerMethodField class ProductSerializer(serializers.ModelSerializer): # ... favorite = serializers.SerializerMethodField() def get_favorite(self, obj): try: self.context['request'].user.profile.favorites.get(pk=obj.pk) return True except Product.DoesNotExist: return False What I am struggling with currently is adding a favorite to the current user's list of favorites with this setup, as this SerializerMethodField is read-only and, because of …