Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Javascript function on input elements in a for loop. Django
I'm working on a Django form that can calculate values in real time. I would like the javascript function to work for all rows which consists of 3 input fields each. I tried assigning each input field with an id followed by a forloop counter. I also looped through the function hoping that it will work for all the ids, a1,a2,a3... b1,b2,b3... c1,c2,c3... However, the function only worked for the last row. Here's the javascript I used: <script type="text/javascript"> for (i = 0; i < {{ total_rows|safe }}; i++) { $('input').keyup(function(){ var firstValue = Number($('#a'+i).val()); var secondValue = Number($('#b'+i).val()); document.getElementById('c'+i).value = firstValue * secondValue; }); } </script> Here's my template: <form> {% csrf_token %} <table> <thead> <tr> <th>Quantity</th> <th>Unit Price</th> <th>Amount</th> </tr> </thead> <tbody> {% for item, amount in loop_list %} <tr> <td> <input id="a{{ forloop.counter }}" type="text" class="form-control" placeholder="" name="quantity1" value="{{ item.quantity }}"> </td> <td> <input id="b{{ forloop.counter }}" type="text" class="form-control" placeholder="" name="unit_price1" value="{{ item.product.unit_price }}"> </td> <td> <input id="c{{ forloop.counter }}" type="text" class="form-control" placeholder="{{ amount }}" readonly> </td> </tr> {% endfor %} </tbody> </table> </form> -
Django does not load static files after opening a new window with JS
I have a Django app, and seems like I did something wrong with static files. My static files works as needed across all project, except one moment. I have following js function: function sendForm() { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200) { window.open('/url/to/open/' + xhr.responseText); } }; let info = document.querySelector("#parameters"); let data = new FormData(info); xhr.open("POST", "/url/to/open/", true); xhr.setRequestHeader("X-CSRFToken", document.getElementsByName("csrfmiddlewaretoken")[0].value); xhr.send(data) } This code works, and new tab loads all the static files it has. But if I do Ctrl + F5 on any page I will see [01/Apr/2020 05:53:42] "GET /static/images/logo.png HTTP/1.1" 404 1669 [01/Apr/2020 05:53:42] "GET /static/js/scripts.js HTTP/1.1" 404 1663 [01/Apr/2020 05:53:42] "GET /static/icons/cat.png HTTP/1.1" 404 1669 [01/Apr/2020 05:53:42] "GET /static/css/style.css HTTP/1.1" 404 1663 [01/Apr/2020 05:53:42] "GET /static/icons/dog.png HTTP/1.1" 404 1675 [01/Apr/2020 05:53:42] "GET /static/icons/butterfly.png HTTP/1.1" 404 1678 [01/Apr/2020 05:53:43] "GET /static/css/style.css HTTP/1.1" 404 1663 [01/Apr/2020 05:53:43] "GET /static/js/scripts.js HTTP/1.1" 404 1663 [01/Apr/2020 05:53:43] "GET /static/favicon.ico HTTP/1.1" 404 1657 which means Django lost somewhere my static files. Since this moment static files will always return 404. Can you explain what does this happen and how to fix it? Template with sendForm() caller. This template does … -
ValueError at /shop/checkout/ Incorrect AES key length (22 bytes)
This code give invalid AES key length error in server side. How can I correct it? Server gets created after that when a msg is sent from client side server gets error. Server code: File "/home/saurabh/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/saurabh/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/saurabh/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/saurabh/project/myshop/shopingsite/shop/views.py", line 126, in checkout param_dict['CHECKSUMHASH'] = Checksum.generate_checksum(param_dict, MERCHANT_KEY) File "/home/saurabh/project/myshop/shopingsite/PayTm/Checksum.py", line 24, in generate_checksum return encode(hash_string, IV, merchant_key) File "/home/saurabh/project/myshop/shopingsite/PayTm/Checksum.py", line 103, in encode c = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8')) File "/home/saurabh/.local/lib/python3.6/site-packages/Crypto/Cipher/AES.py", line 232, in new return _create_cipher(sys.modules[name], key, mode, *args, **kwargs) File "/home/saurabh/.local/lib/python3.6/site-packages/Crypto/Cipher/init.py", line 79, in _create_cipher return modes[mode](factory, **kwargs) File "/home/saurabh/.local/lib/python3.6/site-packages/Crypto/Cipher/_mode_cbc.py", line 274, in _create_cbc_cipher cipher_state = factory._create_base_cipher(kwargs) File "/home/saurabh/.local/lib/python3.6/site-packages/Crypto/Cipher/AES.py", line 93, in _create_base_cipher raise ValueError("Incorrect AES key length (%d bytes)" % len(key)) ValueError: Incorrect AES key length (22 bytes) [01/Apr/2020 06:33:08] "POST /shop/checkout/ HTTP/1.1" 500 101430 -
Python Django get variable problem using in django-tables2
In this project, I need to take the pk in views and use them in tables.py. What should I do to use the variables of views in tables.py? I want to get the var1.pk using in modelB.objects.get(id=3) at tables.py Can anyone help ? and sorry for my poor English views.py def create_page(request, pk): var1 = get_object_or_404(modelB, pk=pk) form = CreateForm(request.POST or None) profile_id_list = [] success_id_list = [] fail_id_list = [] if request.method == 'POST': if form.is_valid(): profile_id = request.POST['profile_id'].split(',') profile_id_list = profile_id for num in profile_id: if modelA.objects.get(id=num).check_function(modelB.objects.get(id=var1.pk)): modelC.objects.create( A=modelA.objects.get(id=num), B=modelB.objects.get(id=royalty.pk), ) success_id_list.append(num) else: fail_id_list.append(num) form = RoyaltyAuthorizerCreateForm() table_success = TableA(modelA.objects.filter(id__in=success_id_list)) table_fail = TableB(modelB.objects.filter(id__in=fail_id_list)) context = {Skip} return render(request, template_path, context) tables.py from django.utils.html import format_html from django.utils.translation import ugettext_lazy as _ from svapps.dps.models import UserProfile, IncomeProject from svapps.pa.tables.base import BaseTable import django_tables2 as tables class RoyaltyAuthorizerCreateFailListTable(BaseTable): A = tables.Column() B = tables.Column() C = tables.Column() fail_reason = tables.Column(, empty_values=(), orderable=False) operation = tables.TemplateColumn(template_name='path', orderable=False) def render_fail_reason(self, record): html_str = '' field_names = ['A','B', 'C'......] for field_name in field_names: if getattr(`modelB.objects.get(id=3)`, field_name): if not getattr(record, field_name): html = format_html('<span class="badge badge-pill badge-light mr-1 mb-1">{}</span>', IncomeProject._meta.get_field(field_name).verbose_name) else: html = '' html_str = format_html('{} {}', html_str, html) return html_str class Meta(BaseTable.Meta): … -
Django ORM Inheritance: You are trying to add a non-nullable field 'dish_ptr' to [...] without a default
I am working on a restaurant app (and new to Django/Python). I want to have a parent class Dish that will contain some counter or ID that increments for every instance of a child class of Dish. The instances are dishes like Pizza, Pasta, etc with different characteristics and relations. I'm trying to make Dish concrete, because in that case I reckon I just access Dish's PK and that will give each menu-item a Dish-ID. However, I don't know how to correctly fix the errors I come across: You are trying to add a non-nullable field 'pasta_ptr'. Here are the relevant code snippets: class Dish(models.Model): pass # should automatically generate PK, right? class Pasta(Dish): name = models.CharField(max_length=64, primary_key=True) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return f"{self.name}, price: ${self.price}" class Pizza(Dish): sizestyle = models.CharField(max_length=4, choices=SIZESTYLE_CHOICES, default=SMALL_REGULAR) topping_count = models.IntegerField(default=0, validators=[MaxValueValidator(5), MinValueValidator(0)]) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return f"Price for {self.sizestyle} pizza with {self.topping_count} toppings: ${self.price}" class Sub(Dish): name = models.CharField(max_length=64, primary_key=True) price_category = models.ForeignKey(SubPrice, on_delete=models.DO_NOTHING, related_name="sub_price_category") def __str__(self): return f"{self.name}, Price Category: {self.price_category}" class Platter(Dish): name = models.CharField(max_length=64, primary_key=True) price_large = models.DecimalField(max_digits=6, decimal_places=2, default=0) price_small = models.DecimalField(max_digits=6, decimal_places=2, default=0) def __str__(self): return f"{self.name} price: Large ${self.price_large}, Small ${self.price_small}" -
how to take sum of each ObjectList, DJANGO
thanks for your time: i am trying to get the sum of all Pets separeted by People: models.py: class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='person') birthday = models.DateField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.user) class Pets(models.Model): pessoa = models.ForeignKey(People, on_delete=models.CASCADE, related_name='peop') nome = models.CharField(max_length=150) custo = models.DecimalField(max_digits=7, decimal_places=2) tipo = models.SmallIntegerField() def __str__(self): return '%s - %s' % (self.pessoa, self.nome) views.py q7 = People.objects.all() for p in q7: q8 = Pets.objects.filter(pessoa=p) l=[] for pet in q8: custa = pet.custo l.append(custa) custo_total2 = sum(l) its returning me just the sum of the last People.Pets query i guess i'm not understanding the logic -
I can not Dockerize MySQL and Django App using docker-compose
I am trying to Dockerize mysql and Django app but facing a lot of issues can you help me with it. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'trying', 'USER': 'root', 'PASSWORD': '159753', 'HOST': 'db', 'PORT': '3306', } } Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /my_app_dir WORKDIR /my_app_dir ADD requirements.txt /my_app_dir/ RUN pip install -r requirements.txt ADD . /my_app_dir/ docker-compose.yml version: '3' services: db: image: mysql:5.7 ports: - '3305:3306' environment: MYSQL_DATABASE: 'trying' MYSQL_USER: 'root' MYSQL_PASSWORD: '159753' MYSQL_ROOT_PASSWORD: '159753' web: build: . command: "python trying/manage.py runserver 0.0.0.0:8000" volumes: - .:/my_app_dir ports: - "8000:8000" depends_on: - db I was running docker-compose run web trying\manage.py migrate but getting a lot of errors error is I was running the command and getting this error I want my container to connect with my MySQL server and work perfectly but I am facing issues please help Traceback (most recent call last): File ".\trying\manage.py", line 21, in <module> main() File ".\trying\manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 341, in run_from_argv connections.close_all() File "/usr/local/lib/python3.6/site-packages/django/db/utils.py", line 225, in close_all for alias in self: File "/usr/local/lib/python3.6/site-packages/django/db/utils.py", line 219, in __iter__ … -
Getting 'No module named 'XYZ' error' while running Django application
I just moved from Django 1.8 to 3.0, and also upgraded python 2.7 to 3.7 simultaneously for my project. Upon python manage.py runserver, I am getting the response File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked No module named "XYZ" where XYZ is a connection mentioned in my Database configuration. Any clue how to resolve this error? -
React & DRF - no cookies being saved
I'm trying to implement session based authentication the first time. I'm using React and Django Rest Framework, but there's some weird thing I don't understand. I have a pretty standart Login view, so I send POST request from React with username and password, I got response with status 200, I can see cookies in the response with Chrome developer tools. But these cookies aren't being saved. If I do the same POST request with Rest plugin for Chrome - it saves them. Maybe I'm missing something here since it's my first time? Or should I save it manually somehow? So that's my request with axios, maybe I need to add something here: const sendLogin = () => { if (login && password) { axios.post(SERVER_ADDRESS + 'login/', {username: login, password: password}) .then((response) => { if (response.status !== 200) { handleClick(); } else { history.push('/'); } }) } } -
jCarousel (connected carousels) with django
I'm trying to make a dynamic jCarousel pulling images from DB, but I don't know how to get it to work, because the thumbnails are not displaying nor the next images on the carousel, the thumbnails were not working before I added the "if" statements <!--jCarousel--> <div class="wrapper"> <div class="connected-carousels"> <div class="stage"> <div class="carousel carousel-stage" data-jcarousel="true"> <ul> <li><img src="{{ property.main_photo.url }}" width="600" height="400" alt=""> </li> {% if property.photo_1 %} <li><img src="{{ property.photo_1.url }}" width="600" height="400" alt=""> </li> {% endif %} {% if property.photo_2 %} <li><img src="{{ property.photo_2.url }}" width="600" height="400" alt=""> </li> {% endif %} {% if property.photo_3 %} <li><img src="{{ property.photo_3.url }}" width="600" height="400" alt=""> </li> {% endif %} {% if property.photo_4 %} <li><img src="{{ property.photo_4.url }}" width="600" height="400" alt=""> </li> {% endif %} {% if property.photo_5 %} <li><img src="{{ property.photo_5.url }}" width="600" height="400" alt=""> </li> {% endif %} </ul> </div> <p class="photo-credits"> <a href="#">credits</a> </p> <a href="#" class="prev prev-stage inactive" data-jcarouselcontrol="true"> <span>&lsaquo;</span></a> <a href="#" class="next next-stage" data-jcarouselcontrol="true"><span>&rsaquo; </span></a> </div> <div class="navigation"> <a href="#" class="prev prev-navigation inactive" data- jcarouselcontrol="true">&lsaquo;</a> <a href="#" class="next next-navigation" data-jcarouselcontrol="true">&rsaquo;</a> <div class="carousel carousel-navigation" data-jcarousel="true"> <ul> <li data-jcarouselcontrol="true" class="active"><img src="{{ property.main_photo.url }}" width="50" height="50" alt=""></li> {% if property.photo_1 %} <li data-jcarouselcontrol="true" class="active"><img src="{{ property.photo_1.url }}" width="50" … -
postfix with django send mail
I have vps on ovh and installed postfix and it's work but i can't send mail with django using postfix and this id django mail settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'localhost' EMAIL_PORT = 25 EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = False and this is how i try to send mail from radio import settings from django.core.mail import EmailMultiAlternatives, send_mail def home(request): if 'requestSong' in request.POST: form = RequestSongForm(request.POST) if form.is_valid(): form.save() send_mail( 'Thank you', 'Hello, thank you for contacting radio-active we hope That you\'ve liked our radio,please send us your feedback and suggestions for the radio and wait for our reply ☺️.', 'root@radio-active.co', ['ahmed.rabea.smaha@gmail.com'], fail_silently=True ) -
writing tests and doc at the same time django rest framework
There is something called Spring Rest Docs in java where you can write api tests and generate doc at the same time Is there such a test driven document generation framework for django rest framework? -
Django modify FileField input button and label in Django form
I am trying to get rid of the regular file upload view by default in a Django formset, my approach is right now to hide the input file and then use a label and make that label clickable to upload file, however, right now after clicking on my label can be uploaded, I am using pure CSS for this current my html template is: HTML FORM <form method="POST" data-url="{% url 'home:post-create' %}" class="post-create-form"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" >Create a Post</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" style="overflow-y: auto;"> {{ form|crispy }} <button type="button" id="show-image-upload-inputs" class="btn btn-sm mr-auto btn-primary pb-1"> <span><i class="fas fa-camera"></i></span> </button> <div id="image-upload-div" class="mt-1 mx-1" style="display: none;"> <div class="d-flex justify-content-center"> {% for a_form in formset %} <div class="pl-1"> <label for="file"><i class="mt-2 fas fa-plus fa-5x"></i></label> {{ a_form }} </div> {% endfor %} </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Post</button> </div> </form> <style> input[type='file'] { display: none; } label[for='file'] { padding-left: 2px; cursor: pointer; background-color: rgb(212, 231, 238); border: 1em; border-radius: 10px; width: 6em; height: 6em; text-align: center; opacity: 0.5; color:lightblue; } </style> Django View @login_required def post_create(request): data = dict() ImageFormset = modelformset_factory(Images,form=ImageForm,extra=4) … -
filter by polygon draw in geodjango
Lets say user draw polygon and request to backend for filtration. As I can filter by bounding box but Can geodjango queryset filter within the draw area ? For instance, I have object with data in multilinestring field. class Datasets(models.Model): name = models.CharField(max_length=100) multipoint = models.MultiPointField(blank=True, null=True, srid=4326) multilinestring = models.MultiLineStringField(srid=4326, blank=True, null=True) multipoly = models.MultiPolygonField(blank=True, null=True, srid=4326) objects = GeoManager() -
Custom Django Channels middleware not finishing processing before Websocket connects
I have an existing WSGI application which I'm adding Django Channels to to give websocket functionality. I created a consumer using WebsocketConsumer, added the custom middleware into the routing file, and implemented a basic version of pulling the token from the incoming connection request. I can successfully print the token that's in the database, so I know the correct information is passing. I can connect to the socket, but it always comes back as being an anonymous user within the scope. It seems that the get_user_from_token function is not getting a chance to execute before the connect function executes, because all of the prints within the __call__ function of the TokenAuthMiddleware class are printed and none of the prints from the get_user_from_Token are printing. I tried switching the consumer to an async consumer, but that opened up a whole other set of problems that I couldn't figure out. I tried putting async in front of the __call__ and await in front of the function call, but that didn't work either. The current error I'm getting is: Exception inside application: 'coroutine' object has no attribute '_wrapped' File "C:\Users\PC\Envs\p3\lib\site-packages\channels\sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "C:\Users\PC\Envs\p3\lib\site-packages\channels\middleware.py", line 40, in … -
Python rest api without frameworks
Can we create Rest API using python without flask, django or any other frameworks? Which means Rest api using core python. -
How to resolve the error type object 'numpy.flatiter' has no attribute 'home'
I try running Jupyter from Pycharm on a Django application to be precise (I used pip install to install Jupyter)m but anytime I run my code I keep on getting the error message 'type object 'numpy.flatiter' has no attribute 'home' '. Please would really need help on how to resolve this issue -
Django AllAuth 'NoneType' object has no attribute 'append'
I'm using Django (3.0.2) and django-allauth (0.41.0) and am getting this error when a user enters the wrong password. I've got both django and all auth running on a different project and this doesn't happen. Internal Server Error: /account/login/ AttributeError at /account/login/ 'NoneType' object has no attribute 'append' Request Method: POST Request URL: https://www.podpage.com/account/login/ Django Version: 3.0.2 Python Executable: /app/.heroku/python/bin/python Python Version: 3.7.6 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python37.zip', '/app/.heroku/python/lib/python3.7', '/app/.heroku/python/lib/python3.7/lib-dynload', '/app/.heroku/python/lib/python3.7/site-packages', '/app/.heroku/src/redwoodlabs', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf'] Server time: Tue, 31 Mar 2020 19:13:05 -0700 csrfmiddlewaretoken = 'Jr4mBrAGlS6dPzADgrj4HaOA2iNtwTG2HQVbL1pTyK1L4lnCSl5mMwkiXDEhKesP' login = '[removed]' password = '********************' FILES: No FILES data I dont even know where to start with troubleshooting this. -
Django custom form not loading in modelformset_factory on html template
I am trying to use my custom form in modelformset_factory but when I set the 'form' attribute in modelformset_factory to my custom form nothing is being displayed. I looked at the documentation and I cannot find what is causing my custom form not to load. this is view: @login_required def post_create(request): data = dict() ImageFormset = modelformset_factory(Images,form=ImageForm,extra=4) if request.method == 'POST': form = PostForm(request.POST) formset = ImageFormset(request.POST or None, request.FILES or None) if form.is_valid(): post = form.save(False) post.author = request.user #post.likes = None post.save() for f in formset: try: i = Images(posts=post, image=f.cleaned_data['image']) i.save() except Exception as e: break data['form_is_valid'] = True posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) else: data['form_is_valid'] = False else: form = PostForm formset = ImageFormset(queryset=Images.objects.none()) context = { 'form':form, 'formset':formset, } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) this is my custom form: class ImageForm(forms.ModelForm): image = forms.FileField( label='', widget = forms.FileInput( attrs={ 'style':'display: none;', 'class':'form-control', 'required': False})) class Meta: model = Images fields = ('image', ) And this is what im using to load the formset: {{ formset }} Appreciate all the help in advance! -
How to check if a Django arrayfield has data
I have a Django model for articles with an array field that sometimes has ids. id_list = ArrayField(models.CharField(max_length=10000), blank=True, null=True) I want to write a query that finds all the article objects that have data in the id_list. I tried the following, but it did not work. Article.objects.filter(id_list__isnull=False) What is the correct way to write this? Thank you. -
How can I make a button pull a specific piece of data from the database?
I am creating a restaurant web app using Django and Python. I am trying to use buttons to select menu items to be added to the order, and displayed in a text area along with their prices. Thanks! Here is the code for this section: HTML: <div class="row"> {% for Product in show_menu %} <div class="col-sm-5" style= "color:#EAEAEA"> <button type = "submit" class="btn btn-info btn-md" onclick = "input()">{{ Product.name }}: ${{ Product.price }}</button> <br><br><br> </div> {% endfor %} </div> <label for="order"><h2 style= "color:#EAEAEA"><u>Order Details</u></h2></label> <br> <form> <textarea readonly class="fixed-right" id="order" name="order" rows="10" cols="80"> </textarea> </form> Views.py: class HomeView(ListView): model = Product template_name = 'mis446/home.html' context_object_name = 'show_menu' Models.py: class Product(models.Model): name = models.CharField(max_length=100) price = models.IntegerField() def __str__(self): return self.name -
Second image not saving with serializer
I have 2 models that looks like this: class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=120) class ChoiceImage(models.Model): choice = models.OneToOneField(Choice, on_delete=models.CASCADE, null=True) img = models.ImageField(upload_to='some-path/') A serializer for the ChoiceImage that looks like this: class ChoiceImageSerializer(serializers.ModelSerializer): img = Base64ImageField() class Meta: model = ChoiceImage fields = ('img',) And a ChoiceSerializer that looks like this: class CreateChoiceSerializer(serializers.ModelSerializer): choiceimage = ChoiceImageSerializer(many=False, required=False) class Meta: model = Choice fields = ('choice', 'choiceimage') def create(self, validated_data): image_uploaded = validated_data.get("choiceimage") if not image_uploaded["img"]: q = validated_data.get("question") if not q.choice_set.exists(): raise APIException("You must upload either an image or a cover.") else: img = q.choice_set.all()[0].choiceimage.img img2 = slice_image(img) validated_data["choiceimage"]["img"] = img2 image_validated_data = validated_data.pop('choiceimage') choice = Choice.objects.create(**validated_data) image_serializer = self.fields['choiceimage'] image_validated_data['choice'] = choice image_serializer.create(image_validated_data) Basically, the intention is this: A user creates 2 choices. If the user provides no image to the choices, then return an error. Else if the user provides only one image, split the image in half. Save one half to the first choice and the second half to the second choice. Lastly, if two images are uploaded then ignore the split image logic. My logic works fine with no image and two images. However, when I submit only one image, the … -
running user input through python script and returning output on django site
new python/django user here. i'm trying to set up a webpage that takes user input (e.g., an address) into a form, then passes it through a python script (in a separate.py file) before returning an output to the same webpage (e.g., the nearest traffic light). how would i go about making the connection between my views.py file and my script.py file in django? simplified code: views.py file input = form.cleaned_data.get('enter_address') script.py file print(input) -
Traversing a ManyToMany relationship to add to context in a Django DetailView
I asked a similar question recently about a different project. In that case (see Traverse multiple foreign keys in Django DetailView), I was able to follow the flow of Foreign Keys to make the needed connection when defining the view. In this case I need to traverse through a ManyToMany junction table, and I'm stymied. Here's an ER diagram of the relevant portion of my model. ┌────────────┐ ┌────────────┐ ┌───────────────┐ ┌────────────┐ │ │ ╱│ │ ╱│ │╲ │ │ │ Company │─────┼──│ Product │────┼──│ PersonProduct │──┼────│ Person │ │ │ ╲│ │ ╲│ │╱ │ │ └────────────┘ └────────────┘ └───────────────┘ └────────────┘ The purpose of this web site is to connect professional archers with the equipment and companies that sponsor them and display those connections. In this particular case, I have a detail view for a company. I've successful set it up for display all the products that the company sells. Now I want to display a list of all the archers that use one or more products from that company. I can't figure out how to span all the way from the company to the individuals who use those products. Here's the model, view, and template I'm working with. # models.py from … -
Django fetch firebase User UID
I'm using Pyrebase to fetch data from firebase in Django and so far it seems to be able to do everything but for some reason, I can't fetch the User UID from the authentication page in firebase. This is necessary for me to be able to do as all my user database nodes are save under the User UID from here. Here is my current attempt but the idToken doesn't return the User UID token = user['idToken'] print(token)