Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework nested serializer wrong update validation
I'm trying to update a related model with nested serializers, but getting a weird error in the process. These are my models: class Individual(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField(max_length=100, blank=True) class EntityMember(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(max_length=255, blank=True) and the serializers: class IndividualSerializer(serializers.ModelSerializer): class Meta: model = Individual fields = ('id', 'first_name',) class EntityMemberSerializer(serializers.ModelSerializer): individual = IndividualSerializer() class Meta: model = EntityMember fields = ('id', 'email', 'individual') def update(self, instance, validated_data): individual_data = validated_data.pop('individual', None) super().update(instance, validated_data) return instance And a test I'm running: def test_update_contact(self): data = { 'email': 'misteryon@friends.com', 'individual': { 'first_name': 'Kenny' } } response = self.client.patch(self.url, data=data, format='json') print(response.data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['email'], 'misteryon@friends.com') self.assertEqual(response.data['individual']['first_name'], 'Kenny') The request is responding with a 400 BAD REQUEST error. The print in the test shows: {'non_field_errors': [ErrorDetail(string="'OrderedDict([('first_name', 'Kenny')])' is not a valid UUID.", code='invalid')]} If I don't send the individual data, the request goes fine and the EntityMember data is updated succesfully (except for the Individual model, of course). It seems to me that the serializer is expecting an UUID for that individual field, but according to the docs http://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations what I'm doing is just fine. I guess I'm missing something but I can't … -
Nginx is not serving django projects that is running on uwsgi
I have 2 django projects that are configured to be served on sockets. They are at the same server. Django project names are proj1 and proj2. So i gave them 2 different names proj1.cr.tm and proj2.cr.tm on /etc/hosts file and both of them are pointing to same local 127.0.0.1 address. So when i ping proj1.cr.tm it pings 127.0.0.1 , when i ping proj2.cr.tm it pings 127.0.0.1 also. So the thing i want is serving 2 projects on these two different domain names on same server ip on port 80. The differentiation with names and projects will be made by nginx. I also prepared 2 nginx configurations proj1.conf and proj2.conf under /etc/nginx/conf.d directory and added proj1.cr.tm and proj2.cr.tm as servers in these configurations. I also included them in main nginx.conf file under /etc/nginx/nginx.conf file. I also prepared 2 ini files for uwsgi and run uwsgi with emperor. When i run uwsgi and nginx i can see that socket files are created. And i can also see nginx is working on http:/127.0.0.1 with default nginx page. I also see that uwsgi processes with project modules are working in linux processes behind. But when i try http://proj1.cr.tm and http://proj2.cr.tm addresses i still cannot … -
add functionality in addition to choose and filter - FilteredSelectMultiple
I prefer using FilteredSelectMultiple django widget for ManyToManyField but it only provides filter and choose objects functionality like below - from django.contrib.admin.widgets import FilteredSelectMultiple from django.db.models import ManyToManyField I am looking for add new object functionality maybe showing up as a + button like below. -
Scheduling in Django
I need to implement a scheduled task in our Django app. DBader's schedule seems to be a good candidate for the job, however when run it as part of Django project, it doesn't seem have any effect. Specifically, this works fine as an independent program: import schedule import time import logging log = logging.getLogger(__name__) def handleAnnotationsWithoutRequests(settings): ''' From settings passed in, grab job-ids list For each job-id in that list, perform annotation group/set logic [for details, refer to handleAnnotationsWithRequests(requests, username) sans requests, those are obtained from db based on job-id ] ''' print('Received settings: {}'.format(str(settings))) def job(): print("I'm working...") #schedule.every(3).seconds.do(job) #schedule.every(2).seconds.do(handleAnnotationsWithoutRequests, settings={'a': 'b'}) invoc_time = "10:33" schedule.every().day.at(invoc_time).do(handleAnnotationsWithoutRequests, settings={'a': 'b'}) while True: schedule.run_pending() time.sleep(1) But this doesn't result in an invocation when run in Django context. def handleAnnotationsWithoutRequests(settings): ''' From settings passed in, grab job-ids list For each job-id in that list, perform annotation group/set logic [for details, refer to handleAnnotationsWithRequests(requests, username) sans requests, those are obtained from db based on job-id ] ''' log.info('Received settings: {}'.format(str(settings))) def doSchedule(settings): ''' with scheduler library Based on time specified in settings, invoke .handleAnnotationsWithoutRequests(settings) ''' #settings will need to be reconstituted from the DB first #settings = {} invocationTime = settings['running_at'] import re invocationTime … -
WAV file from user microphone vs. WAV file from file: Some difference is causing bugs, but what are these different?
Right now I have two methods of sending a WAV file to the server. A user can directly upload said file, or make a recording on their microphone. Once the files are sent, they are processed in nigh the same way. The file is sent to S3, and can later be played by clicking on some link (which plays the file via audio = new Audio('https://S3.url'); audio.play() When dealing with a file from the microphone: audio.play() seems to work. Everything in the audio object is identical (except for the URL itself), but the sound won't actually play through the speakers. On the other hand, for an uploaded file, the sound plays through the speakers. When I visit the URLs directly—both of them open up the sound-player (in Chrome) or prompt a download for a WAV file (in Firefox). The sound-player appropriately plays both sounds, and the downloaded WAV files each contain their respective sound, which other programs can play If I actually download the file with sound from the user's microphone instead of sending it directly to the server, then manually upload the WAV file, everything works as it should (as it would with any other uploaded WAV file). In … -
ImportError: No module named nltk.classify
I'm using python 2.7, Django 1.11.14, I dockerized my app and I have a problem importing nltk.classify while executing docker-compose up I get: .... web_1 | File "/code/personal/classifier.py", line 6, in <module> web_1 | from nltk.classify import ClassifierI web_1 | ImportError: No module named nltk.classify I added some lines to requirements.txt and still it dosent work requirements.txt: Django==1.11.14 psycopg2 nltk nltk.classify Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ -
Django Rest Framework - passing Model data through a function, then posting output in a separate field in the same model
(Django 2.0, Python 3.6, Django Rest Framework 3.8) I'm trying to fill the calendarydays field in the model below: Model class Bookings(models.Model): booked_trainer = models.ForeignKey(TrainerProfile, on_delete=models.CASCADE) booked_client = models.ForeignKey(ClientProfile, on_delete=models.CASCADE) trainer_availability_only = models.ForeignKey(Availability, on_delete=models.CASCADE) calendarydays = models.CharField(max_length=300, blank=True, null=True) PENDING = 'PENDING' CONFIRMED = 'CONFIRMED' CANCELED = 'CANCELED' STATUS_CHOICES = ( (PENDING, 'Pending'), (CONFIRMED, 'Confirmed'), (CANCELED, 'Canceled') ) booked_status = models.CharField( max_length = 9, choices = STATUS_CHOICES, default = 'Pending' ) def __str__(self): return str(self.trainer_availability_only) Now, I have a function that takes values from trainer_availability_only and converts those values to a list of datetime strings, the returned output would look something like this: {'calendarydays': ['2018-07-23 01:00:00', '2018-07-23 02:00:00', '2018-07-23 03:00:00', '2018-07-30 01:00:00', '2018-07-30 02:00:00', '2018-07-30 03:00:00', '2018-08-06 01:00:00', '2018-08-06 02:00:00', '2018-08-06 03:00:00', '2018-08-13 01:00:00', '2018-08-13 02:00:00', '2018-08-13 03:00:00', '2018-08-20 01:00:00', '2018-08-20 02:00:00', '2018-08-20 03:00:00']} Problem How can I fill the calendarydays field with the function output for a user to select from a dropdown, and where should I implement this logic (in my view or the serializer)? My main point of confusion is that, because my function depends on data from trainer_availability_only, I don't want to create a separate model/table for this information (as that would seem too repetitive). I … -
Can't import models in tasks.py with Celery + Django
I want to create a background task to update a record on a specific date. I'm using Django and Celery with RabbitMQ. I've managed to get the task called when the model is saved with this dummy task function: tasks.py from __future__ import absolute_import from celery import Celery from celery.utils.log import get_task_logger logger = get_task_logger(__name__) app = Celery('tasks', broker='amqp://localhost//') @app.task(name='news.tasks.update_news_status') def update_news_status(news_id): # (I pass the news id and return it, nothing complicated about it) return news_id this task is called from my save() method in my models.py from django.db import models from celery import current_app class News(models.model): (...) def save(self, *args, **kwargs): current_app.send_task('news.tasks.update_news_status', args=(self.id,)) super(News, self).save(*args, **kwargs) Thing is I want to import my News model in tasks.py but if I try to like this: from .models import News I get this error : django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. This is how mi celery.py looks like from __future__ import absolute_import, unicode_literals from celery import Celery import os # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('myapp') # Using a string here means the worker … -
Serving an image on django web app
I'm trying to serve an image on my Django web app, but it seems to be giving me a broken image link. I put the picture I want to serve in the same folder as the .html, hoping that would work although it didnt. Here is the hello.html <html> <body> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <input type="submit" value="Upload"> <p>Hello</p> <p><img src="C:\Users\Public\Documents\PycharmProjects\filecomparison\templates\Example.jpg" alt="HTML5 Icon" style="width:128px;height:128px;"></p> </form> </body> </html> This is what I see on the website I'm new to django and I've been reading guides and watch youtube videos but they dont seem to help me to do what i actually i want, any help is appreciated -
Django: Reducing database queries
I have the following two queries in my Django view: current_events = user.ambassador_profile.first().events.all().filter(end_date__gt=now) past_events = user.ambassador_profile.first().events.all().filter(end_date__lt=now) I am not sure, but is there a better way to combine these. Currently, I am doing two queries in my database and I feel like that's wrong. -
partial render django form
I've linked a user_profile to my Django app so I can save some extra user information, here is the model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) code = models.TextField(max_length=9, blank=True) type = models.TextField(max_length=15, blank=True) state = models.TextField(max_length=15, blank=True) and this is my form class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('code', 'type', 'state') labels = { 'code':'Code', 'type':'Type of user', 'state':'State of the account', } widgets = { 'code' : forms.TextInput(attrs={'class':'form-control'}), 'type': forms.Select(choices=TYPES_USERS, attrs={'class':'form-control'}), 'state' : forms.Select(choices=STATEOF_ACCOUNT ,attrs={'class':'form-control'}), } Where type of user can take 3 values: student, professor, administrator and state of the account can take 3 values: active, revision, blocked . code is a 8 digit number when I go to the edit profile url I would like to validate that the fields 'type' and 'state' can only be seen and modified by the super-user, and if the user is a regular user he can only see and modify the field 'code' I have tried with <form method="post"> {%csrf_token%} {% if 'user.is_superuser' in perms %} <div class="form-group col-lg-2 col-sm-6 col-xs-2 "> <label class="textS" style="margin-bottom:-6px;" for="{{form.tipo.name}}">{{form.type.label}}:</label> <div class="form-control-sm" >{{form.type}}</div> </div> <div class="form-group col-lg-2 col-sm-6 col-xs-2 "> <label class="textS" style="margin-bottom:-6px;" for="{{form.estado.name}}">{{form.state.label}}:</label> <div class="form-control-sm" >{{form.state}}</div> </div> {% else … -
Django - TypeError - NoneType' object is not iterable - Dont understand why an Object is being recognized as None
first question here as I am relatively new to programming, and I have been breaking my head for Days over an error I am getting, which is the following: The purpose is creating a user to user "messaging" using Django Channels as per an online tutorial which I want to implement to my django project. I have narrowed down the error as a problem with the Auth model I had in place vs how I am querying it, a URL / path syntax Error or a typo? I am lost after so much research. When I type in localhost:8000/messages/jarturoch in the browser I get the following error: TypeError at /messages/jarturoch/ 'NoneType' object is not iterable Request Method: GET Request URL: http://localhost:8000/messages/jarturoch/ Django Version: 2.0.2 Exception Type: TypeError Exception Value: 'NoneType' object is not iterable Exception Location: /home/jarturoch/Desktop/pythondev/django_projects/quekieres-main/qkchat/views.py in get_object, line 26 Python Executable: /home/jarturoch/Desktop/pythondev/django_projects/myvenv/bin/python Python Version: 3.6.3 Python Path: ['/home/jarturoch/Desktop/pythondev/django_projects/quekieres-main', '/home/jarturoch/Desktop/pythondev/django_projects/myvenv/lib/python36.zip', '/home/jarturoch/Desktop/pythondev/django_projects/myvenv/lib/python3.6', '/home/jarturoch/Desktop/pythondev/django_projects/myvenv/lib/python3.6/lib-dynload', '/home/jarturoch/anaconda3/lib/python3.6', '/home/jarturoch/Desktop/pythondev/django_projects/myvenv/lib/python3.6/site-packages'] The console gives me this 500 Internal Server Error before the traceback: 2018/07/19 14:08:20] HTTP GET /messages/jarturoch/ 500 [0.16, 127.0.0.1:53212] Internal Server Error: /messages/jarturoch/ jarturoch in this case is the main Logged In User. If I type: localhost:8000/messages/jones jones being another registered user. I get … -
Modelforms : not able to view the editable content while updating
Possibly a newbie question, so please bear with me. I have a Django form that edits a certain instance of a Model. I am using Modelforms. I am able to edit the instance but I am not able to see the content of instance that I want to edit. I am learning django right now using video tutorials and in the tutorial adding instance=instance to ModelForm instance and then using form.as_p the values were populated in the input box. In my case when I got to edit url my input fields are blank. However, whatever I write in new blank form gets updated to that object. What could have been wrong here? I am stuck at this point for 4 days so this question is a very desperate one :) My form class: from django import forms from .models import Entry class EntryForm(forms.ModelForm): class Meta: model = Entry fields = ['name','type', 'date', 'description'] My Model: from django.db import models class Entry(models.Model): name = models.CharField(max_length=200) type = models.CharField(max_length= 200) date = models.DateTimeField() description = models.TextField() My views look like this : def update(request,pk): instance = get_object_or_404(Entry,pk=pk) if request.method == 'POST': form = EntryForm(request.POST or None,instance=instance ) if form.is_valid(): instance =form.save(commit=False) instance.save() … -
X-FRAME OPTIONS in Facebook Messenger
I am creating a facebook chatbot and using Django for the backend. The documentation states this regarding webviews on the web. Which is the best way to achieve this in Django? -
Django get_queryset returns 500 instead of 404
Here is my view: class SampleViewSet(viewsets.ModelViewSet): serializer_class = SampleSerializer queryset = Sample.objects.all() def get_queryset(self): queryset = self.queryset test_code = self.request.query_params.get('test_code', None) if test_code is not None: queryset = queryset.filter(test__test_code=test_code) return queryset Here is my Model: class Sampe(models.Model): test = models.OneToOneField(Test, null=True, blank=True, on_delete=models.CASCADE) # few more fields- not so important Here is my serializer: class SampleSerializer(serializers.ModelSerializer): test_code = serializers.CharField(source='test.test_code') class Meta: model = Sample fields = '__all__' This works when I hit /api/sample?test_code="existing_param" So when I do /api/sample?test_code="Not_Existing_param", I was expecting it should throw me 404 instead, it throws 500 Test matching query does not exist. Really appreciate any help. Thank you -
Django REST Framework serializer field is required even when required=False
I have a model like this class FalseUserAnswer(BaseModel): question = models.ForeignKey(TrueOrFalseQuestion, on_delete=models.CASCADE) user_question = models.ForeignKey(TrueOrFalseUserQuestion, on_delete=models.CASCADE, null=True) answer = models.ForeignKey(FalseAnswer, on_delete=models.CASCADE) the problem is one old version of my frontend does not send user_question while the newer one does. So, I want to accept an object that does not have the field at all (it will not be null, or None or nothing, just won't be in the request). I tried to do something like this in my serializer class FalseUserAnswerSerializer(serializers.ModelSerializer): # Allows null for version < 1.18 of the app. Might be removed in the future. user_question = serializers.PrimaryKeyRelatedField(queryset=TrueOrFalseUserQuestion.objects.all(), required=False, allow_null=True) class Meta: model = FalseUserAnswer fields = ['id', 'creator', 'question', 'user_question', 'answer', 'type'] But I still get "error": { "user_question": [ "This field is required." ] } Django REST framework version is 3.8.2 Any help is appreciated, thanks for your time. -
Django template date filter not displaying
I have a bit of a problem with displaying a datetime field in my template. models.py: date_modified = models.DateTimeField(auto_now = True) date_created = models.DateTimeField(auto_now_add = True) In my template: {% for key, value in record.get_fields.items %} {% if key == field_name %} {% if value != "None" %} <div class="li-item"> {% if "Date" in key or "date" in key and key not in do_not_display_fields %} {{ value|date:'Y-m-d H:i' }} When I have the date filter, the dates are not displayed in the template though. If I remove the date filter, the date and time are displayed in this format: 2018-07-10T16:03:56.049408+00:00 What am I doing incorrectly? -
Save() prohibited to prevent data loss due to unsaved related object 'visitor'
GAME CLASS class Game(models.Model): class Meta: ordering = ['start_time'] league = models.CharField( "League", max_length=20, choices=lookups.LEAGUES ) stage = models.ForeignKey(Stage, related_name="game_stage", null=True, blank=True) start_time = models.DateField() visitor = models.ForeignKey(Team, related_name="opposing_team") visitor_points = models.IntegerField("Visitor Points") home = models.ForeignKey(Team, related_name="host_team") home_points = models.IntegerField("Home Points") overtime = models.BooleanField("Overtime") foreign_id = models.CharField("Foreign ID", max_length=100, null=True, blank=True) def __str__(self): return f'{self.start_time} - {self.visitor.name_short} at {self.home.name_short}' TEAM CLASS class Team(models.Model): class Meta: unique_together = ('name_short', 'league') ordering = ['name'] name = models.CharField("Team Nickname", max_length=100) name_short = models.CharField("Abbreviation", max_length=5) image = models.ImageField("Logo", blank=True, null=True, upload_to='images/teams/') area = models.CharField("City or Region represented", max_length=150, blank=True, null=True) league = models.CharField( "Team League", max_length=20, choices=lookups.LEAGUES ) foreign_id = models.CharField("Foreign ID", max_length=40, null=True, blank=True) def __str__(self): return f'[{self.league}] {self.name} ({self.name_short})' CREATOR CODE for g in _parse_games(league_id, stage_id): try: Game.objects.get(foreign_id=g['Foreign ID']) except: print("creating new game...") game = Game( #Game.objects.create( league = g['League'], start_time = g['start_time'], visitor = g['opposing_team'], visitor_points = g['Visitor Points'], home = g['host_team'], home_points = g['Home Points'], overtime = False, foreign_id = g['Foreign ID'] ) game.save() #game = Game.objects.create( #league = g['League'], #start_time = g['start_time'], #visitor = g['opposing_team'], #visitor_points = g['Visitor Points'], #home = g['host_team'], #home_points = g['Home Points'], #overtime = False, #foreign_id = g['Foreign ID'] #) print ("created!") I keep receiving … -
Django Unable to load the SpatiaLite library extension mod_spatialite on Ubuntu
I'm trying to run sqlite3 with spatialite but when i run $ python manage.py makemigrations im getting the error: django.core.exceptions.ImproperlyConfigured: Unable to load the SpatiaLite library extension "mod_spatialite" because: mod_spatialite.so: cannot open shared object file: No such file or directory I'm using Ubuntu 16.04 Xenial Django 1.11 Python 3.5.2 and have installed the packages: spatialite-bin spatialite-gui spatialite-gui-dbg python-pyspatialite I also tried adding SPATIALITE_LIBRARY_PATH = 'mod_spatialite' but it still didnt work. my complete traceback: Traceback (most recent call last): File "/home/marcelo/.virtualenvs/smart-eye-agora-vai/lib/python3.5/site-packages/django/contrib/gis/db/backends/spatialite/base.py", line 60, in get_new_connection cur.execute("SELECT load_extension(%s)", (self.spatialite_lib,)) File "/home/marcelo/.virtualenvs/smart-eye-agora-vai/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: mod_spatialite.so: cannot open shared object file: No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/marcelo/.virtualenvs/smart-eye-agora-vai/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/marcelo/.virtualenvs/smart-eye-agora-vai/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/marcelo/.virtualenvs/smart-eye-agora-vai/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/marcelo/.virtualenvs/smart-eye-agora-vai/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/marcelo/.virtualenvs/smart-eye-agora-vai/lib/python3.5/site-packages/django/core/management/commands/makemigrations.py", line 110, in handle loader.check_consistent_history(connection) File "/home/marcelo/.virtualenvs/smart-eye-agora-vai/lib/python3.5/site-packages/django/db/migrations/loader.py", line 282, in check_consistent_history applied = recorder.applied_migrations() File "/home/marcelo/.virtualenvs/smart-eye-agora-vai/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/home/marcelo/.virtualenvs/smart-eye-agora-vai/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/home/marcelo/.virtualenvs/smart-eye-agora-vai/lib/python3.5/site-packages/django/db/backends/base/base.py", line 254, in … -
Authorization issues with django-wiki
I'm using django-wiki as a part of a larger user portal which is authenticated via Duo. I've already made the hooks for Django-wiki to redirect to the portal login page for authentication instead of using the inbuilt login mechanism. My question is two fold: I only want a subset of authenticated portal users to be able to view the wiki. Everyone else should get a "You are not authorized to view this page" message when they try to access the wiki. I want only a subset of authorized users of the wiki to have write privileges, everyone else should only have read privs. How do I accomplish this? Thanks for your help! -
Make arbitrary url as homepage
I have such a urls.py configuration in project repository "forum" # Project url urlpatterns = [ url(r'^admin/', admin.site.urls), url(r"^$", views.index, name="index"), url(r'^article/', include('article.urls',namespace='article')), ] and with article/urls.py as #Article app's url config urlpatterns = [ # show the article list url(r"^list/(?P<block_id>\d+)$", views.article_list, name="article_list"), I attempt to take "^article/list/1$" as home page instead of "views.index". How to make it redirect to "^article/list/1$" when I issue request "127.0.0.1:8000"? -
Filter objects in Django 2 if all objects in subquery have specific value
I have the follow models: class FactoryDevice(models.Model) ... class InspectionRegister(models.Model) factory_device = models.ForeignKey(FactoryDevice) inspection_date = models.DateTimeField() status = choices.DEVICE_STATUS This is the scenario: In a factory, every week devices are inspected. I want filter all FactoryDevice that have last five InspectionRegister with status equals to choices.REPPROVED -
When to use force_update in Django's save()?
Django official docs state that: In some rare circumstances, it’s necessary to be able to force the save() method to perform an SQL INSERT and not fall back to doing an UPDATE. Or vice-versa: update, if possible, but not insert a new row. In these cases you can pass the force_insert=True or force_update=True parameters to the save() method. Obviously, passing both parameters is an error: you cannot both insert and update at the same time! What are these rare circumstances? Basically, when should one use force_update=True? -
How to call view function via button from template in Django?
I searched some of the related questions and I couldn't figure out how to do it. That is why I am posting a new question here. I have a base html file and there is a button which should run a function from view.py file. Here is the button code; <form action="#" method="get"> <input type="submit" class="btn" value="Click" name="mybtn"> </form> And here is my function from view.py file; def create_new_product(request): if(request.GET.get('mybtn')): '''Execute the code here''' return render('products') Normally I have a IndexView class in view.py file which lists all the current products and what I expect from the above function is that it will generate new products and new products will also be listed in 'products' page. The above function is not inside the IndexView class by the way. -
Restframework APi response hide
I have built an application using python django rest framework and Vue js. The rest framework link is something similar like this 198.123.1.1:8001/test i am using this link to get records in Vuejs. when i call this link generally 198.123.1.1:8001/test GET /test/ HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "test_id": 11, "test_n_key": "as-all-1", } i am getting the below response now i want to hide this response to outside world and what will be the better way to do it.