Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pictures unlimited for each list
I want to solve the problem for an unlimited number of pictures for each list. Whenever I want to put the pictures on the list, I get only one picture or i write several fields for the picture. Note: Photos are added at the same time as the list I try define ForeignKey for picture and then store file in session class Listing(models.Model): title = models.CharField(max_length=200) address = models.CharField(max_length=200) class Photo(models.Model): image = models.ImageField(default="default.png", blank=True, null=True, upload_to="photos/%Y/%M/%D") listing = models.ForeignKey(Listing, related_name='Photos', on_delete=models.CASCADE) Is it possible to add files on the session and then refer to them later after save the list because He didn't accept wanting to turn the object into json if request.method == "POST": myfile = request.FILES['file'] if 'file' in request.FILES else False if myfile: if not 'saved' in request.session or not request.session['saved']: request.session['saved'] = [json.dumps(str(myfile))] else: request.session['saved'].append(json.dumps(str(myfile))) -
How to get google calendar events of users of my website by python
I want to get google calendar events of users of my website by python and django. I used the following code but it gets just my events of google calendar. How can I access to google calendar of users if I hare 'user' in the input of the following 'def' to get and insert event to it (any user have a email field)? from __future__ import print_function import datetime import json import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request def get_events_google_calendar(): """Shows basic usage of the Google Calendar API. Prints the start and name of the next 10 events on the user's calendar. """ # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'] creds = None # The file token.pickle stores the user's access and refresh tokens, and # is created automatically when the authorization flow completes for the first time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( './google_calendar/client_secret.json', SCOPES) creds = flow.run_local_server(port=0) # Save the … -
How to Test in case Unittest By pass file excel to Import API
i'm will test code by TestCase of django.test and APIClient of resrt_framework.test with excel file, where do i can test thus import api test_import_file.py import xlrd from django.test import TestCase from rest_framework.test import APIClient from account.models import Account from account.tests import create_super_user from instructor.models import Instructor from utils.excel import get_value class TestClassImport(TestCase): def setUp(self): self.account = create_super_user() self.client = APIClient() self.client.force_authenticate(self.account) self.url = 'static/example/example_class_import.xlsx' self.file = open('static/example/example_class_import.xlsx', 'rb') self.wb = xlrd.open_workbook(file_contents=self.file.read()) self.sh = self.wb.sheet_by_index(0) def test_real_import(self): file = open(self.url, encoding="utf8", errors='ignore') url = '/api/dashboard/content-migration/import/instructor/' self.response = self.client.post(url, file) self.failUnlessEqual(self.response.status_code, 201) I hope it will "test_real_import (class.unittest.test_import_file.TestInstructorImport) ... ok" -
How do i turn off django's plural notation in the admin page
I have some tables that are presented as inlines of another class. I have altered the default title of these inline representations by adding an inner class to the respective tables. class Meta: verbose_name = 'Binnengekomen punten' I have only the verbose_name defined but it still adds an s to all the names. So 'Binnengekomen punten' is displayed as 'Binnengekomen puntens' What i could do is define the plural of verbose_name verbose_name_plural the same as verbose_name. But is there a way to simply turn off the plural notation? I'd love to know thank you. -
How to populate (Chained) Dependent Dropdown
I want to populate dependent combos based on selection of parent combos. my code is as follow: class Species(models.Model): name = models.CharField(max_length=120, blank=False, null=False) description = models.TextField(max_length=300, blank=False, null=False) class SpeciesDetail(models.Model): species = models.ForeignKey(Species, on_delete=models.CASCADE) picture = models.ImageField(upload_to='pics') gender = models.CharField(max_length=1) health = models.CharField(max_length=120) class Pair(models.Model): species = models.ForeignKey(Species, on_delete=models.CASCADE) male = models.ForeignKey(SpeciesDetail, on_delete=models.CASCADE, related_name='male_set') female = models.ForeignKey(SpeciesDetail, on_delete=models.CASCADE, related_name='female_set') -
How to resize image file in django model
I have a model with an ImageField . I would like to add a save method in the model to resize image before saving. I got the code to work without throwing any error. But the image file was not resized. I tried put the same code in views.py and uploaded images are resized correctly. Wonder what I did wrong I am using python 3.7 with django 2.2. model.py class UploadFile(models.Model): image_file_path = models.ImageField(upload_to='images/', null=True, blank=True) def save(self, *args, **kwargs): Img.MAX_IMAGE_PIXELS = 933120000 if self.image_file_path: image = Img.open(self.image_file_path) (width, height) = image.size print(width,height) # "Max width and height 800" if (800 / width < 800 / height): factor = 800 / height else: factor = 800 / width size = (int(width * factor), int(height * factor)) resized_image = image.resize(size, Img.ANTIALIAS) image.close() file_path = os.path.join(settings.MEDIA_ROOT, str(self.image_file_path)) resized_image.save(file_path,optimize=True,quality=95) return super(UploadFile, self).save(*args, **kwargs) -
Best way to store measurement units for Django model's fields?
I have a product model which has a lot of fields with all the product's specs such as width, weight, and a lot of other. I want to display a table with all specs, so I decided to iterate through my model's fields and display the table with a field name + value + measurement units in my template. I'm storing field name in a verbose_name attribute and field description in the help_text attribute, but I'm curious what is the best way to store a particular measurement unit for a specific field? -
Django migrations: what `elidable` argument is for?
I have a RunPython operation in my migrations. This operation accpets an optional elidable argument, which is described in the Django docs: The optional elidable argument determines whether or not the operation will be removed (elided) when squashing migrations. This description is a little bit confusing for me. My question is: what happens, when migrations with elidable=True flag are squashed? I guess that migrations with elidable=True would be simply deleted. And some manual steps would have to be taken in order to add the logic of elided migrations into the squashed one. -
Able to upload file but non retrieve them - Page not found
I am creating a website in Django and Postgres where a user can answer multiple questions and upload some PDFs. I am able to upload the PDF but not to display it. I want the user to be able to click on a link, and a new webpage opens containing the PDF. In my details.html I wrote the code: <a href="{{ MEDIA_URL }}{{project.thirdquestiondetail.third_seven.url}}">Click here to see the file</a> But, if the user clicks on the links, he gets this messages: I have the following: mysite/urls.py from django.contrib import admin from django.urls import path, include from django.views.generic.base import TemplateView from django.conf import settings from django.views.static import serve from django.conf.urls.static import static urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home'), path('conditions/', TemplateView.as_view(template_name='conditions.html'), name='conditions'), path('admin/', admin.site.urls), path('users/', include('users.urls')), path('users/', include('django.contrib.auth.urls')), path('projects/', include('projects.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) mysite/settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'mysite/static/') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' As said, I am pretty sure the PDF is uploaded. In fact, if I login as superuser in the admin panel, I can see the PDF. HOWEVER if I click it, I get the same 404 error reported above I think the error is in my settings.py when … -
Django set M2M field similar to other M2M field
I have a problem with Many-to-Many Fields. In a post-save hook I am trying to set a Many-to-Many Field. I basically want to copy another M2M field and save it into the new one. class A(models.Model): a = ManyToManyField(X, ...) class B(models.Model): b = ManyToManyField(X, ...) @receiver(post_save, sender=B, dispatch_uid="uid") def postsave_it(sender, instance, **kwargs): if not instance.b.exists(): post_save.disconnect(...) instance.b.set(instance.a) post_save.connect(...) So the line instance.b.set(instance.a) doesnt work, the instance of A has no value for a selected. Help would be very much appreciated! -
Cannot import <app>. Check that <path> is correct
I have a next structure of project I want to create a signal in a blog application, but I get an error Cannot import 'blog'. Check that 'project.blog.apps.BlogConfig.name' is correct. If I write default_app_config = 'blog.apps.BlogConfig' in __init__.py I get error: No module named 'blog' settings.py INSTALLED_APPS = [ #... # project apps 'project.blog', #... ] apps.py class BlogConfig(AppConfig): name = 'blog' def ready(self): import blog.signals __init__.py default_app_config = 'project.blog.apps.BlogConfig' -
I got this error "Tuple has no attribute 'obj'"
I got this error "Tuple has no attribute 'obj'" def upload_list(request): pdf = Client_files.objects.all() cn = pdf.values_list('client').distinct() print(cn) for i in range(len(cn)): client = Client_Process.objects.filter(client__in=cn[i]) cn[i].obj = client -
Is there a more elegant way to write this django view?
I've been messing around with django and I have this django view: def handle_results(request): if request.method == "POST" and request.is_ajax(): # Do something with the post request elif request.method == "GET" and request.is_ajax(): # Do something with the get request else: # First time in this view, render first element to display return render( request, "result_page.html", context={"display": arr[0]} ) The main idea is, this is supposed to be a Same Page Application, and the first time I'm in this view, I need to render the contents of the array to display to the user, after that, the user can interact with said array via the html (think of it as upvoting or downvoting stuff that's shown). Depending on the user's choice, I get a GET or POST request and need to deal with said request. However, the way I'm implementing this seems not that elegant and I was wondering if there'd be another better way to accomplish what I'm doing. Thank you so much! -
the website created is for editing images with frames
the django website i have created is not saving any of the images that i choose neither it is displayed on the frame whc i select.. this is my views.py def SaveProfile(request): saved = False if request.method == "POST": # Get the posted form MyProfileForm = ProfileForm(request.POST, request.FILES) if MyProfileForm.is_valid(): profile = Profile() profile.name = MyProfileForm.cleaned_data["name"] profile.picture = MyProfileForm.cleaned_data["picture"] profile.save() saved = True else: MyProfileForm = Profileform()class Profile(models.Model): name = models.CharField(max_length = 50) picture = models.ImageField(upload_to = 'media') class Meta: db_table = "profile" return render(request, 'saved.html', locals()) this is models.py class Profile(models.Model): name = models.CharField(max_length = 50) picture = models.ImageField(upload_to = 'media') class Meta: db_table = "profile" this is forms.py class ProfileForm(forms.Form): name = forms.CharField(max_length = 100) picture = forms.ImageFields() i cannot save o display the chose image from the form neither i can download -
Detail page with Tag and Slug not found DJANGO
I am currently going through a django book and learning how to use Tags. It works fine but unfortunately whenever I want to access the detail page, the terminal return not found. I have checked several times and not able to find what the issue is. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from taggit.managers import TaggableManager class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='published') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() # Tag manager tags = TaggableManager class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.year, self.slug]) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return 'Comment by {} on {}'.format(self.name, self.post) urls.py from django.contrib import admin from django.urls import path, include from . import views app_name = 'blog' urlpatterns = … -
how can i solve this using django
Traceback (most recent call last): File "C:/Users/siva/PycharmProjects/mtech2/mysite/oms.py", line 1, in import omsFunctions File "C:\Users\siva\PycharmProjects\mtech2\mysite\omsFunctions.py", line 1, in import nltk File "C:\Users\siva\AppData\Local\Programs\Python\Python37-32\lib\site-packages\nltk__init__.py", line 99, in from nltk.internals import config_java File "C:\Users\siva\AppData\Local\Programs\Python\Python37-32\lib\site-packages\nltk\internals.py", line 11, in import subprocess File "C:\Users\siva\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 126, in import threading File "C:\Users\siva\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 8, in from traceback import format_exc as _format_exc File "C:\Users\siva\AppData\Local\Programs\Python\Python37-32\lib\traceback.py", line 5, in import linecache File "C:\Users\siva\AppData\Local\Programs\Python\Python37-32\lib\linecache.py", line 11, in import tokenize File "C:\Users\siva\AppData\Local\Programs\Python\Python37-32\lib\tokenize.py", line 41, in all = token.all + ["tokenize", "detect_encoding", AttributeError: module 'token' has no attribute 'all' Process finished with exit code 1 -
Dependencies on Media class in Django
I have a simple ModelAdmin, which defines a Media class and this class includes some JavaScript class ExerciseAdmin(NestedPolymorphicModelAdmin): class Media: js = ( 'exercises/ck-editor-dynamic-init.js', ) I'd like to use django.jQuery in this script, but the problem is that when thi script is injected to the admin site django.jQuery is not initialized yet. Here is my workaround, but it's ugly: let loading = setInterval(function () { if (django.jQuery !== undefined) { loading = clearInterval(loading); (function ($) { $(document).on('formset:added', function newForm(event, row) { console.log(event); }); })(django.jQuery); } }, 100); I can imagine, that this is not the best way how to do it. Can somebody suggest any better? Thanks -
I am trying to make a specific query the contains sub-string comparison using row function
I am trying to make a query that joins 3 tables and contains conditions that use substring comparison. I am using row function I have tried filters but didn't know how to join more than one table This is the view.py def index(request): transportServices=TransportServices.objects.all() interFaceType= InterfaceType.objects.raw(''' SELECT it_pk,it_short_name from transport_services,interface_type,router WHERE rou_pk= 519342 and ts_rou_pk=rou_pk and ts_it_pk=it_pk and rou_last=1 and (it_short_name like 'GE%' or it_short_name like 'FE%' or it_short_name like 'TE%') order by it_short_name ''') print(interFaceType) if request.method == 'GET': connectionType = request.GET.get('ConnType') print(connectionType) #print(Router.objects.all()) return render(request,'posts/index.html',{'router': router}) This is model.py class Router(models.Model): rou_pk = models.AutoField(db_column='ROU_PK', primary_key=True) rou_st_pk = models.DecimalField(db_column='ROU_ST_PK', max_digits=10, decimal_places=0, blank=True, null=True) rou_name = models.CharField(db_column='ROU_NAME', max_length=20, blank=True, null=True) rou_last = models.BooleanField(db_column='ROU_LAST', blank=True, null=True) class TransportServices(models.Model): ts_pk = models.AutoField(db_column='TS_PK', primary_key=True) # Field name made lowercase. ts_ts_pk = models.DecimalField(db_column='TS_TS_PK', max_digits=10, decimal_places=0, blank=True, null=True) # Field name made lowercase. ts_rou_pk = models.DecimalField(db_column='TS_ROU_PK', max_digits=10, decimal_places=0, blank=True, null=True) # Field name made lowercase. # ts_spe_pk = models.DecimalField(db_column='TS_SPE_PK', max_digits=10, decimal_places=0, blank=True, null=True) # Field name made lowercase. # ts_at_pk = models.DecimalField(db_column='TS_AT_PK', max_digits=10, decimal_places=0, blank=True, null=True) # Field name made lowercase. ts_it_pk = models.DecimalField(db_column='TS_IT_PK', max_digits=10, decimal_places=0, blank=True, null=True) # Field name made lowercase. class InterfaceType(models.Model): it_pk = models.AutoField(db_column='IT_PK', primary_key=True) # Field name made lowercase. #it_it_pk … -
Check url status without opening it
At Now when url is opened (without a slash - example.com/blog), a slash is automatically added at the end (there are 301 redirects). The question is, can I somehow do it so that the check first goes to see if the page exists (without a slash - example.com/blog). If so, open it. If not, then check whether the page exists with a slash (only without 301 - example.com/blog/). If so, then redirect 301, and if not, then throw 404. Now just if there is no page (example.com/blog), then a slash is added to the end first (example.com/blog/), 301 redirects go and only then a 404 error is thrown. In this case, the 404 error must be thrown immediately, without a 301 redirect. The dispatch was rewritten as follows. def is_normal_slash_count(url): temp_url = url slash_count = 0 while temp_url.endswith('/'): slash_count += 1 temp_url = temp_url[:-1] return (slash_count == 1, slash_count) def replace_bad_slash(url, slash_count): if slash_count == 2: return url.replace('//', '/') return url.replace('/'*(slash_count-1), '') def normalize_url(url): if len(url) > 1: if not url.endswith('/'): return url + '/' # replace the url like /contacts//// to /contacts/ good_slash, slash_count = is_normal_slash_count(url) if not good_slash: url = replace_bad_slash(url, slash_count) return url def is_bad_url(url): if len(url) … -
Django Login using function error: join() argument must be str or bytes, not 'User'
I'm using Django 2.2.4 with this implementation for a login function def login_ajax(request): response = {'complete': False} if request.method == 'POST': data = json.loads(request.body) email, password = data['email'], data['password'] user = authenticate(request, username=email, password=password) if user is None: #try with email user = authenticate(request, email=email, password=password) #both checks done so invalid if user is None: response['error'] = 'Username/Email and Password Combination Failed.' else: print(user.id) login(request, user) response['complete'] = True else: response['error'] = 'no post data found' return HttpResponse( json.dumps(response), content_type="application/json" ) which can login with username/email based on Django's documentation but it throws this error TypeError at /login-ajax join() argument must be str or bytes, not 'User' Request Method: POST Request URL: http://127.0.0.1:8000/login-ajax Django Version: 2.2.4 Python Executable: C:\Users\samuel.irungu\Envs\chuify\Scripts\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\samuel.irungu\\code\\chuify', 'C:\\Users\\samuel.irungu\\Envs\\chuify\\Scripts\\python37.zip', 'C:\\Users\\samuel.irungu\\Envs\\chuify\\DLLs', 'C:\\Users\\samuel.irungu\\Envs\\chuify\\lib', 'C:\\Users\\samuel.irungu\\Envs\\chuify\\Scripts', 'c:\\users\\samuel.irungu\\appdata\\local\\programs\\python\\python37\\Lib', 'c:\\users\\samuel.irungu\\appdata\\local\\programs\\python\\python37\\DLLs', 'C:\\Users\\samuel.irungu\\Envs\\chuify', 'C:\\Users\\samuel.irungu\\Envs\\chuify\\lib\\site-packages'] Server time: Thu, 22 Aug 2019 10:03:59 +0000 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'common'] Installed Middleware: ['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'] Traceback: File "C:\Users\samuel.irungu\Envs\chuify\lib\ntpath.py" in join 89. for p in map(os.fspath, paths): During handling of the above exception (expected str, bytes or os.PathLike object, not User), another exception occurred: File "C:\Users\samuel.irungu\Envs\chuify\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\samuel.irungu\Envs\chuify\lib\site-packages\django\core\handlers\base.py" in _get_response 115. … -
Get/Display API data at front end from an API created in Django using Django-REST-Framework in an HTML page or Template
I am working with Django for quite some time but only at the basic backend level. Now I have started using DRF or Django-REST-Framework for creating an API and this is a new thing for me. I have successfully made an API using it and tested it using Postman by hitting on the URL for the data. My app is sending data as JSON. Problem is that I am unable to find a tutorial or link to see how can I consume this API data at front end. How can I send requests to get the data and then make a form to save data at the back end. Models.py class Poll(models.Model): question = models.CharField(max_length=100) created_by = models.CharField(max_length=256) pub_date = models.DateTimeField(auto_now=True) serializers.py class PollSerializer(serializers.ModelSerializer): class Meta: model = Poll fields= ('created_by', 'question', 'pub_date') views.py class PollDetail(generics.RetrieveUpdateDestroyAPIView): serializer_class = serializers.PollSerializer queryset = Poll.objects.all() authentication_classes = [TokenAuthentication, BasicAuthentication] permission_classes = [IsAuthenticatedOrReadOnly] urls.py path('polls/<int:pk>/', views.PollDetail.as_view(), name='poll_detail_api'), Can someone help me with this? ALso How can I send information to authenticate users using Tokens saved in my DB? -
Deploy Django to Heroku (TemplateDoesNotExist)
I just deploy the project to Heroku, however the templates can't be found. Can someone help me out settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR,'Users/jay/Downloads/PJ/ecommerce/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', ], }, }, ] Error message: Exception Type: TemplateDoesNotExist Exception Value: list.html Exception Location: /app/.heroku/python/lib/python3.6/site-packages/django/template/loader.py in get_template, line 19 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.8 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Thu, 22 Aug 2019 09:51:24 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /app/Users/jay/Downloads/PJ/ecommerce/templates/list.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/templates/list.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/templates/list.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.6/site-packages/crispy_forms/templates/list.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/accounts/templates/list.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/carts/templates/list.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/orders/templates/list.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.6/site-packages/bootstrap4/templates/list.html (Source does not exist) -
Update records depending on fields - Django
I want to override the save method of a model in Django. Consider this model: class OtherClass(models.Model): name = models.CharField(max_length=255, blank=True, null=True) class MyClass(models.Model): admin = models.ForeignKey(OtherClass, on_delete=models.CASCADE) myfield1 = models.CharField(max_length=128) myfield2 = models.CharField(max_length=128) myfield3 = models.CharField(max_length=128, blank=True, null=True) myfield4 = models.CharField(max_length=128, blank=True, null=True) myfield5 = models.TextField(blank=True) What I want, is to update the model only if myfield5 is present in whatever form or view the user is filling. This is the current save method I have: def save(*args, **kwargs): fieldgroup = f"{self.myfield2}\n{self.myfield3}" self.myfield5 = f"{fieldgroup}\n{self.field1} {self.field4} {self.field5}" super().save(*args, **kwargs) Any ideas? Maybe it would be better to achieve this on a form rather than directly into the model? -
how do I write a test that would allow me to upload an image via DRF
I am trying to figure out how I can write a test for DRF that would allow me to upload an image file. uploading images does work fine via the the normal drf web view, but I am not sure the process to write a test for this. Below is what I currently have, however it is not currently working. When I do a trace on the response I am getting *** ValueError: Content-Type header is "text/html", not "application/json" Code below - doing a post to via Django's client for testcase def test_user_image_upload_post(self): header_admin = { "HTTP_AUTHORIZATION": "Token {}".format(self.token_admin), "Content-Type": "application/json" } img_1_path = Path("api/temp_files/temp1.gif") with open(img_1_path, 'rb') as tmp_file: tmp_file_str = base64.b64encode(tmp_file.read()).decode('utf-8') tmp_file_str_json = json.dumps(tmp_file_str) response = self.client.post( "api/images", data={ "gallery": "http://127.0.0.1:8000/api/galleries/{}/".format("2"), "img": tmp_file_str_json }, **header_admin ) import pdb; pdb.set_trace() #Not done yet self.assertEqual(tmp_image) Any help would be appreciated since this should return a 200 status code somehow. I know I am doing something wrong :-( -
How to show balance ZERO by default when someone new makes an account?
I have a page which shows a user how much balance he/she has. I put that balance in admin page. But when somebody makes an account first time, I want to show them their balance zero. How to do it? models.py class Balance(models.Model): amount = models.DecimalField(max_digits=12, decimal_places=2) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'Balance' def __str__(self): return f'{self.owner} Balance' views.py @login_required def balance(request): total = Balance.objects.get(owner=request.user) return render(request, 'nextone/balance.html', {'amount': total.amount}) HTML page <h2>Your Balance is Rs. {{amount}}</h2