Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django adding data into model from nested json returning TypeError: 'NoneType' object is not subscriptable
I am using a third-party API to get data and add it into my database via objects.update_or_create() method. This data has many records and some of the fields in the response only exists for certain records. Below the a snippet of the JSON that is returned from the API. However this data is only present for some of the records in the JSON response. When I try to add this data into my model, I am getting the following error: 'f_name': i.get('card_faces')[0].get('name'), TypeError: 'NoneType' object is not subscriptable I am trying to have it so that if the card_faces field exists, True is added to the card_face column in the database, and then the card_faces name to the database. If card_faces doesn't exist, then False is added to the card_face column in the database, and subsequent fields are null. JSON: { "data": [ "name": "Emeria's Call // Emeria, Shattered Skyclave", "card_faces": [ { "object": "card_face", "name": "Emeria's Call" }, { "object": "card_face", "name": "Emeria, Shattered Skyclave" } ], ] } views.py: for i in card_data: Card.objects.update_or_create( id=i.get('id'), defaults={ 'name': i.get('name'), 'card_faces': i.get('card_faces'), 'f_name': i.get('card_faces')[0].get('name'), 'b_name': i.get('card_faces')[1].get('name'), } ) -
How to give the json data in post api request in django rest framework
I am new to the Django rest framework, please guide me where I made a mistake, I want to make the API that takes two arguments cat name (which is char field) cat fields (which is JSON field) I want to put dynamic JSON fields, like it upon the client that they will add the 4 fields data with key pairs in JSON or any number of fields, I hope so you all guys would understand my query Please help me, it will really appreciate Here is my Views.py @api_view(['POST']) @parser_classes([JSONParser]) def add_cateogry_with_fields(request, format=None): if request.method == "POST": insert_Serializers = AddCategoryWithFieldsSerializer(data=request.data) if insert_Serializers.is_valid(): insert_Serializers.save() return Response(insert_Serializers.data, status=status.HTTP_201_CREATED) else: return Response(insert_Serializers.data, status=status.HTTP_400_BAD_REQUEST) and here is the serializer class serializer.py class AddCategoryWithFieldsSerializer(ModelSerializer): category_name = serializers.CharField(max_length=34) category_fields = serializers.JSONField() class Meta: model = CategoryModel fields = ('category_name', 'category_fields') the Model.py class is class CategoryModel(models.Model): category_id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=255) category_fields = models.JSONField() parent_category = models.ForeignKey('self', on_delete=models.CASCADE, null=True) class Meta: db_table = 'category' enter image description here -
Pass id user to view function
I try pass id by template to view but I have MultiValueDictKeyError at /accounts/profile/1 <a class="nav-link" href="{% url 'accounts:profile' request.user.id %}">{{request.user}}</a> path('accounts/profile/<int:id>', views.profile, name="profile"), def profile(request, id): user = User.objects.get(id=int(request.POST[id])) return user -
Need 2 values to unpack in for loop; got 4
I'm new to Django, and trying to pass api results (dictionaries within a list) to a template using context. I have tried doing this {% if apiList != "Error..." %} {% for i in apiList %} {% for key, value in i %} {{ key }} {{ value }}<br> {% endfor %} {% endfor %} {% endif %} but I get the error Need 2 values to unpack in for loop; got 4. When I do the same code but take out the value, so it just searches for the keys, it works fine and prints out all the keys on a new line. I've also tried the following code: {% for key, value in apiList.items %} {{ key }} : {{ value }} {% endfor %} but this does not seem to work either, it does not give an error, but nothing shows on the screen. Any idea how to solve this problem? Here is my code in the views.py try: apiList = json.loads(api_request.content) except Exception as e: apiList = "Error..." return render(request, 'financials.html', {'apiList': apiList}) else: return render(request, 'financials.html', {}) Thanks! -
Django log to file by date
I am trying to create log files for Django application by using logging.handlers.TimedRotatingFileHandler class. but i am getting error. In setting.py i am adding this LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'verbose': { 'format': '%(levelname)s|%(asctime)s|%(module)s|%(process)d|%(thread)d|%(message)s', 'datefmt' : "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'default': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': os.path.join(path, 'django.log'), 'formatter': 'verbose', 'when': 'midnight', 'interval': 1, 'backupCount': 365, }, }, 'loggers': { 'django': { 'handlers': ['default'], 'level': 'DEBUG', 'propagate': True, }, }, } but I am getting following errors --- Logging error --- Traceback (most recent call last): File "/opt/rh/rh-python36/root/usr/lib64/python3.6/logging/handlers.py", line 72, in emit self.doRollover() File "/opt/rh/rh-python36/root/usr/lib64/python3.6/logging/handlers.py", line 397, in doRollover if self.backupCount > 0: TypeError: '>' not supported between instances of 'str' and 'int' Call stack: File "/home/mohsin/demo/bin/gunicorn", line 8, in sys.exit(run()) File "/home/mohsin/demo/lib64/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 58, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() File "/home/mohsin/demo/lib64/python3.6/site-packages/gunicorn/app/base.py", line 228, in run super().run() -
i have proplem with pip resolver 2020
i am trying puplish my django project on Cpanel i had used pip install django==2.1 --use-feature=2020-resolver for install all my package but i got following error this error han't appear on my PC Applying authtoken.0001_initial... OK Applying authtoken.0002_auto_20160226_1747...Traceback (most recent call last): File "/home/aeraeg/virtualenv/python/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.SyntaxError: syntax error at or near "WITH ORDINALITY" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... ^ ....... line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/aeraeg/virtualenv/python/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/aeraeg/virtualenv/python/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/aeraeg/virtualenv/python/3.7/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/aeraeg/virtualenv/python/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: syntax error at or near "WITH ORDINALITY" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... ^ -
Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain". Strict MIME type checking is enforced for module
I followed the this video while installing the django debug toolbar as well as the docs. However, I just cannot get it to work. The mime type error keeps popping up in the console tab of the dev tools. settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'this is secret' DEBUG = True if DEBUG: import mimetypes mimetypes.add_type("application/javascript", ".js", True) INTERNAL_IPS = [ '127.0.0.1', ] ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', ] MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'demo.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'demo.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')] VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(VENV_PATH, 'static_root') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(VENV_PATH, 'mdeia') # … -
Understanding Model Permissions in Django 3.1
I have some troubles understanding how Django 3.1 checks permissions, especially how model permissions versus default permissions are handled. I have the following model: from django.db import models class MyModel(models.Model): class Meta: permissions = [("finalize", "Can finalize"),] is_final = models.BooleanField(default = False) which defines a new finalize permission for this model. With the model along we have a model admin: from django.contrib import admin from django.contrib.auth import get_permission_codename from .models import * class MyModelAdmin(admin.ModelAdmin): actions = ['set_final', 'remove_final'] def set_final(self, request, queryset): queryset.update(is_final=True) set_final.allowed_permissions = ('finalize',) def remove_final(self, request, queryset): queryset.update(is_final=False) remove_final.allowed_permissions = ('finalize',) # Permissions def has_change_permission(self, request, obj = None): if obj and obj.is_final: return False codename = get_permission_codename('change', self.opts) print("has_perm(change) : %s.%s : %s" % (self.opts.app_label, 'change', request.user.has_perm('%s.%s' % (self.opts.app_label, 'change')))) print("has_perm(codename): %s.%s : %s" % (self.opts.app_label, codename, request.user.has_perm('%s.%s' % (self.opts.app_label, codename)))) return request.user.has_perm('%s.%s' % (self.opts.app_label, codename)) def has_finalize_permission(self, request, obj = None): codename = get_permission_codename('finalize', self.opts) print("has_perm(finalize): %s.%s : %s" % (self.opts.app_label, 'finalize', request.user.has_perm('%s.%s' % (self.opts.app_label, 'finalize')))) print("has_perm(codename): %s.%s : %s" % (self.opts.app_label, codename, request.user.has_perm('%s.%s' % (self.opts.app_label, codename)))) return request.user.has_perm('%s.%s' % (self.opts.app_label, 'finalize')) admin.site.register(MyModel, MyModelAdmin) which defines two actions: setting and removing the is_final flag from objects. Along with it, the has_change_permission is redefined because the … -
Django Choices Object Not passing id to URL
I'm using a model with a choices field that is being displayed by a form. I want to create a delete function in my views.py but can't get it to work. I suspect it's because my model object is not passing an id, or my url just isn't picking the object's id for whatever reason. Here's my model. class Player(models.Model): PLAYER_ROLE_CHOICES = ( (1, 'Quarterback'), (2, 'Runningback'), (4, 'Widereceiver'), (5, 'Tightend'), (6, 'Kicker'), ) role = models.PositiveSmallIntegerField(choices=PLAYER_ROLE_CHOICES) Here's the delete function I'm trying to make in views.py def delete_player(request, id): player = Player.objects.get(id=id) player.delete() return redirect('show') and my url path('delete_player/<int:id>', views.delete_player, name="delete_player") I know that I obviously need an id to be passed to both the url and delete function in views.py, but I don't know how to get the id from my model. I'd appreciate any help/another set of eyes on the problem. Thanks in advance. -
I want to show a specific customers balance in a panel
I want to show a specific customers balance in a panel for that I want to fetch the specific customers balance and want to show it in a page or somewhere else.Like this example: user 1 has 100$ and user 2 has 200$ so when user 1 will login the page will show 100$ and when user 2 login he will be shown 200$.But I am confused here to complete this task.How can I do this ? I have a coin var which is working as a balance. Here is my Model for Customer : class Customer(models.Model): phone_number = models.CharField(max_length=100, default=1) email = models.EmailField( default=1) password = models.CharField(max_length=100) coin = models.FloatField(null=True, blank=True) def __str__(self): return self.phone_number def register(self): self.save() def get_customer(phone_number): try: return Customer.objects.get(phone_number=phone_number) except: return False -
Django-import-export export also related field of a model
In my project i have a model like this: models.py class e_cart(models.Model): e_uid = models.ForeignKey(User, on_delete=models.CASCADE, ) e_prodid = models.ForeignKey(p_prodotti, on_delete=models.CASCADE, verbose_name="Product") e_qta = models.IntegerField(default=0, verbose_name="Quantita") e_datain = models.DateTimeField(auto_now=True, verbose_name="Insert Data") .... I use django-import-export for export my data in admin panel and in admin.py i do: from import_export.admin import ImportExportModelAdmin class OrderAdmin(ImportExportModelAdmin): search_fields = ('onum',) list_display = ('onum', 'date', 'paid', 'onotes', 'totord', 'obank') ordering = ('-date', 'onum') Now for example the e_uid field is exported as just an id (1,2 ecc) bu i would export the select_related() filds for example e_uid.firstname, e_uid.lastname ecc How can i modify my code for export also related field of my model? so many thanks in advance -
Django-React Axios request breaks token
Everytime I do an axios request in the ComponentDidMount() for example: axiosInstance.get('/user/profile', { headers:{ "Authorization": "JWT " + localstorage.getItem('access_token') } }).then(res => { return res; }).catch(err => { console.log(err) }) OR THIS axiosInstance.get('/user/profile').then(res => { axiosInstance.defaults.headers["Authorization"] = "JWT " + localstorage.getItem('access_token'); return res; }).catch(err => { console.log(err) }) I am running a Django-React project with postgresql as my DB. I followed the guide by Toruitas on Hackernoon on how to use simple-JWT to issue my access_token and refresh_token. Everytime the axios request runs, my refresh_token becomes undefined and It just renders my whole other requests useless as my refresh_token is missing My axiosAPI - axiosInstance : import axios from "axios" import jwt from "jwt-decode" import history from "./utilities/history" const baseURL = 'http://127.0.0.1:8000/api/' const axiosInstance = axios.create({ baseURL: baseURL, timeout: '5000', headers: { 'Authorization': localStorage.getItem('access_token') ? "JWT " + localStorage.getItem('access_token') : null, 'Content-Type': "application/json", 'accept': "application/json" } }); axiosInstance.interceptors.response.use( response => response, error => { const originalRequest = error.config; // if (error.response.status === 401 && originalRequest.url === baseURL +'token/refresh/') { // history.push('/login') // return Promise.reject(error); // } if (error.response.data.code === "token_not_valid" && error.response.status === 401 && error.response.statusText === "Unauthorized") { const refreshToken = localStorage.getItem('refresh_token'); if (refreshToken) { // const tokenParts = … -
Deploying Serverless Django with Zappa through Terraform
I want to deploy my django project through terraform, catch is I need it to be serverless so I need to use Zappa one way or another. So far I've figured I should only use Zappa for zipping up the project for Lambda but I have no idea what else to do. I know I should basically reflect what Zappa does in deployment to terraform but I can't figure out all the things it does. Creates IAM Role Creates Permission Policy Uploads zip to s3, creates lambda Schedules keep_warm callback Uploads Gateway API Settings ? I've got the Gateway API settings in a JSON file but I do not know how to use it for deployment with terraform. What should the lambda handler be in terraform? How do I even do this in terraform? -
How to create a "field group" in django-filter to a searchbar
Good morning, I'm working on a Django site and I'm making a search bar for my site with django-filter library. It's working well but it works only with one model field. I would have a search bar that works with more field (in this case text, desc and title), how is it possible to do? Filters.py import django_filters from django_filters import CharFilter, DateFilter from .models import * class PostFilter(django_filters.FilterSet): text = CharFilter(lookup_expr='icontains') class Meta: model = Post fields = ('text', 'date') Models.py class Post(models.Model): # Post core title = models.CharField(max_length=299) author = models.ForeignKey(User,default=ANONYMOUS_USER_ID, on_delete=models.CASCADE) category = models.CharField(max_length=50) image = models.ImageField(blank=True) desc = models.TextField() text = RichTextField(blank = True, null = True ) date = models.DateTimeField(auto_now=False, auto_now_add=True) slug = models.SlugField(null = True, blank = True, unique=True) Thanks for all. -
html select value from database record in django not working
This question is asked many times, but I think I am having issues with strings in the Django template I have a select tag <select name="category" class="form-control" required="" id="id_category"> <option value="" >--------</option> {% for cat in all_categories %} <option value="{{cat}}" {% if form.instance.category == cat %} selected {% endif %}> {{cat}}</option> {% endfor %} </select> my {{cat}} variable has value 'Django Book' and {{form.instance.category}} also have same value i.e. 'Django Book'. But it doesn't select the desired option however, I am using similar logic in another part <select class="form-control" id="client" required name="client"> <option value=" ">-----</option> {% for customer in all_customers %} <option value="{{customer.pk}}" {% if form.instance.client_id.pk == customer.pk %}selected{% endif %}>{{customer}}</option> {% endfor %} </select> but this time I am comparing ids to select the default option and it works. what is the issue in the above code?? is this issue with strings?? and how can I overcome this. Also, I would like to set strings in the value attribute in the first code example. Thanks for any help. -
Django migration id char column to existing table
I am trying to create an ID charfield column and set it as primary key to an existing table. So because it is an existing table when i generate Migrations django asks me to provide a default value. What can i enter as primary key default for existing rows? If i enter a single string e.x 'abcd' i will get error for existing rows on migrate because of duplicate value -
how fix npm run dev?
Can't configure package.json, this code gives an error: "scripts": { "dev": "webpack --mode development ./leadmanager/frontend/src/index.js --output-path .leadmanager/frontend/static/frontend", "build": "webpack --mode production ./leadmanager/frontend/src/index.js --output-path .leadmanager/frontend/static/frontend" }, When I do npm run dev: (venv) awan2rist@Vladimir lead_manager_react_django % npm run dev > lead_manager_react_django@1.0.0 dev /Users/awan2rist/Dev/lead_manager_react_django > webpack --mode development ./leadmanager/frontend/src/index.js --output-path .leadmanager/frontend/static/frontend sh: webpack: command not found npm ERR! code ELIFECYCLE npm ERR! syscall spawn npm ERR! file sh npm ERR! errno ENOENT npm ERR! lead_manager_react_django@1.0.0 dev: `webpack --mode development ./leadmanager/frontend/src/index.js --output-path .leadmanager/frontend/static/frontend` npm ERR! spawn ENOENT npm ERR! npm ERR! Failed at the lead_manager_react_django@1.0.0 dev script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/awan2rist/.npm/_logs/2020-11-24T09_20_20_637Z-debug.log -
Question about graphene-django mutation documentation
While I've been able to make my application work, I have some concerns about doing things the right way. Therefore there is something I "do not understand" : In the documentation, here, in the QuestionMutation class, there is a question attribute. What does that actually mean ? It says that it defines the response and I don't understand what this means. Code from the documentation : class QuestionType(DjangoObjectType): class Meta: model = Question class QuestionMutation(graphene.Mutation): class Arguments: # The input arguments for this mutation text = graphene.String(required=True) id = graphene.ID() # The class attributes define the response of the mutation question = graphene.Field(QuestionType) @classmethod def mutate(cls, root, info, text, id): question = Question.objects.get(pk=id) question.text = text question.save() # Notice we return an instance of this mutation return QuestionMutation(question=question) And in my code I've been able to do this : My type : class UserType(DjangoObjectType): class Meta: model = User fields = ( 'id', 'username', 'password', 'email', 'first_name', 'last_name', 'is_active', 'group_ids', ) full_name = graphene.String() # Python property full_identification = graphene.String() # Python property My mutation : class UpdateUser(graphene.Mutation): # --------> I could comment these and no problem. Why ? <-------- # id = graphene.ID() # username = graphene.String() # email … -
Django is Inserting Record instead Of Updating
I am trying to perform crud operations but when i try to update then django add's a new row in the db with the new pk 'id'. I am using autofield set to primary_key = True(default). @login_required def edit(request,id): note = UserCreatedNote.objects.filter(pk=id,user=request.user) if request.method == 'POST': form = AddNoteForm(request.POST,note[0]) if form.is_valid(): form_data = form.save(commit=False) form_data.user = request.user //cause i have excluded this field in form. form_data.save() form = AddNoteForm(instance=note[0]) context={'note':note[0],'u_form':form} return render(request,'edit_note.html',context) Models.py class UserCreatedNote(models.Model): user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE) note_title = models.CharField(default='',max_length=100,blank=True,null=True) note_tags = models.CharField(default='',max_length=20,blank=True,null=True) note_contents = RichTextField(default='',max_length=1000,blank=True,null=True) creation_time = models.DateTimeField(auto_now_add=True) last_modified_time = models.DateTimeField(auto_now=True) class Meta: ordering = ['creation_time',] def __str__(self): return str(self.user) -
Not able to create Django model in Celery task
@shared_task def create_request(self, par1, par2, par3, par4): print("Task Initiated") urequest = askrequest(par1= par1, par2 = par2, par3 = par3, par4=par4) urequest.save() return urequest Here I am creating and saving my request model instance and returning newly created instance back to the caller. But System throws error of Bad Request always. If i do same without celery task it works fine. -
How to call a function in django views?
def categories_list(request): categories_in_nav = Category.objects.all() return render(request, 'partials/navbar.html', {'categories': categories_in_nav}) def homepage_view(request): categories_in_nav = categories_list(request) # it is returning <HttpResponse status_code=200, "text/html; charset=utf-8"> instead of queryset. ....... return render(request, 'main/home.html', context} In home.html, partials/navbar.html is included because of some reasons. In the navbar.html there will be a list of categories but how can I render them in home.html? I am thinking of using the context_processors which will work but is it a good to use context processors in such cases also ? Is there any other way except context_processors. -
django.db.utils.ProgrammingError: column "Price" of relation "ogs_features_product" does not exist
I am currenltly running django 3.1 I am trying to migrate my models.py file to postgres database. I was able to makemigrations, but when I did python manage.py migrate I got the following error. Previously, I had a "Price" table which included "Product_ID" of "Product" table. After having issues with my models.py id's (I have previously changed my current primary keys names you see to just id, and that caused the whole confusion), I went back to a previous version of my code that did not include "Price" table. I was able to hop on the local server and everything, but I cannot access Customers in admin page because Customer_ID does not exist for some reason (This is in addition to not being able to migrate because of the "Price" table error!) Is their a way to completely clean all the migrations. models.py file from django.db import models from django.contrib.auth.models import User # Create your models here. #strong entities + many-to-one + many-to-many class Customer(models.Model): Customer_ID = models.CharField(max_length = 9, primary_key = True) addressID = models.ManyToManyField('Address') First_name = models.CharField(max_length = 20, null = True) Middle_initial = models.CharField(max_length = 1, null = True) Last_name = models.CharField(max_length = 20, null = True) … -
Save model instance in a variable before save in Django
I am using a viewset where there is a partial_update method that updates the values of a model instance. What I would like to do is to save the old model instance in a variable and then save the model instance with the new values so that I can compare some values after the new values are saved in database. class ModelViewSet(viewsets.ModelViewSet): def partial_update(self, request, *args, **kwargs): oldObj=self.get_object() if self.check_update_permission(request, oldObj): responseObject = super(ModelViewSet, self).partial_update(request, *args, **kwargs) newObj = self.get_object() m2mArgs = {"ModelObject": newObj, "details": request.data} oldObject = Model.objects.get(id = oldObj.id) newObj = self.saveMappedFields(**m2mArgs) serializer = self.readSerializer(newObj) responseObject.data = serializer.data return responseObject else: return HttpResponse('Unauthorized', status=401) def saveMappedFields(self, **args): modelObject = args.get("modelObject", None) details = args.get("details", None) if modelObject and details: # flag = False modelObject.model_attribute.clear() if "model_attribute[]" in details: modelObject.model_attribute.set(details.getlist("model_attribute[]")) return modelObject What I would like is to have the value of oldObject value to be the old model instance values. But it is showing the values of newObj. How can I rectify this error? -
how to upload images in aws lightsail django project via admin page
I wanna upload images along with texts to the database of my Django site through the admin page of my Django project. I have set static and media url and root in settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'myproj/static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and in urls.py: from django.views.static import serve urlpatterns = [ ... url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}), url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}), ] And I declared my image in any model as follows: some-app-models.py: cover = models.ImageField(upload_to='photos/products/', blank=True) I did it without any problem in development mode on my local machine. to do so, I simply go to localhost/admin and select any table and add a row in that database. In this scenario, I select an image from my local machine to be stored in the path which I defined in models.py. The problem arises when I want to do that routine in production mode. I have deployed my Django project on AWS lightsail. It's working correctly and static files are being loaded too. But, When I go to http://mysite/admin and want to add data to the database to be shown in the site, I select an image from my local machine … -
Using Django .update() with .get()
I have an invoice table # app/models.py class tbl_invoice(models.Model): invoice_id = models.IntegerField(blank=True, null=True) invoice_number = models.IntegerField(blank=True, null=True) quotation_id = models.IntegerField(blank=True, null=True) quotation_number = models.IntegerField(blank=True, null=True) invoiced = models.CharField(max_length=50, default='', blank=True, null=True) this table contains invoice and quotations records, system user has the option to convert any quotation to invoice, but the quotation record will still remain along with the newly generated invoice record and this is my views #views.py obj = tbl_invoice.objects.get(pk='someId') # getting existing record with pk obj.pk = None obj.invoice_id = 'someId' obj.quotation_id = None obj.invoice_number = 'someValue' obj.quotation_number = None obj.invoiced = 'no' obj.type_status = 'invoice' obj.save() above code is working fine, it creates a new invoice record and also maintains the old quotation record however, after converting quotation to invoice I also want to update the invoiced value on the quotation record to yes for that, I tried obj.update(invoiced = 'yes') but .update() doesn't work on .get() how can I create a new record from an existing record and update the old record at the same time or do I have to use multiple queries Thanks for any help.