Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Authenticate two parameters in Django Rest Framework
I built a simple api endpoint using Django Rest Framework where, in order to see the endpoint's data, the user needs to input a public key and a secret key. Here is what i did: class CustomAuthentication(authentication.BaseAuthentication): def authenticate(self, request): # Get the username and password public = request.data.get('public', None) secret = request.data.get('secret', None) if not public or not secret: raise exceptions.AuthenticationFailed(_('No credentials provided.')) credentials = { get_user_model().USERNAME_FIELD: public, 'secret': secret } user = authenticate(**credentials) if user is None: raise exceptions.AuthenticationFailed(_('Invalid username/password.')) if not user.is_active: raise exceptions.AuthenticationFailed(_('User inactive or deleted.')) return (user, None) # authentication successful class My_View(viewsets.ModelViewSet): authentication_classes = (CustomAuthentication,) ... Now, i'm trying to access the endpoint like that: localhost/api/endpoint/?public=TEST&secret=TEST but every time i get "No credentials provided.". What do i need to do in order to be authenticated here? Thanks in advance! -
Djagno Rest Framework Serialization only reading in first column
I am trying to read in data from a list into a serializer. When the method is executed below it only appends the name of the dashboard to my widgets_value table. A little bit about widget_endpoint_post method it first takes in a request object that looks like request object {'dashboard_name': 'check_out', 'widgets': [{'position': {'top': 1, 'left': 1, 'width': 1, 'height': 1}, 'name': 0, 'content': {}, 'public_private': '', 'owner': '', 'title': ''}], 'type': 'public', 'user': 'Person_1'} The method below uses two serializers one to create a table to reference a dashboard another to save each dashboard's layout views.py @api_view(['POST']) def widget_endpoint_post(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) serializer=AddDashboardSerializer(data=request.data) data={} if serializer.is_valid(): account=serializer.save() body['dashboard_name']=account.dashboard_name body['user']=account.user body['type']=account.type print('test') else: data = serializer.errors print(body['widgets']) # print(body['widgets']) for x in range(len(body['widgets'])): print(body['widgets'][x]['position']['top']) serializer2=AddWidgitSerializer(data=request.data) data={} if serializer2.is_valid(): account=serializer2.save() body['dashboard_name'] = account.dashboard_name body['type'] = account.widget_type body['user'] = account.owner body['widgets'][x]['name'] = account.widget_name body['widgets'][x]['position']['top'] = account.top body['widgets'][x]['position']['left'] = account.left body['widgets'][x]['position']['width']=account.width body['widgets'][x]['position']['height']=account.height else: data=serializer.errors return Response('Dashboard saved') serializers.py class AddDashboardSerializer(serializers.ModelSerializer): dashboard_name=serializers.CharField(), user=serializers.CharField(), type=serializers.CharField(), class Meta: model= DashboardView fields=['dashboard_name','user','type'] class AddWidgitSerializer(serializers.ModelSerializer): dashboard_name=serializers.CharField(), widget_name=serializers.CharField(), top=serializers.CharField(), left=serializers.CharField(), height=serializers.CharField(), width=serializers.CharField(), widget_type=serializers.CharField, owner=serializers.CharField, class Meta: model=WidgetView fields=['dashboard_name','widget_name','top','left','height','width','widget_type','owner'] Below is the WidgetView table it only validates the name of the dashboard and I don't know why. -
Add custom attributes to Django models through mixins
I'm trying to add custom fields to models to be displayed as columns when inlined in admin. These fields are derived from a separate abstract model. I would like to compute these values at display time. Details below, issues tl;dr: For multiple ingredients, all rows are updated with the last computed value. When there are two ingredients 1 and 2, nutritional info for 2 is displayed for both ingredients. The column name displayed in the inline table is "Get nutrient value", and not 'calories', 'fats', etc. class Nutrition(models.Model): class Meta: abstract = True calories = models.DecimalField(max_digits=10, decimal_places=2, default=0) proteins = models.DecimalField(max_digits=10, decimal_places=2, default=0) fats = models.DecimalField(max_digits=10, decimal_places=2, default=0) carbohydrates = models.DecimalField(max_digits=10, decimal_places=2, default=0) class RecipeIngredient(..., NutritionMixin) ... size = models.DecimalField(max_digits=10, decimal_places=2, default=1) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) ... Ingredient stores the nutrition information for each ingredient, and RecipeIngredient.size stores the quantity in the current recipe. I define a mixin class, with the goal of adding a method for each field in Nutrition. from functools import partial from functools import update_wrapper def get_nutrient_value(base, derived, nutrient_name): ratio = nutrition.get_measurement_ratio(base, derived) return round(ratio*getattr(base, nutrient_name), 2) class NutritionMixin(object): def __init__(self, *args, **kwargs): for f in Nutrition._meta.fields: if self.ingredient_id: base = Ingredient.objects.get(id=self.ingredient_id) derived = self method … -
how to get the value in flask from Django?
I am beginner in Django & flask,I created a form in django and i want the value in the form to be passed to flask webservice where it takes the value and invoke the method and return back the outputs back to Django Where i can display the outputs.Below are the codes: views.py import django from django.shortcuts import render from django.http import HttpResponse import requests import math import json # Create your views here. def hi(request): return render(request,'hello/index.html') def output(request): n=int(request.POST.get("no")) response=requests.post("http://127.0.0.1:5000/") return render(request,'hello/index.html',{'out':response['out'],'value':response['value']}) index.html <!DOCTYPE html> <html> <body> <form action="output" method="post"> {% csrf_token %} Enter a number: <br/> <input type="number" name="no" value="0"> <br/> <input type="submit" ><br/> </form> <div> {{out}}</div> </body> </html> flask code from flask import Flask,jsonify,request import math import django app = Flask(__name__) @app.route('/',methods=['POST']) def index(): n=request.form["no"] r=[] for i in range(int(n)+1): r.append(i) a=[] for i in range(int(n)+1): com=math.factorial(int(n))/(math.factorial(r[i])*math.factorial(int(n)-r[i])) a.append(com) return jsonify({'out' : a,'value': r}) if __name__ == '__main__': app.run(debug=True) -
How do I make custom filters work in Django_filters?
So I've made this custom filter in filters.py with Django-filters and when I'm submitting the "YEAR CHOICE" the page refreshes but it doesn't work. I think my "year_filter_method" is not working also I want my pagination and filter system to work together. Any help would be really appreciated. Cheers! **Note it doesn't work with or without pagination. models.py from django.db import models import datetime YEAR_CHOICES = [] for r in range(2000, (datetime.datetime.now().year + 1)): YEAR_CHOICES.append((r, r)) class Music(models.Model): Song = models.CharField(max_length=100, blank=False) Year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year) def __str__(self): return self.Song filters.py import django_filters import datetime class MusicFilter(django_filters.FilterSet): YEARCHOICES = [] for r in range(2010, (datetime.datetime.now().year + 1)): YEARCHOICES.append((r, r)) year_filter = django_filters.ChoiceFilter(label="Year", choices=YEARCHOICES, method="year_filter_method") def year_filter_method(self, queryset): expression = Music.Year return queryset.filter(expression) views.py def music_page(request): #pagination & filter music = Music.objects.all().order_by('-id') music_filter = MusicFilter(request.GET, queryset=music) paginator = Paginator(music, 6) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) try: music = paginator.page(page_number) except PageNotAnInteger: music = paginator.page(1) except EmptyPage: music.paginator.page(paginator.num_pages) return render(request, template_name='main/music.html', context={'music': music, 'page_obj': page_obj, 'filter': music_filter}) filters.html {% load static %} <link rel="stylesheet" href="{% static 'main/filter.css' %}" type="text/css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <div class="container"> <form method="get"> <span class="label">{{filter.form}}</span> <span class="btn-search-handler"><button id="search_btn_id" type="submit">Search</button></span> </form> </div> music.html {% include 'main/includes/navbar.html' %} … -
Django: Multiplication of n Decimal Fields returns result with n*2 decimal places
I'm using django, and I have this model: class CartLine(DeletableModel): product = models.ForeignKey('Product', related_name='cart_lines', on_delete=do_nothing) cart = models.ForeignKey('Cart', related_name='lines', on_delete=do_nothing) quantity = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=_('Quantity')) @property def total_sum(self): return self.product.price * self.quantity class Meta: verbose_name = _('Cart Line') verbose_name_plural = _('Cart Lines') when I used the property total_sum in the template like {{ line.product.price }}, it return the result 300.0000. even when I tried with the filter tag floatformat like {{ line.product.price|floatformat:2 }} it returned the same value, it didn't format it. so I went to the python shell and tried it, and it returned the same value: >>> cartline.total_sum Decimal('300.0000') and when I changed the property to: @property def total_sum(self): return self.product.price * self.quantity * self.quantity and tested it in the console: cartline.total_sum Decimal('900.000000') it's like concatinating the decimal places... how can I fix that or work around that to limit the display to 2 decimal places when I do the multiplication or any other operation? -
How to allow configurable choices on a model of a django library without permanent migration changes?
I have a model in a library with a ChoicesField. Ideally I would want to allow people to define these choices in the settings of the apps that will use the library. This is not really possible as this would create/require a new migration in the library for every change made in the settings for every app!!! The django docs state in https://docs.djangoproject.com/en/dev/topics/migrations/ that is not possible to skip that model. Django will make migrations for any change to your models or fields - even options that don’t affect the database - as the only way it can reconstruct a field correctly is to have all the changes in the history, and you might need those options in some data migrations later on (for example, if you’ve set custom validators). What are the best alternatives? I could subclass ChoicesField to not trigger migrations, but it's not really the most elegant solution. Is there any nice alternative to do something similar? (I would also try to avoid having another model) -
Comment body for blog returning none
I'm including a comment section for a blog and the body of the comments return none instead of the comment entered. Point me in the direction of what I'm doing wrong. The views.py for the comment section def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) #List if active comments for this post comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': cd = form.cleaned_data #A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): #Create comment object but don't save to db yet new_comment = comment_form.save(commit=False) #Assign the current post to the comment new_comment.post = post #Save the comment to db new_comment.save() else: comment_form = CommentForm() return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form}) the models.py of the comment section class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=50) #user's name 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 f'comment by {self.name} on {self.post}', self.body In forms.py I'm using the ModelForm method like so: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body') detail.html {% with comments.count as total_comments %} <h2> {{ total_comments … -
Particular data is not shown in a class based rest API 's detail page .It shows only attributes with no values. What will I do?
I created a class based rest API successfully. The ProgramAPIView shows all program in the Django rest framework. But the ProgramDetailAPIView does not return the particular program's data in the restapi instead it just shows the attributes with no value. Program Api GET /program/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "programCode": "116", "pro_name": "B.Sc. Engg. in EEE", "url": "http://127.0.0.1:8000/program/116/", "DepartmentID": "http://127.0.0.1:8000/departments/2/" }, { "programCode": "115", "pro_name": "B.Sc. Engg. in CSE", "url": "http://127.0.0.1:8000/program/115/", "DepartmentID": "http://127.0.0.1:8000/departments/1/" } ] Program Detail Api GET /program/116/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "programCode": "", "pro_name": "", "DepartmentID": null -
how to add code in the github repository to the html template with django
I want to create a website which will show the code requested by user, taking it from my github repository. I am using django as a backend, but as i am completely beginner here in django, i don't know how to take code from repository and show it on html page. Please can anyone help me with this? -
Translator in an invented language django
I am currently coding my first website, which is a translator in an invented language. You input a random phrase and it should get translated in the invented language. Here's the code for the translation: class TranslatorView(View): template_name= 'main/translated.html' def post (self, request,*args, **kwargs): return render(request, self.template_name) def get (self, request, phrase, *args, **kwargs): phrase = request.POST.get('text', 'translation') translation = phrase for letter in phrase: if letter.lower() in "a": if letter.isupper(): translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper(): translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper(): translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper(): translation = translation + "C" else: translation = translation + "c" context = { 'translation': translation } return render(request,'main/translator.html', context) Template where you input the phrase: {% extends "base.html"%} {% block content%} <form action="{% url 'translated' %}" method="post">{% csrf_token %} <div class="form-group"> <center><h2 class = "display-3">TRANSLATE YOUR DNA CHAIN</h2></center> <br> <br> <textarea class="form-control" name='text' id="exampleFormControlTextarea1" rows="6"></textarea> <br> <button type='Submit' class= "btn btn-primary btn-lg btn-block">Translate</button> </div> </form> {% endblock content %} Template where the text should appear translated: {% … -
Is it possible to import in forms.py values from a view function Django? Is there another way to create functions in forms.py?
In my forms.py I have a section of code which gives me an error when I try to migrate for the first time. So I thought a good solution would be to change the location of the code. This is the problem section: tags = Tag.objects.all() choice_list_tags =[] for tag in tags: choice_list_tags.append(tag) Its role is to create a list which is used in widgets -> tags -> choices And this is my forms.py: from django import forms from .models import BlogPost, Category, Tag class SimpleForm(forms.Form): content = forms.CharField(widget=forms.Textarea) tags = forms.MultipleChoiceField() tags = Tag.objects.all() choice_list_tags =[] for tag in tags: choice_list_tags.append(tag) class BlogPostForm(forms.ModelForm): class Meta: model = BlogPost fields = ['title', 'content', 'preview_content', 'private', 'tags'] widgets ={ 'title': forms.TextInput(attrs={'class': 'form-control'}), 'content': forms.Textarea(attrs={'class': 'form-control'}), 'preview_content': forms.TextInput(attrs={'class': 'form-control'}), 'private': forms.CheckboxInput(attrs={'class': 'form-check-label'}), 'tags': forms.CheckboxSelectMultiple(choices=choice_list_tags, attrs={'class': 'form-check-label'}), } I tried to create in context_processors.py a function and import the values in forms.py but I dont know how. Iam not sure that's the solution either def tag_list(): tags = Tag.objects.all() choice_list_tags =[] for tag in tags: choice_list_tags.append(tag) return {'choice_list_tags':choice_list_tags} If there is any other solution to avoid the error for the first migration or to make the logic in a view and import it … -
Gunicorn + Django + Nginx configuration has upstream issue
I have configured Gunicorn with Nginx for a Django application. I have received a lot of traffic to my website and I saw an nginx error where it was mentioned Gunicorn.sock failed. What does it mean? Also, Do we need to create gunicorn.conf.py for Gunicorn server? Is it mandatory? -
How can i use the nested ModelSerializer()?
I am trying to use this nested ModelSerializer class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id','email','username','password','followiing') def get_fields(self): fields = super(UserSerializer, self).get_fields() fields['followiing'] = UserSerializer(many=True) return fields This system is not making any changes. What is the issue here that i can't understand? -
Django Model Mocking - Better to create model or mock model for testing?
I have a very simple model like this: class Observation(models.Model): thing = models.ForeignKey(Thing, on_delete=models.PROTECT) user_locked = models.BooleanField(default=False) admin_locked = models.BooleanField(default=False) created = models.DateTimeField(auto_now=False, auto_now_add=True) created_by = models.ForeignKey( User, on_delete=models.PROTECT, related_name="%(class)s_created_by" ) updated = models.DateTimeField(auto_now=True, auto_now_add=False) updated_by = models.ForeignKey( User, on_delete=models.PROTECT, related_name="%(class)s_updated_by" ) def is_fully_locked(self): """Return boolean if Observation is locked by both""" if self.user_locked and self.admin_locked: return True return False I'm trying to test the is_fully_locked() method and I was curious about creating the Observation model. I have used things like Mixer and factory_boy in the past to create objects to test against, but as those projects grew so did the time it took for the tests to run which I'd like to avoid. I have recently started reading about using Mock (I'm still confused by it a little). My question is - for a simple model like this - what is the best/fastest way to test that method? Currently I have some test like this: class ObservationTest(TestCase): def test_is_fully_locked_with_no_employee_locked(self): start = time.time() observation = Observation(admin_locked=True) print(time.time() - start) # Takes 5.91278076171875e-05 # FASTEST self.assertFalse(observation.is_fully_locked()) def test_is_fully_locked_with_no_employee_locked_mixer(self): start = time.time() observation = mixer.blend(Observation, admin_locked=True) print(time.time() - start) # Takes 0.011276006698608398 # SLOWEST self.assertFalse(observation.is_fully_locked()) def test_is_fully_locked_with_no_employee_locked_mock(self): start = time.time() observation = … -
Django forms - create a variable based on user input selection
I am attempting to create a router config generator using django form. The idea is that the form takes input / choices and these are then displayed as part of a larger router config page using jinja and html. Where I am getting stuck is being able to create a new variable based on input and displaying this in the config_page.html. So for example lets say for 'WAN_SubnetMask' '30' is selected, I want to take the integers entered for 'WAN_Subnet', perform some very basic math e.g. add 2 and then create a new variable called 'WAN_IP'. I can display objects from my database in the however the 'WAN_IP' does not show as desired. Here is what I have come up with so far, I have tried adding the logic to create the 'WAN_IP' variable in both forms and views. forms.py from django import forms from .models import CPEconfig Router = [ ('2901', 'Cisco 2901'), ('1941', 'Cisco 1941'), WAN_SubnetMask = [ ('30', '30'), ('29', '29'), ] LAN_SubnetMask = [ ('30', '30'), ('29', '29'), ] class ConfigForm(forms.ModelForm): Router = forms.CharField(label='Select Router', widget=forms.Select(choices=Router)) WAN_Subnet = forms.GenericIPAddressField() WAN_SubnetMask = forms.CharField(label='WAN Subnet Mask', widget=forms.Select(choices=WAN_SubnetMask)) LAN_SubnetMask = forms.CharField(label='LAN Subnet Mask', widget=forms.Select(choices=LAN_SubnetMask)) class Meta: model = CPEconfig … -
Django not deleting stored messages when iterated over
I'm tryin to retrieve django messages through an api. However the messages are not being deleting upon iteration. It is being consumed with Vue JS on the front-end with a request made through Axios. def api_messages(request): all_messages = [] stored_messages = messages.get_messages(request) for message in stored_messages: all_messages.append({"message": message.message, "tag": message.tags}) response = {"messages": all_messages} return JsonResponse(response) -
Create an app only for the homepage in Django?
The rest of the apps do not seem relevant enough to make use one of their views as the main homepage. Is it a bad practice to create an app only for the homepage? What is the best practice for the homepage when developing in Django? Or at least the most common? -
translate django formset to apollo graphql mutation
I'm currently converting a full django app to a Django/React app and I need to update multiple objects in the same form. I'm using GraphQl with apollo client to link React and Django but I can't find to process to replicate the django Formset. Anyone has an idea ? -
Django and Celery - ModuleNotFoundError: No module named 'celery.task'
I wanted to start a periodic task in Django using Celery. Here are the relevant parts of my project: # celery.py from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookProjectSetting.settings') app = Celery('bookProjectSetting') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') The __init__.py looks like this: # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) My tasks.py file in my books app folder looks like this: from books.models import Book from celery.schedules import crontab from celery.decorators import periodic_task @periodic_task( run_every=(crontab(minute='*/10')), name="update_life_time_of_books", ignore_result=True) def update_life_time_of_books(): # do sth. I also set up redis as broker and installed the django-celery-beat stuff. But when I run the worker via the command: celery -A bookProjectSetting beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler Then I get the following error: File "/home/ac3l1k/Desktop/PROJECT/simpleDjangoProjects/bookProject/env/lib/python3.8/site-packages/celery/local.py", line 403, in _compat_periodic_task_decorator … -
Input text boxes in HTML for loop not recognized
so I am trying to align each Comment input box and comment text per updated posts. I am using for loop to iterate all the posts but only the text input in very first comment input box is recognized, and trying to enter text input on other boxes returns "enter a text" error. Will there be any way to fix this? Below is the code of my for loop. <ol> {% for post in posts reversed%} <li> {% csrf_token %} </form> <span class="details"> <a href ="{% url 'profile' post.created_by.id %}"> <label>Post by</label> <span id = "id_post_profile_{{post.id}}"> {{post.created_by.first_name}} {{post.created_by.last_name}} </span> </a> </span> <div id = "id_post_text_{{post.id}}"> {{post.content}} </div> <span class="details" id = "id_post_date_time_{{post.id}}"> {{post.creation_time}} </span> <br><label class = "comment">Comment: </label> <input type = 'text', id = "id_comment_input_text_{{post.id}}", class = "comment", name = "comment"> <button class = "comment", type = "submit", id = "id_comment_button_{{post.id}}", onclick = "addItem()" >Submit your comment</button> <span id="error" class="error"></span> {% for comment in post.test_set.all %} <li> {{comment.text}} </li> {% endfor %} </li> {% endfor %} </ol> -
What exactly does UpdateCacheMiddleware and FetchFromCacheMiddleware do?
I added these to my "settings.py" and Django seemed to cache every page. I wasn't expecting it to change the behaviour of the whole site. MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', (other middleware goes here) 'django.middleware.cache.FetchFromCacheMiddleware' ] This seems to happen on a view (every one) unless you override the behaviour by adding the never cache decorator for example. I guess that it is how it is supposed to work, right? from django.views.decorators.cache import never_cache @never_cache def fooView(request): return render(request, 'foo.html') If you put this decorator on every view that you didn't want to cache, then is that equivalent to not using this caching middleware and just putting a cache page decorator on all the other pages (the ones you do want to cache), or is there more to it? Using the caching middleware seems a bit drastic if you only need caching on a few pages. -
Django Admin model editor: grey out field if another boolean field is not checked
I have the following two fields in my Treatment Model: is_followup = models.BooleanField() parent_treatment = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE) In the screen grab below from my admin page, I'd like to grey out "Parent treatment" if is followup is not checked. Is this possible? and if so, how to do it? -
Django request.POST QueryDict only returns true/on values from forms.booleanfield(required=False)
I am currently working on a Django admin action where you can create a model object from two or more already existing objects. Each object have an integerfield to store the current amount of items it has. When I'm using the action I want to be able to choose how many to take from each object and give to the new one. I also want to have an option to take all. Currently this is a simple Boolean checkbox field. My problem is, whenever i submit my form, where I for example only checked 2/4 checkboxes and two a number in the other two. The request.POST returns a QueryDict where the booleanfield called empty_field is like this: 'empty_field': ['on', 'on']. It doesn't account for False or 'off' which i need. The exact thing I am asking for, is how do I get the False/off values from request.POST? Thanks My views.py: def post(self, request, *args, **kwargs): form = MergeForm(data=request.POST) print(request.POST) My forms.py: class MergeForm(forms.ModelForm): batch_stock_choicefield = forms.IntegerField() empty_field = forms.BooleanField(required=False) class Meta: model = Batch fields = ['batch_stock_choicefield', 'empty_field'] My html div: <div> <form action="" method="POST"> {% csrf_token %} <table class="form-group"> <thead> <tr> <th>Batch id</th> <th>Stock item</th> <th>Quantity</th> <th>Take From Batch … -
Django read file from model, [Errno 2] No such file or directory
In Django I am using model forms to upload .stl file in model shown below. Once I submit form I see files get uploaded to myproject => media directory. But while reading uploaded file from the model, I am keep getting file not found error. I tried using both absolute and relative path without success, any help is much appreciated. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') model.py from django.db import models class StlFile(models.Model): uploaded_file = models.FileField() uploaded_at = models.DateTimeField(auto_now_add=True) volume = models.FloatField(default=0.0) forms.py from django import forms from .models import StlFile class StlForm(forms.ModelForm): class Meta: model = StlFile fields = [ 'uploaded_file' ] After POST request numpy stl reads saved stl file from the model in views.py. views.py import os from django.shortcuts import render import numpy as np from stl import mesh from .forms import StlForm from .models import StlFile # Create your views here. def model_form_upload(request): if request.method == 'POST': form = StlForm(request.POST, request.FILES) if form.is_valid(): stl_file = form.save(commit=False) # Read file but Don't save the file yet stl_file.uploaded_file = request.FILES['uploaded_file'] # Read file instance in model parameter stl_file.save() # Extract mechanical properties from STL stl_path = stl_file.uploaded_file.url stl_mesh = mesh.Mesh.from_file(stl_path) # Read saved file from the …