Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UndefinedColumn column integrations_externalrecord.oppcontact_id does not exist django postgresql
When accessing my ExternalRecord model via the django admin screen, or by querying ExternalRecord.objects.all(), I receive the error: psycopg2.errors.UndefinedColumn: column integrations_externalrecord.oppcontact_id does not exist I am building an integration functionality, and we have a junction table that houses an external id and the instance in our database that corresponds to this external id, set up like so: class ExternalRecord(UUIDPrimaryKey, CreatedModifiedMixin, models.Model): integration = models.ForeignKey( to=Integration, related_name='external_records', on_delete=models.CASCADE ) emailuser = models.ForeignKey( "accounts.EmailUser", related_name='external_records', null=True, blank=True, on_delete=models.CASCADE ) institution = models.ForeignKey( "institutions.Institution", related_name='external_records', null=True, blank=True, on_delete=models.CASCADE ) oppcontact = models.ForeignKey( "opp_contacts.OppContact, related_name='external_records', null=True, blank=True, on_delete=models.CASCADE ) external_record_id = models.CharField( max_length=1000 ) and so on... When I view the OppContact model either by viewing in the django admin screen or with OppContact.objects.all(), I see that the model has a field for "id". When I rollback to the migration before applying the oppcontact field, everything returns to work as normal, meaning I can query/view ExternalRecords without getting an error. This is my OppContact model: class OppContact(UUIDPrimaryKey): company = models.ForeignKey( "accounts.Company", on_delete=models.CASCADE, blank=True, null=True ) first_name = models.CharField( max_length=100 ) last_name = models.CharField( max_length=100 )... And this is another model to which my ExternalRecord can be linked, Institution: class Institution(UUIDPrimaryKey, CreatedModifiedMixin, models.Model): company = … -
InMemoryUploadedFile is not JSON serializable
I'm sending a payload with some string and two images in a POST Request. But I'm not sure how to serialize the images in the payload. I'm using POSTMAN's form-data to send this request and I'm getting ('Object of type InMemoryUploadedFile is not JSON serializable') def registration(self, payload): try: headers = {"accept": "application/json"} logger.debug({"payload": payload}) response = requests.post(url=self.registration_url, headers=headers,json=payload) if response is None: return None, status.HTTP_424_FAILED_DEPENDENCY parsed_data = data_parser.render_registration_response(response, payload) return parsed_data, response.status_code except Exception as e: logger.error(repr(e)) return None, status.HTTP_424_FAILED_DEPENDENCY Serializers.py class RegistrationSerializer(serializers.Serializer): name = serializers.CharField(max_length=20) vehicle_number = serializers.CharField(max_length=50) blue_book = serializers.ImageField(max_length=None, allow_empty_file=False, required=False) vehicle_class = serializers.CharField(max_length=50) bank_account = serializers.CharField(max_length=50) phone = serializers.CharField(max_length=20) avatar = serializers.ImageField(max_length=None, allow_empty_file=False, required=False) country = serializers.CharField(max_length=20) state = serializers.CharField(max_length=20) city = serializers.CharField(max_length=20) zip = serializers.CharField(max_length=20) -
Add attribute to the checkbox field based on initial django form
class MyForm(Form): real = BooleanField() If MyForm(data={'real': 'on'}), I want to render <input type="checkbox" checked=checked data-initial='on'>. If MyForm(data={}), I want to render <input type="checkbox">. How to achieve this? -
Import images from excell file to django database
I am looking for some code to import all images from excel sheet and save them in my database without using pywin32. Any help would be grateful. Thanks -
ValueError: source code string cannot contain null bytes in django anytime i run mange.py
I am having issues with my django project, Anytime i run the manage.py command line. It gives out this error main() File "/storage/emulated/0/django/twitter/manage.py", line 21, in main execute_from_command_line(sys.argv) File "/data/data/com.termux/files/home/my_venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/data/data/com.termux/files/home/my_venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 369, in execute settings.INSTALLED_APPS File "/data/data/com.termux/files/home/my_venv/lib/python3.10/site-packages/django/conf/__init__.py", line 84, in __getattr__ self._setup(name) File "/data/data/com.termux/files/home/my_venv/lib/python3.10/site-packages/django/conf/__init__.py", line 71, in _setup self._wrapped = Settings(settings_module) File "/data/data/com.termux/files/home/my_venv/lib/python3.10/site-packages/django/conf/__init__.py", line 179, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/data/data/com.termux/files/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 879, in exec_module File "<frozen importlib._bootstrap_external>", line 1017, in get_code File "<frozen importlib._bootstrap_external>", line 947, in source_to_code File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed ValueError: source code string cannot contain null bytes I have tried other solutions online and it is not working. Please could anyone help me. This is my setting file -
How to validate unique roll number and show them a validation error when the roll already exists using serializers Django Rest framework
I want to validate roll number in Serializers Django Rest framework I want to show validation error when the roll number is already present in the database. -
DRF: Is there any way to keep ModelSerializer's auto-generated validators while using dynamic fields?
I'm trying to have Django Rest Framework serializers with dynamic fields that depend on the context passed (request method, CRUD action etc.). So I set the fields in self.fields when the serializer is initialized. It works fine at the moment, but the problem is that I don't get the automatically generated validators that ModelSerializer provides. Is there any way to get those validators or do I have to resort to copy pasting validators from my models? -
foreign key dynamic filter with another foreign key in admin.py in django
I have a problem with the dynamic design of the admin. Thank you for your help. I want the selected productCategory to be dynamically filtered when I select the productType. For example, I do this manually in models.py (ProductCategory.objects.filter(productType=2 or 1 or 4 ...( i cant dynamic)) models.py enter code here class ProductType(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) class ProductCategory(models.Model): productType = models.ForeignKey(ProductType, on_delete=models.CASCADE) name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) productType = models.ForeignKey(ProductType, on_delete=models.CASCADE, default=1) productCategory = models.ForeignKey(ProductCategory, on_delete=models.CASCADE) enter code here admin.py class ProductForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) if self.instance: self.fields['productCategory'].queryset = ProductCategory.objects.filter(productType=self.instance.productType.id) @admin.register(Product) class ProductAdmin(admin.ModelAdmin): form = ProductForm -
Django template doesn't see data of db
While learning it, I faced with an issue, when I'm trying to show data from db, template doesn't see it. I tried to remove db and migrations and create new with new objects, but it didn't helped. models file: from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class Product(models.Model): name= models.CharField( max_length= 100, verbose_name= 'Name' ) description= models.TextField(max_length= 500) photo= models.ImageField(upload_to= 'photos/%Y/%m/%d') price= models.FloatField(validators= [MinValueValidator(2.0), MaxValueValidator(1000000.0)],) amount= models.IntegerField() last_updated= models.DateTimeField(auto_now= True) is_published=models.BooleanField(default=False) category= models.ForeignKey( "Category", verbose_name= 'Category', default='Unselected', on_delete=models.SET_DEFAULT ) class Meta: verbose_name = "Product" verbose_name_plural = "Products" def __str__(self): return self.name class Category(models.Model): name=models.CharField(max_length=100) class Meta: verbose_name = 'Category' verbose_name_plural = "Categories" def __str__(self): return self.name views file: from django.shortcuts import render from .models import * # Create your views here. def index(request): print(request) product=Product.objects.all() return render(request,'main.html',{product :'product'}) template file: {% for item in product %} <h1>{{item.name}}</h1> {% if item.photo %} <img src="{{item.photo.url}}" alt="Not found"> {% endif %} <p>{{item.description}}</p> <h2>{{item.price}}</h2> {% endfor %} I didn't show full html file,due to stackoverflow didn't let me to post it, because there is a lot of code, and no text -
Django: calculating multiple values of over a set of children
I'm writing the management interface for a competition, and have the following models: class Heat(models.Model): current_heat = models.IntegerField() track = models.ForeignKey(Track, on_delete=models.PROTECT) previous_heat = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) start_date = models.DateTimeField('Start Date', default=timezone.now) end_date = models.DateTimeField('End Date', null=True, blank=True) class Game(models.Model): heat = models.ManyToManyField(Heat) format = models.TextField(max_length=20, default="V") player1 = models.ForeignKey(User, on_delete=models.PROTECT, related_name='player1') player2 = models.ForeignKey(User, on_delete=models.PROTECT, related_name='player2') winner = models.ForeignKey(User, on_delete=models.PROTECT, related_name='winner', null=True, blank=True) Now I want to get the standings for a specific heat. In other words, I want to get all unique players in that heat, together with how many wins they got (thus where they are in Game.winner), and how many losses they got (thus where Game.winner is not that player but it is not Null, and they are in either Game.player1 or Game.player2.) Ideally, this should then even be ordered by wins (descending), losses (ascending). I've been looking through the aggregation docs from Django, but I don't see how to start since I need to get so many different things all combined. -
urllib [Errno 11001] getaddrinfo failed with windows proxy
I'm running Django 3.2 with django-tenants on a Windows local dev environment. In my windows hosts file I have: 127.0.0.1 *.localhost ...so that I am able to use subdomains with django-tenants. E.g. http://mysub.localhost:8000. When running ./manage.py runserver the dev server runs perfectly. However, when trying to execute urlopen in my code I get an error: >>> html = urlopen('http://mysub.localhost:8000') Traceback (most recent call last): [...] urllib.error.URLError: <urlopen error [Errno 11001] getaddrinfo failed> As far as I can tell the error is due to the proxy settings on my windows machine (this does not fail in production), but I am unsure how to resolve it? -
How to server Django media files on apache2 and docker
I'm Running a django app on apache2 using docker, everything works great but when i try to open an uploaded file ( media file) it says an URL not found error like : physical/path/to/file/filename.jpg doesnt exsits so it converts the url to a phyical path from inside the docntainer.. Here are my files: DockerFile FROM ubuntu RUN apt-get update # Avoid tzdata infinite waiting bug ARG DEBIAN_FRONTEND=noninteractive ENV TZ=Africa/Cairo RUN apt-get install -y apt-utils vim curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python3-pip #Add sf to avoid ln: failed to create hard link '/usr/bin/pip': File exists RUN ln -sf /usr/bin/pip3 /usr/bin/pip RUN pip install --upgrade pip RUN pip install django ptvsd COPY www/demo_app/water_maps/requirements.txt requirements.txt RUN pip install -r requirements.txt ADD ./demo_site.conf /etc/apache2/sites-available/000-default.conf EXPOSE 80 5432 WORKDIR /var/www/html/demo_app #CMD ["apache2ctl", "-D", "FOREGROUND"] #CMD ["python", "manage.py", "migrate", "--no-input"] docker-compose.yaml version: "2" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data - ./data/static:/var/www/html/demo_app/static - ./data/upload:/var/www/html/demo_app/upload ports: - '5432:5432' environment: - POSTGRES_DB=database_innvoentiq - POSTGRES_USER=database_user_innvoentiq - POSTGRES_PASSWORD=mypass@ - PGDATA=/tmp django-apache2: build: . container_name: water_maps environment: - POSTGRES_DB=database_innvoentiq - POSTGRES_USER=database_user_innvoentiq - POSTGRES_PASSWORD=mypass@ - PGDATA=/tmp ports: - '80:80' volumes: - ./www/:/var/www/html # command: sh -c 'python manage.py migrate && … -
how i login to my new user account using login(request )
in my base.html i wrote this code {% if user.is_authenticated %} <div class="btn-group" > <button class="btn btn-primary" type="button" data-bs-toggle="dropdown" data-bs-auto-close="true" aria-expanded="false"> welcome {{user.username}} </button> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">profile</a></li> <li><a class="dropdown-item" href="#">change password</a></li> <li><a class="dropdown-item" href="{% url 'logout'%} ">logout</a></li> </ul> </div> {%else%} <a href="#" class ="btn btn-outline-secondary">login</a> <a href="{%url 'signup'%}" class ="btn btn-outline-primary">signup</a> {%endif%} but everytime i create a new user it always shwos the ELSE condition html this is my views: ''' from django.shortcuts import render, redirect from django.contrib.auth import login as auth_login from .forms import SignUpForm def signup(request): form = SignUpForm() if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): user =form.save() auth_login(request, user) return redirect('index') return render(request, 'signup.html', {'form': form}) ''' what is the problem -
Django : HttpRequest.__init__() takes 1 positional argument but 2 were given
So I simply want when I click on the particular article to output its slug, for example if the slug of the given article is django-rules then i want it to be outputted as django-rules when i click on it. just that here is my model from django.db import models # Create your models here. class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add = True) #add in tubnail and author later def __str__(self): return self.title def snippet(self): return self.body[:50]+'...' Here is my views.py from datetime import date from django.shortcuts import render from .models import Article from django.http import HttpRequest # Create your views here. def article_list(request): articles = Article.objects.all().order_by('date') return render(request,'articles/article_list.html', {'articles': articles} ) def article_detail(request, slug): return HttpRequest(slug) url.py from posixpath import relpath from django.contrib import admin from django.urls import path from django.views.generic import TemplateView from . import views app_name = 'articles' urlpatterns = [ path('', views.article_list, name = 'list'), path('<slug:slug>/', views.article_detail, name = 'detail'), ] Please dont suggest to add as_view() its not working. -
Azure FTPS How to find the deployed project files
I am using Azure FTP to update the project files after they are deployed via CLI I get to /site/wwwroot I see a tar file, where do I find all the project files. Requirement is to update single file each time to test it. -
elasticsearch.exceptions.RequestError: RequestError(400, 'no handler found for uri [/haystack_books/modelresult/_bulk] and method [POST]',
I'm writing a site on Django, I'm currently implementing a search system using django-haystack via elasticsearch I did everything as in the official documentation, but when I execute the command python manage.py rebuild_index I am getting an error elasticsearch.exceptions.RequestError: RequestError(400, 'no handler found for uri [/haystack_books/modelresult/_bulk] and method [POST]', 'no handler found for uri [/haystack_books/modelresult/_bulk] and method [POST]') Here is the full error trace: GET http://127.0.0.1:9200/haystack_books/_mapping [status:401 request:0.004s] PUT http://127.0.0.1:9200/haystack_books [status:401 request:0.003s] POST http://127.0.0.1:9200/haystack_books/modelresult/_bulk [status:400 request:0.004s] POST http://127.0.0.1:9200/haystack_books/modelresult/_bulk [status:400 request:0.006s] POST http://127.0.0.1:9200/haystack_books/modelresult/_bulk [status:400 request:0.008s] POST http://127.0.0.1:9200/haystack_books/modelresult/_bulk [status:400 request:0.006s] POST http://127.0.0.1:9200/haystack_books/modelresult/_bulk [status:400 request:0.013s] [ERROR/MainProcess] Failed indexing 1 - 11 (retry 5/5): RequestError(400, 'no handler found for uri [/haystack_books/modelresult/_bulk] and method [POS T]', 'no handler found for uri [/haystack_books/modelresult/_bulk] and method [POST]') (pid 3932): RequestError(400, 'no handler found for uri [/haysta ck_books/modelresult/_bulk] and method [POST]', 'no handler found for uri [/haystack_books/modelresult/_bulk] and method [POST]') Traceback (most recent call last): File "D:\Джанго проект\venv\lib\site-packages\haystack\management\commands\update_index.py", line 111, in do_update backend.update(index, current_qs, commit=commit) File "D:\Джанго проект\venv\lib\site-packages\haystack\backends\elasticsearch_backend.py", line 222, in update bulk(self.conn, prepped_docs, index=self.index_name, doc_type="modelresult") File "D:\Джанго проект\venv\lib\site-packages\elasticsearch\helpers\actions.py", line 410, in bulk for ok, item in streaming_bulk( File "D:\Джанго проект\venv\lib\site-packages\elasticsearch\helpers\actions.py", line 329, in streaming_bulk for data, (ok, info) in zip( File "D:\Джанго проект\venv\lib\site-packages\elasticsearch\helpers\actions.py", line 256, in _process_bulk_chunk … -
Saving objects to postgresql with DJango in UTC instead of local timezone?
I have a column in my table called "signed_up_date", which I am using the auto_now_add=True parameter with the DateTimeField() function. I want this function to save timestamps to the PostgreSQL DB in UTC instead of my local time (EST) which it is currently doing. Barebones version of the model for quick ref below: class TutorTest(models.Model): signed_up_on = models.DateTimeField(auto_now_add=True) Settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True I thought based on the docs, if I have Time_Zone set to UTC and UTC_TZ set to True, then the default behavior of Django would be to save as UTC. I know when I check postgresql timezone I get: SHOW TIMEZONE; TimeZone ------------ US/Eastern (1 row) I just tried a new model with timezone.now() and it looks like in the db shell I get: datetime.datetime(2022, 9, 21, 14, 36, 16, 670726, tzinfo=datetime.timezone.utc) But the db saved it as: 2022-09-21 10:35:26.633116-04 I guess it's the DB in this situation? Confused lol -
Django cart management
I work on a cart management application, I use the django-shopping-cart 0.1 package, At the level of my project I use a dictionnary the products then add them to the basket, Also noted the products are added by setting the product code. def cart_add(request, code): dico={"produits":[{'code':'fg21','name':'coca cola','prix':1500}, {'code':'br21','name':'pomme','prix':1800}]} all_produits=dico['produits'] all_product = next((item for item in all_produits if item["code"] == code), None) if selected_product != None: cart = Cart(request) product = selected_product cart.add(product=product) return render(request, 'cart/detail.html',context) Here the error comes from the cart.py module of django-shopping-cart 0.1 At line level (id = product.id) I am told the dic object has no code attribute even if I do (id=product.code) cart.py class Cart(object): def __init__(self, request): self.request = request self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, action=None): """ Add a product to the cart or update its quantity. """ id = product.id newItem = True if str(product.id) not in self.cart.keys(): self.cart[product.id] = { 'userid': self.request.user.id, 'product_id': id, 'name': product.name, 'quantity': 1, 'price': str(product.price), 'image': product.image.url } else: newItem = True for key, value in self.cart.items(): if key == str(product.id): value['quantity'] = … -
How to change the name of document in filefield url to an ID of document in Django/DRF
I want to change my url of document so that in response instead of returning with the name of the document, it should return the id of the document. so, /nononoo.txt becomes like this /2 ( id of the document) This is my response that i am getting, "id": 2, "document": "http://127.0.0.1:8000/images/nononno.txt", "filesize": "13 bytes", "filename": "nononno.txt", "mimetype": "text/plain", "created_at": "2022-09-21" I want to change this /nononoo.txt to the id of the document so that it becomes like this "document": "http://127.0.0.1:8000/images/2(id of the current document uploaded)" models.py class DocumentModel(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="DOCUMENT_ID") document=models.FileField(max_length=350 ,validators=[FileExtensionValidator(extensions)]) filename=models.CharField(max_length=100, blank=True) filesize=models.IntegerField(default=0) mimetype=models.CharField(max_length=100, blank=True) created_at=models.DateField(auto_now_add=True) def save(self, force_insert=False, force_update=False, *args, **kwargs): self.filename=self.document.name self.mimetype=mimetypes.guess_type(self.document.url)[0] self.filesize=self.document.size super().save(force_insert, force_update, *args, **kwargs) class Meta: verbose_name_plural="Documents" ordering=["document"] def __str__(self): return f'{self.document}' @property def sizeoffile(self): x = self.document.size y = 512000 if x < y and x < 1000 : value=round(x, 0) ext = ' bytes' elif x < y and x >= 1000 and x < 1000*1000: value = round(x / 1000) ext = ' KB' elif x < y * 1000 and x >= 1000*1000 and x < 1000*1000*1000 : value = round(x / (1000 * 1000), 2) ext = ' MB' elif x >= 1000*1000*1000: value = round(x … -
How to re-save a ModelForm?
I instantiate a ModelForm based on some input data, and then I generate/fetch some new data based on that input data, and want to refresh my ModelForm with the new data and then save it. I would rather like to use ModelForms as much as possible and avoid having to use the associated Model object directly when it comes to saving/validation and other stuff (e.g. white-space trimming). One solution would be to instantiate another new ModelForm based on the new (and the previous) data and feeding it the generated Model object via instance argument, then save() again, but, is there another better/neater/more optimized way, without having to instantiate two ModelForms? [app].models.py: from django.db import models from .custom_fields import HTTPURLField from .function_validators import validate_md5 class Snapshot(models.Model): url = HTTPURLField(max_length=1999) content_hash = models.CharField(max_length=32, default='00000000000000000000000000000000', validators=[validate_md5]) timestamp = models.DateTimeField(auto_now=True) [app].forms.py: from django import forms from .models import Snapshot class SnapshotModelForm(forms.ModelForm): class Meta: model = Snapshot fields = ('url', 'content_hash') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['content_hash'].required = False [app].views.py: from django.http import HttpResponse from .forms import SnapshotModelForm def index(request): snapshot_form = SnapshotModelForm( data={'url': ' http://www.baidu.com/ '}) try: model_instance = snapshot_form.save(commit=False) generated_new_content_hash = ' 21111111121111111111111111111111 ' snapshot_form2 = SnapshotModelForm(instance=model_instance, data={'url': model_instance.url, 'content_hash': generated_new_content_hash }) … -
'corsheaders' could not be found but it is installed
I am trying to add the cors header as instructed by https://pypi.org/project/django-cors-headers/ However, when I try to run the server i get 'Module not found: corsheaders', even though it is installed. Any idea what could be wrong? settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'api', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', "corsheaders.middleware.CorsMiddleware", 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True -
Graphene_django can not use <class 'taggit.managers.TaggableManager'> field
the best way to used tagged.managers.TaggableManager with Graphql graphene_django? where I try to use a model with taggableManager Field, Graphql displays the following error: Don't know how to convert the Django field app.Asset.keywords (<class 'taggit.managers.TaggableManager'>) -
Cannot upload image to server
I am trying to upload image to the server. I received Imagename (string) and Imagefile (multipart) from android, Imagename is successfully saved with below algorithm but Imagefile wasn't. I think the problem is the column name of image figure is not imgfigure but "Character". However, @Part("imgfigure") imgfigure : MultipartBody.Part gives me an error. What should I do? Here is the code below, @view.py @api_view(['POST']) def Createtest(request): if request.method == "POST": serializer = FullSerializer(request.POST, request.FILES) if serializer.is_valid(): serializer.save() return JsonResponse({'code':'0000', 'msg': 'saved'}, status=200) return JsonResponse({'code':'1001', 'msg': 'failed'}, status=200) @serializer.py class FullSerializer(forms.ModelForm): class Meta: model = Character fields = ('imgname','imgfigure') @model.py class Character(models.Model): imgname = models.TextField(max_length=20) imgfigure = models.ImageField(upload_to='Image/',blank=True, null=True) Here is the request data in Django //The result of request.POST = <QueryDict: {'imgname': ['"session1"']}> //The result of request.FILES = <MultiValueDict: {'character': [<InMemoryUploadedFile: haruRoll.jpg (image/*)>]}> Here is Retrofit service from Kotlin interface SessionCreateService { @Multipart @POST ("/character/create/") fun SessCreate( @Part("imgname") imgname:String, @Part imgfigure : MultipartBody.Part, ):Call<SessionCreate_o> //output } -
How to get many to many value in Django template
I have 2 app: authors_app and books_app Authors_app Models.py class Author(models.Model): name = models.CharField(max_length=250, unique=True) Books_app Models.py class Book(models.Model): author = models.ManyToManyField(Author, related_name='authors') Authors_app Views.py class AuthorBio(DetailView): model = Author template_name = 'author-bio.html' Problem I need to get all the book published by the author. In my template I try: {% for book in author.books.all %} ... {% endfor %} But this doesn't work Question How can I get all the books by the author -
How to update/change attribute in Django Class Based View Test
I created a mixin that requires an attribute to be added to a Class Based View (cbv) and it works as expected - but I'm having a tough time 'testing' that mixin specifically. Here is my test: class TestView(GroupRequiredMixin, View): group_required = ("test_group",) raise_exception = True def get(self, request): return HttpResponse("OK") class GroupRequiredMixinTest(TestCase): def setUp(self): group = GroupFactory(name="test_group") self.user = UserFactory(groups=(group,)) def test_view_without_group_required_improperly_configured(self): rfactory = RequestFactory() request = rfactory.get("/fake-path") request.user = self.user view = TestView() view.group_required = None with self.assertRaises(ImproperlyConfigured): view.as_view()(request) This test errors with this message: AttributeError: This method is available only on the class, not on instances. What is the 'appropriate' way to test this? Should I be setting up a unique class for each situation I want to test? Or is there a way I can dynamically change that attribute on an instance like in my test that fails?