Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset filtering not providing expected behavior
I have an app taking inputs from a user on the front end. The functionality I'm trying to implement should display all titles on the front end that have reviews <=0, or display NULL values in the database. reviewsign_high = 'lte' if reviewinput_high == '0': review_kwargs = { 'amz_reviews__isnull': True, 'amz_reviews__{}'.format(reviewsign_high): float(reviewinput_high) } titles = titles.filter(**review_kwargs) However, I don't get any results back here. If I remove one parameter, i.e. 'amz_reviews__isnull': True, I do get all titles with reviews less than or equal to 0. Vice versa, if I remove 'amz_reviews__{}'.format(reviewsign_high): float(reviewinput_high), I get all titles with NULL reviews. But them together, displays 0 results. Any ideas on a solution here? Thanks! -
changing color of a particular string in entire html document with Django
Suppose you have a word "day" in 100 sentences in your document. You can change the color of that word in the following way: <span style="color: #ff0000"> day </span> The problem is that you need to do it 100 times. I am using Django and I want to do it inside template with for loop. So, my problem is now to change the color of a string inside some sentence that I don't know what it will be. I tried with something like: def colored(sentence, string, color): if string not in sentence: return sentence else: colored_string = f'<span style="color: {color}"> {string} </span>' colored_string.join(sentence.split(string)) I thought that that will give me colored variable string, but that wasn't the case. It just returned the string '....<span....' without any including the same stuff. It just like it didn't recognized html at all. What is the correct way of solving the same problem? -
What does request.POST.get method return in Django?
What does request.POST.get("a") return while "a" is the reference to following html label for = "a">ADDED ITEMS:</label> <input hidden type="number" name="a" id="a"> def myfunc(): if request.method == "POST": a = request.POST.get("a"); obj = TransferedItems(item_id = a); obj.save(); return HttpResponse("sent") else: return HttpResponse("form submission failed") I am new at Django and I am unable to find what does request.POST.get return. Please guide me on my question. -
Why my code Django into HTMl variables didnt work
''' Im trying to get a variable into a html document with python and django ''' def nombrarVariables(request): nombre="juan" doc_externo=open("SeleccionGrafica2.html") template=Template(doc_externo.read()) doc_externo.close() contexto=Context({"variable": nombre}) documento=template.render(contexto) return HttpResponse(documento) -
how to get the instance of a newly created user in django function based view
i'm writing the logic in django where a newly created user would automatically get the free membership when they hit the signup button and right now, i know what to do but i don't know how to implement maybe becuase i don't have much experince with django. i defined an instance variable to store all the newly created information but i'm just stock and it keeps showing red underlined word in vsCode, Any help would be greatly appreciated views.py def register(request): reviews = Review.objects.filter(status='published') info = Announcements.objects.all() categories = Category.objects.all() if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') obj = request.user get_membership = Membership.objects.get(membership_type='Free') # error is showing "instance" is not access using visual studio code instance = UserMembership.objects.create(user=obj, membership=get_membership) messages.success(request, f'Account Successfully created for {username}! You can Login In Now') return redirect('userauths:login') elif request.user.is_authenticated: return redirect('elements:home') else: form = UserRegisterForm() context = { 'reviews': reviews, 'form': form, 'info': info, 'categories': categories } return render(request, 'userauths/register.html', context) traceback Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in … -
Image stored in media is not been displayed
when click on "yo" image is shown but when displayed through img tag its not appearing on webpage <a href="{{status.adv.url }}">yo</a> <img src="{{status.adv.url}}" width="250" height="250" alt="advertise"/> -
Is there any way to edit django template?
In the last part of the code there exists a for loop which helps in constructing the boostrap crousel , but to make the website responsive i need to remove that forloop . So is there any way achive responsiveness? <div class="carousel-item active"> {% for i in products %} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card align-items-center" style="width: 18rem;"> <img src='/media/{{i.image}}' class="card-img-top mt-2" alt="..."> <div class="card-body"> <h5 id="productName{{i.id}}" class="card-title">{{i.product_name}}</h5> <p id="productPrice{{i.id}}" class="card-text">₹ {{i.price}}</p> <span id='button{{i.id}}'> <div id='product{{i.id}}' class="btn btn-primary cart">Add to cart</div> </span> <a href="/shop/productView/{{i.id}}" id="quickView{{i.id}}" class="btn btn-primary ml-3">Quick view</a> </div> </div> </div> {% if forloop.counter|divisibleby:4 and forloop.counter > 0 and not forloop.last %} </div> <div class="carousel-item"> {% endif %} {% endfor %} </div> </div> -
Django - deployment Heroku, how to solve error server (500)? Cloudinary error?
I have a question about my deployment app Django on Heroku. Whenever it is Debug=False in the setting.py file, it returns Error server 500, and when True then it is, ok? It is with the collecstatic parameter? find below the setting file: Django settings for ecommerce project. Generated by 'django-admin startproject' using Django 3.2.8. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ import os from pathlib import Path import django_heroku import cloudinary.api import cloudinary_storage # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXXXXXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['ecom-beta-XXXXX.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store.apps.StoreConfig', 'cloudinary', 'cloudinary_storage', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'ecommerce.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'ecommerce.wsgi.application' # Database # … -
Adding data to form before it submits via Javascript in Django
I am working on an app in Django where the user puts in their address and submits it in a form. I need to get this form data, along with its corresponding lat/long, into the views and save it in a model. So, I have used Javascript to call a lat/long API before the form submits and then add that data to the form so all of the data (the address and the lat/long) gets submitted to the server. However, this newly inserted data by Javascript does not show up with the rest of the POST data when submitted. I am not sure why this is. Here is the JS code: const initiate_ride_form = document.querySelector("#initiate-ride-form"); if (initiate_ride_form != null) { document.querySelector("#start-ride-button").onclick = () => { // these are just predecided addresses to simplify the code and isolate this problem const origin = '20%20W%2034th%20St%2C%20New%20York%2C%20NY%2010001' const destination = '1600%20Pennsylvania%Avenue%20NW%2C%20Washington%2C%20DC%2020500'; fetch(`https://api.opencagedata.com/geocode/v1/json?q=${origin}&key=b45938af46624365b08b989268e79d5e`) // Put response into json form .then(response => response.json()) .then(data => { // get the lat and long and save them in variables console.log(data.results[0].geometry); const longitude_origin = data.results[0].geometry.lng; const latitude_origin = data.results[0].geometry.lat; // add the make the hidden input's value equal to the long var input_long_origin = document.querySelector("#from_long"); input_long_origin.value = longitude_origin; // … -
How do I make an upload pdf and make it render to my page in django?
Right now I just have it so that in the admin site when the admin writes out the form and clicks send it has a button that says view on the page and you click it, it brings you to a pdf. How do I make it so that the admin can just upload a pdf from the admin site and make it render for all the users? -
How to precache/load remote postgres DB in django/python for faster testing?
I am running django with a remote heroku hosted DB for testing. When developing locally/testing I am using the remote DB. Is there a way to precache/load the entire database locally so that I don't have to do network calls when running queries? Otherwise, I am using lru_cache in python for certain queries. Is there something I'm missing where I can just fetch the whole thing and cache it? -
two formsets in one view - django
i'm trying to implement two formset in one view , one of the formsets should be pop up modal form , class MobileCollection(models.Model): mobile = models.ForeignKey(ModelCategory,on_delete=models.PROTECT,related_name='model_category') qnt = models.IntegerField() price = models.DecimalField(decimal_places=3,max_digits=20) class Imei(models.Model): mobile = models.ForeignKey(MobileCollection,on_delete=models.PROTECT) imei = models.CharField(max_length=15,unique=True) serial_no = models.CharField(max_length=7,unique=True,blank=True,null=True) status = models.BooleanField(default=True) def __str__(self): return f'{self.mobile}-{self.imei}' in the page we adding new instance of MobileCollection , and each MobileCollection have its own set of imei , if qnt = 10 then we have to add 10 imei @login_required def create_collection(request): item_formset = mcollection(queryset=MobileCollection.objects.none()) imei_formset = imei_modelformset(queryset=Imei.objects.none(),prefix='imei') if request.POST: item_formset = mcollection(request.POST) imei_formset = imei_modelformset(request.POST,prefix='imei') if imei_formset.is_valid() and item_formset.is_valid() and request.user.is_superuser: for item in item_formset: item_obj = child.save(commit=False) item_obj.save() for imei in imei_formset: imei_obj = imei.save(commit=False) imei_obj.mobile = item_obj imei_obj.save() return JsonResponse({'success':True}) else: return JsonResponse({ 'success':False,'error_child_msg':item_formset.errors,'error_imei_msg':imei_formset.errors}) context = { 'item_formset':item_formset, 'imei_formset':imei_formset } return render(request,'storage/collection.html',context) but it only saves the last item entry and doesnt save imei , only its instance(from the item) will be saved these are my formsets mcollection = modelformset_factory( MobileCollection,form=MobileCollectionForm,fields= ['mobile','qnt','price'],can_delete=True,extra=1) imei_modelformset = modelformset_factory(Imei,form=ImeiForm,fields= ['imei'],extra=1,can_delete=True) const addNewRow = document.getElementById('add-more') const totalNewForms = document.getElementById('id_form-TOTAL_FORMS') addNewRow.addEventListener('click',add_new_row); function add_new_row(e){ if(e){ e.preventDefault(); } const currentFormClass = document.getElementsByClassName('child_forms_row') const countForms = currentFormClass.length const formCopyTarget = document.getElementById('form-lists') const empty_form = … -
Django Project - 'urlpatterns' = (syntax error - cannot assign to literal)....Please advise?
Django Project - 'urlpatterns' = (syntax error - cannot assign to literal)....Please advise? -
The included URLconf 'web_project.urls' does not appear to have any patterns in it
My Customer Apps urls.py ''' from django import urls from django.urls import path from django.urls.resolvers import URLPattern from .import views URLPattern = [ path('', views.base ,name= 'customer-base'), path('Hall/', views.Hall ,name= 'customer-Hall'), path('Food_item/', views.Food_item ,name= 'customer-food'), path('About_us/', views.About_us ,name= 'customer-about'), ] ''' My web_project urls.py ''' from django.contrib import admin from django.urls import path, include from django.urls.resolvers import URLPattern URLPattern = [ path('admin/', admin.site.urls), path('base/', include('customer.url')), ] ''' errors that are showing ''' Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\urls\resolvers.py", line 600, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Nawaf Bhatti\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\Nawaf Bhatti\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\utils\functional.py", line 48, … -
How to using two parameters in delete method of class GenericViewSet in Django
I'm newbie Django How can use 2 params on my url with delete method on django 3 My url config: API_VERSION = os.getenv('API_VERSION') API_ROOT = "grpz/" router = routers.DefaultRouter(trailing_slash=False) router.register(r'^groups/(?P<group_id>.)/users/(?P<user_id>.)', group_views.DeleteGroupViewSet) schema_view = get_schema_view( title='next_blog', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]) urlpatterns = [ path('admin', admin.site.urls), path('api_auth', include( 'rest_framework.urls', namespace='rest_framework')), path('docs', schema_view, name='docs'), path(API_ROOT, include(router.urls)), ] My class viewsets: class DeleteGroupViewSet(viewsets.GenericViewSet): queryset = Groups.objects.all() serializer_class = GroupSerializer permission_classes = (AllowAny,) def destroy(self, request, group_id, user_id): try: # user_id = self.kwargs['user_id'] # group_id = self.kwargs['group_id'] user = Users.objects.filter(user_id=user_id).first() if user is None: return Response({ 'msg': 'User is not exist', }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: user_owner_role_in_group = GroupHasUsers.objects.filter( group_id=group_id, user_id=user_id, role__name='owner' ) if user_owner_role_in_group.count() == 0: return Response({ 'msg': 'User is not a owner role' }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: Groups.objects.filter(id=group_id).delete() return Response({'msg': 'success'}, status=status.HTTP_200_OK) except Exception as e: return Response({ 'msg': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) Thanks all ! -
Accessing os files with django inside an electron application
I have a web application built with Django/React. I want to convert it to an electron app and am unsure if I need to refactor some of the backend code to node.js. Here is the relevant information: User needs to create a file with their own API token received from 3rd party. I would like to avoid sending their personal token to my server and want to keep it on their operating system. Django uses the token to query data from the 3rd party api. Django sends data back to front end. My question is, once the application is bundled as an electron app, can django access their api token and query the 3rd party api without hitting my server? Will the django code be run on the localhost (or can it) is I guess what I mean. Thanks, hope this is a valid SO question. -
Django modelformset not saving data. Returns empty list after calling cleaned_data
I have a problem with formset, its doesnt save. Console returns no errors but after calling print(formset.cleaned_data) it returns empty list. Standard form saves normally. This formset is for adding a service made to a car object. I couldnt find the answer online, maybe someone will help or find a better solution. models.py class Car(models.Model): FUEL = ( ('', '---------'), ('1', 'Gasoline'), ('2', 'Diesel'), ('3', 'Electric'), ('4', 'Hybrid'), ) client = models.ForeignKey(Client,on_delete=models.CASCADE, null=True, blank=True) car_make = models.ForeignKey(CarMake, on_delete=models.CASCADE) car_model = models.ForeignKey(CarModel, on_delete=CASCADE) fuel_type = models.CharField(max_length=15, choices=FUEL, default=None) engine = models.CharField(max_length=15) extra_info = models.TextField(max_length=300, verbose_name='Remarks', null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.client} | {self.car_make} {self.car_model}" class Meta: ordering = ('-date_updated',) class Service(models.Model): car_relation = models.ForeignKey(Car, on_delete=models.CASCADE) service_name = models.CharField(max_length=200, verbose_name='Service') service_price = models.CharField(verbose_name='Price', blank=True, null=True, max_length=20) def __str__(self): return self.service_name forms.py class AddServiceForm(forms.ModelForm): class Meta: model = models.Service fields = ['service_name'] class CarForm(forms.ModelForm): class Meta: model = models.Car fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['car_model'].queryset = models.CarModel.objects.none() # returns no value till "Make" field is chosen, will be negated in elif statement if 'car_make' in self.data: try: car_make_id = int(self.data.get('car_make')) self.fields['car_model'].queryset = models.CarModel.objects.filter(make_id=car_make_id).order_by('model_name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['car_model'].queryset = self.instance.car_make.carmodel_set.order_by('model_name') # … -
how to to check if a value exists in a multiselectfield with django templat language
I am using multiselectfield in the models so that a user can select multiple values and store in a column called sub_law_type. The values are gettting stored correctly in that column. Now in the html I have some conditions that are to be met for the judgement data to be displayed. All the other condtions are being checked correctly but I am confused as to how to check if a value exists in the sub_law_type. here I want to check if the sub_law_type has the value 'ipc' in it then only display the judgement the code below is the way I wrote initially to check if the condition is true but this was not displaying any result {% if data.law_type == 'criminal' and data.sub_law_type.ipc and data.law_category == 'limitations' and data.court_type == 'The Supreme Court of India' %} then i tried writing it as below but even that was not displaying the correct result {% if data.law_type == 'criminal' and data.sub_law_type== 'ipc' and data.law_category == 'limitations' and data.court_type == 'The Supreme Court of India' %} Since both of them are not working I am confused how I should write it so tat i can get the result. models.py sub_type_of_law = ( … -
django model ImageFile upload through code/manually
I am writing a populate script in python to register users and registeration asks them to upload a picture. Now, to achieve it through code, I read various threads of stackoverflow and came up with the 'picture.save' code below to save an image to the ImageField where actually user uploads a image. Below is the snippet of code in my populate_dogpark.py file from django.core.files import File created, __ = Dog.objects.get_or_create(owner=dog['owner'], breed=dog['breed'], breedname=dog['breedname'], name=dog['name'], age=dog['age'], gender=dog['gender']) created.picture.save(dog['path'], File().read(), True) created.save() But, upon attempting to execute this command I get the following error: File "populate_dogpark.py", line 80, in create_dog created.picture.save(dog['path'], File().read(), True) TypeError: __init__() missing 1 required positional argument: 'file' (socialapp) What I want to achieve is that for the following field in my model, picture = models.ImageField(upload_to="dog_profile_picture", blank=True) I want the ImageField to automatically upload picture from the path to file from the static/images directory I will provide in dog['path']. I need help to resolve this error. Stack trace provided above. -
django user authenticate only returns None
i'm trying to create a simple API on Django, and this is my first. The class User get the AbstractUser, like this: from django.db import models from django.contrib.auth.models import AbstractUser class Usuario(AbstractUser): nome = models.CharField(max_length = 255) username = models.CharField(max_length=150, unique=True, blank=False, null=False, default="") nascimento = models.DateField() password = models.CharField(max_length=128, blank=False, null=False, default="") But when I try to authenticate, the method allways returns None. Why? I checked, on DataBase, and the Users are already there. from django.shortcuts import render, redirect from conta.models import Usuario import secrets from django.contrib.auth import authenticate, login def login_view(request): if request.method == "POST": user = request.POST.get("user") senha = request.POST.get("password") autenticador = authenticate(request, username=user, password=senha) if autenticador is None: context = {"error" : "Invalid username or password"} return render(request, "conta/tela_de_login.html", context) login(request, autenticador) redirect('/admin') return render(request, "conta/tela_de_login.html", {}) -
OpenCV camera issue with Django and Azure
I am new to using azure and django. During my project I'm having issues with the camera on my laptop. When running the code on my local system, it works completely fine (the camera opens, detects everything and does what it needs to). So after that I uploaded my code on azure using a virtual machine to get it up and running. The code is uploaded fine and everything works fine but the camera doesn't switch on (a broken image box appears) when I go to the page where the camera is supposed to run. What can I do to fix this? I uploaded the code using azure web app to look at the error logs, errors like this appear too- [ERROR] import gi [ERROR] ModuleNotFoundError: No module named 'gi' [ERROR] [ WARN:0] global /tmp/pip-req-build-khv2fx3p/opencv/modules/videoio/src/cap_v4l.cpp (890) open VIDEOIO(V4L2:/dev/video0): can't open camera by index [ERROR] INFO: Created TensorFlow Lite XNNPACK delegate for CPU. [ERROR] cv2.error: OpenCV(4.5.4) /tmp/pip-req-build-khv2fx3p/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor' (I do not get these errors on my local system, only when I upload it) (Also the audio clip that is supposed to play doesn't work either, does that have something to do with server configuration?) I … -
How to get model-objects using other models in django
I need if user requests to get the following page the response of the request would be the page containing specific posts made by the users who is followed by the user who requests. I thought to do some actions to do this: Get the requester Get the users who are followed by the requester Get the posts created by the users the who are being followed In my models.py: class User(AbstractUser): image_url = models.CharField(max_length=5000, null=True) class Follow(models.Model): follower = models.ForeignKey( User, on_delete=models.PROTECT, related_name="follower") following = models.ForeignKey( User, on_delete=models.PROTECT, related_name='following') class Post(models.Model): content = models.CharField(max_length=140) date_created = models.DateTimeField(auto_now_add=True) poster = models.ForeignKey(User, on_delete=models.CASCADE) In my views.py: def following_page(request, username): user = User.objects.get(username=username) f = user.following.all() posts = Post.objects.filter(poster=f.following) posts = posts.order_by("-date_created").all() return render(request, 'network/index.html', { "posts": posts }) It says AttributeError 'QuerySet' object has no attribute 'following' Should I have to change the model? How to solve the problem? -
Djongo ArrayReferenceField in Django Admin Issue
I have used the below models class ProductVariation(Trackable): """Product Variation""" variation_name = models.TextField() storage = models.CharField(max_length=127) color = models.CharField(max_length=255) ram = models.CharField(max_length=255) price = models.CharField(max_length=31) variation_images = models.ArrayReferenceField(to=GenericImages, null=True, on_delete=models.CASCADE) objects = models.DjongoManager() class Product(Trackable): """Product master""" product_model = models.CharField(max_length=255) processor = models.CharField(max_length=127) screen_size = models.CharField(max_length=127) variation = models.ArrayReferenceField(to=ProductVariation, on_delete=models.CASCADE, related_name='variants') product_metadata = models.JSONField(blank=True) ##Foreignkey category = models.ManyToManyField('Category') # sub_category = models.ManyToManyField('SubCategory') brand = models.ForeignKey(Brand, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.long_name and this is my admin.py for product model class ProductAdmin(admin.ModelAdmin): list_display = ('product_model', 'created_at',) I'm not able to add the variations in the django admin for Product form(i.e there is no add symbol like for categories in front of variations field)Refer the Image Versions: Python: 3.7 Django: 3.2.6 djongo: 1.3.6 Please help me with this. Thanks! -
How to convert UIImage to data that Django understands
It may seem like a stupid question, but I have a problem with UIImage. My app communicates with my Django server, and for that, I'm using Alamofire. I need to pass an image, but I don't know how to convert UIImage to appropriate data so that the server can understand. My code currently looks like this: let param = ["image": image] // <- 'image' is a UIImage AF.request(method: .post, parameters: param) // and so on The server says the form is invalid. For my server, I'm using a form looks like this: class UploadImageForScanForm(forms.Form): image = forms.ImageField() How can I convert a UIImage to an appropriate data format so that my Django server can understand it and do its work with it? -
How to filter users first name from related model in Django filter form
I want to filter users first name from my profile model using Django filter this is my profile model in models.py. from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) total_members = models.CharField(max_length=500, blank=True) ...other fields and this is my filters.py import django_filters from .models import Profile class ProfileFilter(django_filters.FilterSet): class Meta: model = Profile fields = '__all__' in this when I add my form to template it gives me select tag with all users username and I don't want that because if user want to filter user by it's name than they can search by their name instead of looking in drop down.Please help me (: