Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django prevent data from passing in URL
I am new to Django and web dev. I am currently working on a textbox that a user will input data. Then they will click submit and I want that data to go to another page. However when they click the submit button, all the text ends up in the URL. The amount of text that will be passed in this text area is going to be thousands of characters. Is it possible to not allow it to appear in the url? This is my textbox and submit button: <form action="{% url 'parsed' %}"> <textarea name="fulltextarea" cols=40 rows=10></textarea> <br /> <input type="submit" value="Submit"/> </form> urls.py urlpatterns = [ path('', views.home, name='jsonparser-home'), path('parsed/', views.parsed, name="parsed") ] views.py def parsed(request): data = request.GET.get('fulltextarea') print(data) return render(request, 'jsonparser/parsed.html', {"json":data}) Now when I enter text into my text box and click the submit button my URL gets the data in it as: http://localhost:8000/parsed/?fulltextarea=wefwefallmydatasubmittedishere Is it possible to remove all of that in the URL? -
How to post a list of objects containing file input with Axios post and Django
I want to create a web app that allows users to upload a list of files with an associated file name that the user chooses. I want my POST to look as below. {"user": "ME", "files": [{"file":"InMemoryFileUpload", "name": "file_name"}, {"file":"InMemoryFileUpload", "name": "file_name1"}]} I cannot find a way of extracting the files from the POST for this particular use case. I can extract the elements from the list if there are no file objects, and I can extract files if they are not stored in a list. Here is my simplified React script import React, { Component } from "react"; import axios from "axios"; class SomeForm extends Component { handleSubmit(e) { e.preventDefault(); const user = '3' const selectedFile = e.target.input.files[0]; const selectedKey = e.target.keyName.value var formData = new FormData(); formData.append('user', user) formData.append('files', [{'name': selectedKey, 'file': selectedFile}, {'name': 'TEST', 'file': selectedFile}]) axios.post("http://localhost:8000/api/handle_user_input/", formData) } render(){ return( <form onSubmit={this.handleSubmit}> <label>Upload File:</label> <input type="text" name="keyName" /> <input type="file" name="input" /> <button type="submit">Upload</button> </form> ); } } export default SomeForm; The request POST.data is like below <QueryDict: {'user': ['3'], 'files': ['[object Object],[object Object]']}> How can I POST the files correctly in this format? Also, this is my first Django project so any other feedback is … -
HTTP Error 403 on pafy package for python
I have a Django app in which I am using pafy. It worked perfectly fine until today. Now when I try to play a song I get this error: Access to r1---sn-uxaxiv0nxx5q-nv4l.googlevideo.com was denied The page also says "HTTP ERROR 403". The thing is that I haven't changed anything in my code to get this error. What can be causing this? My code is: views.py def more(request,song_url,title): url = 'http://www.youtube.com/watch?v=' + str(song_url) video = pafy.new(url) s = video.getbestaudio(preftype='m4a') audio_stream = {'extension': s.extension, 'video_url': s.url + "&title=" + video.title} context = {'stream': audio_stream, 'title': video.title, 'song_title': title}] more.html <a href="{{ stream.video_url }}" style="text-decoration: none;" download="{{ song_title }}.{{ stream.extension }}" target="_blank" >Play/Download</a> -
Problem configuring react inside a drf project
I'm trying to create auth scheme for my API using this tutorial: JWT auth guide When trying the react part of the tutorial I ran 'npm run build' and got the following error: yovel@YovelBeastPad:~/PycharmProjects/Triangulation$ npm run build > triangulationapi@1.0.0 build /home/yovel/PycharmProjects/Triangulation > webpack --config webpack.config.js /home/yovel/PycharmProjects/Triangulation/node_modules/webpack-cli/bin/cli.js:93 throw err; ^ ReferenceError: triangulationapi is not defined at Object.<anonymous> (/home/yovel/PycharmProjects/Triangulation/webpack.config.js:20:9) at Module._compile (/home/yovel/PycharmProjects/Triangulation/node_modules/v8-compile-cache/v8-compile-cache.js:192:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10) at Module.load (internal/modules/cjs/loader.js:996:32) at Function.Module._load (internal/modules/cjs/loader.js:896:14) at Module.require (internal/modules/cjs/loader.js:1036:19) at require (/home/yovel/PycharmProjects/Triangulation/node_modules/v8-compile-cache/v8-compile-cache.js:161:20) at WEBPACK_OPTIONS (/home/yovel/PycharmProjects/Triangulation/node_modules/webpack-cli/bin/utils/convert-argv.js:114:13) at requireConfig (/home/yovel/PycharmProjects/Triangulation/node_modules/webpack-cli/bin/utils/convert-argv.js:116:6) at /home/yovel/PycharmProjects/Triangulation/node_modules/webpack-cli/bin/utils/convert-argv.js:123:17 at Array.forEach (<anonymous>) at module.exports (/home/yovel/PycharmProjects/Triangulation/node_modules/webpack-cli/bin/utils/convert-argv.js:121:15) at /home/yovel/PycharmProjects/Triangulation/node_modules/webpack-cli/bin/cli.js:71:45 at Object.parse (/home/yovel/PycharmProjects/Triangulation/node_modules/yargs/yargs.js:567:18) at /home/yovel/PycharmProjects/Triangulation/node_modules/webpack-cli/bin/cli.js:49:8 at Object.<anonymous> (/home/yovel/PycharmProjects/Triangulation/node_modules/webpack-cli/bin/cli.js:366:3) at Module._compile (internal/modules/cjs/loader.js:1147:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10) at Module.load (internal/modules/cjs/loader.js:996:32) at Function.Module._load (internal/modules/cjs/loader.js:896:14) at Module.require (internal/modules/cjs/loader.js:1036:19) at require (internal/modules/cjs/helpers.js:72:18) at Object.<anonymous> (/home/yovel/PycharmProjects/Triangulation/node_modules/webpack/bin/webpack.js:156:2) at Module._compile (internal/modules/cjs/loader.js:1147:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10) at Module.load (internal/modules/cjs/loader.js:996:32) at Function.Module._load (internal/modules/cjs/loader.js:896:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! triangulationapi@1.0.0 build: `webpack --config webpack.config.js` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the triangulationapi@1.0.0 build script. I understand that the error has something to do with webpack but where is the error is coming from, and what does it mean? Project structure: My 'front' Django app inside … -
How to style specific django form field in html and css
How do I style the form in CSS and without using bootstrap or crispy forms, any help is appreciated, Thanks. .field1 { font-family: inherit; margin-bottom: 25px; display: flex; justify-content: space-between; } label { font-family: Segoe UI; font-size: 18px; color: #1E1E1E; padding-left: 60px; } .holder { padding-right: 60px; } <div class="field1"> <label>Username</label> <span class="holder">{{ form.username }}</span> </div> [1]: https://i.stack.imgur.com/CxfoX.png what it looks right now [2]: https://i.stack.imgur.com/GgHlz.png what it should look like -
How to resize images with Django when uploading to AWS S3?
I am uploading and storing my media files on DigitalOcean Spaces (which is built on AWS) with Django using the Boto 3 package. Everything works fine and I am able to view my images on my site, however, I get an error when trying to modify the image using Pillow on upload. I would like to convert the images to JPEG and resize and optimize them. This is how my model's current save function looks: def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.image: img = Image.open(self.image.path) if img.mode != 'RGB': img = img.convert('RGB') if img.width > 100: ratio = img.width / img.height height = 100 / ratio output_size = (100, height) img.thumbnail(output_size) img = ImageOps.exif_transpose(img) img.save(self.image.path, optimize=True, quality=90, format='JPEG') If anyone can help me, I would really appreciate it! -
How to add disable attribute to a Django <select> form?
I have a Django choice form: SEASON_CHOICES = ( ('running', 'Running season'), ('next', 'Next season' ) ) class DeterminingForm(forms.Form): season = forms.ChoiceField(widget=forms.Select, choices=SEASON_CHOICES) I want a disabled option in my form. Something like a placeholder with 'Choose an option', just like you see on almost any select form. I don't know how to do this. Any idea? -
Aborting long running request in Django
I want to abort a request to an API which takes longer than 5 seconds. I know the client-side code can have a timeout of 5 seconds and that will ensure it doesn't wait any longer than that to get a response, but the Django server would still be processing the request even though the client won't be receiving it at the end. As far as I know, even if I configure this on nginx or gunicorn, those will still act as clients for the Django server app and the same problem will occur - that nginx will not wait for more than 5 seconds, but Django will continue processing the request. Is there any way I can somehow abort this request processing in Django (application server code level) itself? -
css script working but js script not working in Django
My index.css script located at Project/static/css/index.css is working fine and effect is seen in index.html page. But window alert from index.js script is not seen. Since .css script is working fine, I assume that there is no issue with settings.py so problem might be with linking. I tried two alternatives: Both not working. Please help! Html page: Project/templates/index.html <!DOCTYPE html> {%load static%} <html lang="en" dir="ltr"> <head> <script src="{% static "jss/index.js" %}" type="text/javascript"></script> <link rel="stylesheet" href="{% static "css/index.css"%}"> <meta charset="utf-8"> <title>Base Html</title> </head> <body> {%block body%} {%endblock%} </body> </html> Javascript Page: Project/static/jss/index.js alert("Hello, Welcome to my page"); settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '&cq=^n*t!55h)0c@3f+7*ilrvr$066)*n)&-8v6rokna4-yd30' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'App', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Project.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N … -
Safest and driest way to filter query_set depending on some user info
I have a Post model with a boolean field, is_draft. If the user is logged and is member of the staff, then I want to displays all posts; otherwise, only the posts for which is_draft is false. My first thought was to use a custom model manager and use request.user as following: class PostManager(models.Manager): def get_queryset(self): if request.user and request.user.is_staff: return super().get_queryset() else: return super().get_queryset().filter(is_draft=False) but request is not available in the model. I saw some people use a middleware to access the user in the model. It seems to me the safest way to address my need (ie it's done once, in the custom manager; people modifying the views.py don't have to bother, no risk of forgetting it) but this solution seems controversial. I have of course the possibility to add some logic in the view, but I feel this is not DRY (as I query Post many times) nor safe (risk somebody forgets it at some point). According to you, what would be the cleanest and safest way to address this need? PS: I've found a similar question for which a solution was proposed for Class-based views, but my views are function-based. Thanks a lot! -
How to change href in django based on the current page url?
As I said in the title, what would be the correct syntax to change the href of a link according to the current url the user is on? I tried this, but it doesn't work. {% if url == '' %} href='/cookies' {% else %} href='' {% endif %} What would be the correct syntax to do this? -
djnango DoesNotExist at /medical-basics
this is what i see instead of the table contents.the code is completely fine and the server is running fine too.The Microsoft Edge console shows "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" DoesNotExist at /medical-basics Tutorial matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/medical-basics Django Version: 2.1.7 Exception Type: DoesNotExist Exception Value: Tutorial matching query does not exist. Exception Location: C:\Users\JShaikh\anaconda3\envs\djangoenv\lib\site-packages\django\db\models\query.py in get, line 399 Python Executable: C:\Users\JShaikh\anaconda3\envs\djangoenv\python.exe Python Version: 3.7.7 Python Path: ['C:\Users\JShaikh\Desktop\apple\mysite', 'C:\Users\JShaikh\anaconda3\envs\djangoenv\python37.zip', 'C:\Users\JShaikh\anaconda3\envs\djangoenv\DLLs', 'C:\Users\JShaikh\anaconda3\envs\djangoenv\lib', 'C:\Users\JShaikh\anaconda3\envs\djangoenv', 'C:\Users\JShaikh\anaconda3\envs\djangoenv\lib\site-packages'] Server time: Tue, 21 Apr 2020 16:45:23 +0000 -
I have a long error message when writing "python manage.py makemigrations" saying invalid syntax
1**. I am following Mosh' tutorial on (youtube https://www.youtube.com/watch?v=_uQrJ0TkZlc)- at the part where we get to the DB SQLite part, it sayd this long message when writing "Python manage.py makemigrations": (venv) C:\Users\user\PycharmProjects\PyShop>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\user\PycharmProjects\PyShop\venv\lib\site- packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\user\PycharmProjects\PyShop\venv\lib\site- packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\PycharmProjects\PyShop\venv\lib\site- packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\PycharmProjects\PyShop\venv\lib\site- packages\django\core\management\base.py", line 350, in execute self.check() File "C:\Users\user\PycharmProjects\PyShop\venv\lib\site- packages\django\core\management\base.py", line 376, in check all_issues = self._run_checks( File "C:\Users\user\PycharmProjects\PyShop\venv\lib\site- packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\user\PycharmProjects\PyShop\venv\lib\site- packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\user\PycharmProjects\PyShop\venv\lib\site- packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\user\PycharmProjects\PyShop\venv\lib\site- packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\user\PycharmProjects\PyShop\venv\lib\site- packages\django\urls\resolvers.py", line 396, in check for pattern in self.url_patterns: File "C:\Users\user\PycharmProjects\PyShop\venv\lib\site- packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\user\PycharmProjects\PyShop\venv\lib\site- packages\django\urls\resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\user\PycharmProjects\PyShop\venv\lib\site- packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\user\PycharmProjects\PyShop\venv\lib\site- packages\django\urls\resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File … -
Django authentication with active directory cause 500 internal error
I have Django web app running on production server CentosOs-7. I'm trying to authenticate my user through the corporate Active Directory server. However, I'm encountering 500 internal server error when I visit my web app. So I've looked at httpd log file, I've found that Tue Apr 21 18:15:09.372866 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] mod_wsgi (pid=32508): Exception occurred processing WSGI script '/opt/BsP_v0/kwnProtclBsline_proj/kwnProtclBsline_proj/wsgi.py'. [Tue Apr 21 18:15:09.372884 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] Traceback (most recent call last): [Tue Apr 21 18:15:09.372897 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] File "/opt/BsP_v0/kwnProtclBsline_proj/kwnProtclBsline_proj/wsgi.py", line 16, in <module> [Tue Apr 21 18:15:09.372917 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] application = get_wsgi_application() [Tue Apr 21 18:15:09.372924 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] File "/opt/BsP_v0/kwnProtclBsline_proj/venv/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Tue Apr 21 18:15:09.372936 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] django.setup(set_prefix=False) [Tue Apr 21 18:15:09.372942 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] File "/opt/BsP_v0/kwnProtclBsline_proj/venv/lib/python2.7/site-packages/django/__init__.py", line 22, in setup [Tue Apr 21 18:15:09.372950 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Tue Apr 21 18:15:09.372955 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] File "/opt/BsP_v0/kwnProtclBsline_proj/venv/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ [Tue Apr 21 18:15:09.372963 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] self._setup(name) [Tue Apr 21 18:15:09.372967 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] File … -
Django-oscar less css
OSCAR_USE_LESS = True DEBUG = True In Oscar Documentation, it says that you can view compiled css via browser after a reload(F5) but my pages show without a CSS effect on them. What am I missing <link rel="stylesheet/less" type="text/css" href="{% static "oscar/less/styles.less" %}" /> <script src="//cdnjs.cloudflare.com/ajax/libs/less.js/3.9.0/less.min.js" ></script> -
Django Jinja - If an object in all objects has attribute run html
I'm needing help figuring out how to write code for this problem (in title). Let's say I have this model: from django.db import models class Section(models.Model): name = models.CharField(max_length=20) display = models.BooleanField(default=True) and I create 2 objects with different names and 2 different display variables: >>> s1.display True >>> s2.display False Here I have some HTML code with Jinja templating for this code to display, if these objects even exist: <!-- In Views, Section.objects.all() is 'sections' --> {% if sections %} <div class="all-sections"> <h2 class="title">Explore</h2> {% for section in sections %} <div class="section"> <p class="section-title">{{ section.name }}</p> </div> {% endfor %} </div> {% endif %} Now I make both of them false: >>> s1.display = False >>> s1.save() Now, if ALL OF THEM HAVE DISPLAY FALSE I don't want the entire section to be there, the same as if there weren't any in that list at all. I've thought about doing a for loop and iterating through each one, but then that would just repeat the all of the HTML code for each one that did have display on. <!-- Wouldn't Work Example --> {% if sections %} {% for section in sections %} {% if section.display %} <div class="all-sections"> … -
Django Update view saving but not updating
I have made a working form to post reviews for restaurants. When user is logged in he can see displayed under his post the edit button. When I use the Updateview however, it doesn't edit, but instead creates a new line in which the new review appears (and that new line doesn't appear then on my webpage). Here is the model: class UserReview(models.Model): # Defining the possible grades Grade_1 = 1 Grade_2 = 2 Grade_3 = 3 Grade_4 = 4 Grade_5 = 5 # All those grades will sit under Review_Grade to appear in choices Review_Grade = ( (1, '1 - Not satisfied'), (2, '2 - Almost satisfied'), (3, '3 - Satisfied'), (4, '4 - Very satisfied'), (5, '5 - Exceptionally satisfied') ) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) user_review_grade = models.IntegerField(default=None, choices=Review_Grade) # default=None pour eviter d'avoir un bouton vide sur ma template user_review_comment = models.CharField(max_length=1500) posted_by = models.ForeignKey(User, on_delete=models.DO_NOTHING) def get_absolute_url(self): return reverse('restaurants:reviews', args=[self.id]) def get_edit_url(self): return reverse('restaurants:edit-review', args=(self.id,)) Here is the update form (similar as review form): class EditReviewForm(forms.ModelForm): class Meta: model = UserReview fields = [ 'restaurant', 'user_review_grade', 'user_review_comment' ] widgets = { 'restaurant': forms.HiddenInput, 'user_review_grade': forms.RadioSelect, 'user_review_comment': forms.Textarea } labels = { 'user_review_grade': 'Chose a satisfaction level:', … -
Use Matplotlib on django site
I am thinking of starting a new django project for plotting stock prices and displaying them onto the site. I know matplotlib pretty well and was wondering if I could plot the chart and somehow push it to the site with the usual matplotlib features like zoom etc. I have seen this done where that images are pushed but I am wondering if I could push the chart with its functionality provided by matplotlib and I can't seem to find an answer anywhere so maybe it isn't possible? -
how to override django admin delete confirmation page?
When i tried to delete an object which has 500 related objects. delete confirmation page talking so long to render related objects. how to override it so that it will not show related objects in the delete confirmation page. but it will delete it in the background. -
Django get values for Max of grouped data
After many trials and errors and checking similar questions, I think it worth asking it with all the details. Here's a simple model. Let's say we have a Book model and a Reserve model that holds reservation data for each Book. class Book(models.Model): title = models.CharField( 'Book Title', max_length=50 ) name = models.CharField( max_length=250 ) class Reserve(models.Model): book = models.ForeignKey( Book, on_delete=models.CASCADE ) reserve_date = models.DateTimeField() status = models.CharField( 'Reservation Status', max_length=5, choices=[ ('R', 'Reserved'), ('F', 'Free') ] ) I added a book and two reservation records to the model: from django.utils import timezone book_inst = Book(title='Book1') book_inst.save() reserve_inst = Reserve(book=book_inst, reserve_date=timezone.now(), status='R') reserve_inst.save() reserve_inst = Reserve(book=book_inst, reserve_date=timezone.now(), status='F') reserve_inst.save() My goal is to get data for the last reservation for each book. Based on other questions, I get it to this point: from django.db.models import F, Q, Max reserve_qs = Reserve.objects.filter( book__title='Book1' ).values( 'book__title' ) reserve_qs now has the last action for each Book, but when I add .value() it ignores the grouping and returns all the records. I also tried filtering with F: Reserve.objects.filter( book__title='Book1' ).values( 'book__title' ).annotate( last_action=Max('reserve_date') ).values( ).filter( reserve_date=F('last_action') ) I'm using Django 3 and SQLite. -
Django form is saying field is required despite providing value
I have a form with a required field customer_phone_number and despite passing a phone number in with the data the form isn't valid.. class OrderForm(forms.ModelForm): class Meta: model = models.Order fields = ( 'date', 'customer_phone_number', ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['customer_phone_number'].required = True self.fields['customer_phone_number'].widget = PhoneNumberPrefixWidget() data = { 'date': '2020-04-20', 'customer_phone_number': '+17168567800', } form = OrderForm(data=data) form.is_valid() print(form.errors) # {'customer_phone_number': ['This field is required.']} The only thing I can think of is that I'm using a custom widget but I have no idea how to correct this error. from phonenumber_field.phonenumber import PhoneNumber from django.forms import Select, TextInput from django.forms.widgets import MultiWidget class PhonePrefixSelect(Select): initial = '+1' def __init__(self, attrs=None): choices = [('+1', '+1')] super().__init__(attrs, choices=sorted(choices, key=lambda item: item[1])) def render(self, name, value, *args, **kwargs): return super().render( name, value or self.initial, *args, **kwargs) class PhoneNumberPrefixWidget(MultiWidget): """ A Widget that splits phone number input into: - a country select box for phone prefix - an input for local phone number """ def __init__(self, attrs=None): widgets = ( PhonePrefixSelect(attrs={ 'class': 'form-control w-25 mr-2', 'tabindex': '-1' }), TextInput(attrs={ 'class': 'form-control w-75' }), ) super().__init__(widgets, attrs) def decompress(self, value): if value: if type(value) == PhoneNumber: if value.country_code and value.national_number: return ["+%d" % … -
Reuse django urls patterns and views
I have a usecase where I would like to reuse a bunch of existing views and url patterns. Current situation is a product with about 20 views for it: urlpatterns = [ # product url(r'^product/(?P<pid>\d+)$', views.view_product, name='view_product'), url(r'^product/(?P<pid>\d+)/something$', views.view_something, name='view_something'), url(r'^product/(?P<pid>\d+)/morethings', views.view_morethings, name='view_morethings'), url(r'^product/(?P<pid>\d+)/deeper/things$', views.view_deeper_things, name='view_deeper_things'), ... etc. So I can browse to the following urls: https://host/product/1 https://host/product/1/something https://host/product/1/morethings https://host/product/1/deeper/things In the new situation I want to add additional ways to browse to the products, i.e. product name or some key valuepair. i.e. https://host/product/name/product1 https://host/product/name/product1/something https://host/product/name/product1/morethings https://host/product/name/product1/deeper/things and https://host/product/meta/property1/value1 https://host/product/meta/property1/value1/something https://host/product/meta/property1/value1/morethings https://host/product/meta/property1/value1/deeper/things where I use a database query in the view to find the product by name, or by the specified property+value. How can I reuse patterns and views to avoid having 20 new views and patterns for each way of identifying a product? I could just list all the (20x3) possible patterns and add 20 more for each new way of identifying products. url(r'^product/(?P<pid>\d+)/something$', views.view_something, name='view_something'), url(r'^product/(?P<pid>\d+)/morethings', views.view_morethings, name='view_morethings'), url(r'^product/(?P<pid>\d+)/deeper/things$', views.view_deeper_things, name='view_deeper_things'), url(r'^product/name/<str:name>/something$', views.view_something_name, name='view_something_name'), url(r'^product/name/<str:name>/morethings', views.view_morethings_name, name='view_morethings_name'), url(r'^product/name/<str:name>/deeper/things$', views.view_deeper_things_name, name='view_deeper_things_name'), url(r'^product/meta/key/<str:name>/<str:name>/something$', views.view_something_meta, name='view_something_meta'), url(r'^product/meta/key/<str:name>/<str:name>/morethings', views.view_morethings_meta, name='view_morethings_meta'), url(r'^product/meta/key/<str:name>/<str:name>/deeper/things$', views.view_deeper_things_meta, name='view_deeper_things_meta'), I know I could do: urlpatterns = [ # product url(r'^product/(?P<pid>\d+)$', views.view_product, name='view_product'), url(r'^product/name/<str:name>$', views.view_product, name='view_product_by_name'), And have default … -
Django Template `With` Operator complex boolean assignment
I am creating a Django template that has columns only visible to admins. Currently I am using a template tag has_group that works well. I have to include some logic for superusers. {% if request.user|has_group:"Admins" or request.user.is_superuser %} <th class="detail_btn_col" scope="col">Detail</th> {% endif %} ... Similar code for the <td> But it's making a query for every row of a table. Not terrible but I would like to just set the value once at the start of the template. I saw that I could assign a variable using with and that would accomplish what I want. {% with has_admin_view=request.user|has_group:"Admins" or request.user.is_superuser %} Does not work. {% with has_admin_view=request.user|has_group:"Admins" %} The above works, but superusers aren't included. Is there a way to do AND/OR operations in Django template's WITH statement? -
Django rest framework serialize model with FK
I'm learning Django and Vuejs. There is something I'm not understanding how it works. I have a model "Nc" wich have some foreign key to other models like Affaire. How can i obtaines in my JSON files the str return for instances instead of the real value... models.py : class Affaires(models.Model): id = models.PositiveSmallIntegerField(primary_key=True) nom = models.CharField(max_length=50) adresse = models.CharField(max_length=100, blank=True, null=True) cp = models.CharField(max_length=5, blank=True, null=True) ville = models.CharField(max_length=50, blank=True, null=True) dessinateur = models.PositiveSmallIntegerField(blank=True, null=True) conducteur = models.PositiveSmallIntegerField(blank=True, null=True) chefdeprojet = models.PositiveSmallIntegerField(blank=True, null=True) cloture = models.IntegerField() class Meta: managed = True db_table = 'affaires' def __str__(self): return '{} - {}'.format(self.id, self.nom) class NC(models.Model): idaffaire = models.ForeignKey(Affaires, models.DO_NOTHING,verbose_name="N° d'affaire", db_column='idAffaire') idof = models.ForeignKey(AffairesOfs, models.DO_NOTHING,verbose_name="N° d'OF", db_column='idOf') idposte = models.ForeignKey(ProductionPostes, models.DO_NOTHING,verbose_name="Poste", db_column="idPoste") idrepere = models.ForeignKey(AffairesReperes, models.DO_NOTHING,verbose_name="Repère", db_column='idRepere') idnc = models.ForeignKey(Nc_type, models.DO_NOTHING,verbose_name="Type de NC", db_column='idNc_type') quantite = models.PositiveIntegerField(verbose_name="Quantité") dateajout = models.DateField(default=timezone.now, verbose_name="Date d'ajout", db_column='dateAjout') class Meta: managed = True db_table = 'qualite_Nc' serialize.py class NcSerializer(serializers.ModelSerializer): class Meta: model = NC fields = '__all__' JSON files : { "id": 1, "quantite": 1, "dateajout": "2020-04-08", "idaffaire": 1145, "idof": 1433, "idposte": 6271, "idrepere": 5361, "idnc": 1 }, { "id": 2, "quantite": 17, "dateajout": "2020-04-09", "idaffaire": 1205, "idof": 1290, "idposte": 5812, "idrepere": 7004, "idnc": 1 }, … -
Null field in database
I have a form with conditionned field my problem is that empty field is registered instead of NULL in database 2 last fields are conditionned on selected value just before (ran_bug) my 2 conditionned fields are required = false (even it should not be necessary ?) in my models, this fields are null=True and blank=True class Randomisation(models.Model): ran_ide = models.AutoField(primary_key=True) pay_ide = models.CharField("Patient's country code", max_length=2, null=True, blank=True) ran_str_num = models.CharField("Logical numerotation", max_length=2, null=True, blank=True) ran_bra = models.CharField("Arm", max_length=1, null=True, blank=True) bra_lib = models.CharField("Arm label", max_length=50, null=True, blank=True) ran_act = models.IntegerField("Activated line", null=True, blank=True) pat = models.CharField("Patient number", max_length=12, unique=True, null=True, blank=True) ran_nai = models.IntegerField("Patient birthdate (year)", blank=True) ran_sex = models.IntegerField("Sex", null=True, blank=True) ran_st1 = models.IntegerField("Stratification variable 1", blank=True) ran_st2 = models.IntegerField("Stratification variable 2", blank=True) ran_bug = models.IntegerField("Use of alternative randomization procedure?", null=True, blank=True) ran_dem_nom = models.CharField("Name of the person asking for randomization", max_length=12, null=True, blank=True) ran_dem_dat = models.DateTimeField("Date of demand", null=True, blank=True) ran_log = models.DateTimeField("User", null=True, blank=True) ran_dat = models.DateTimeField("Date", null=True, auto_now_add=True, blank=True) forms.py class RandomizationEditForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): super(RandomizationEditForm, self).__init__(*args, **kwargs) self.user_country = request.session.get('user_country') self.language = request.session.get('language') self.user_site_type = request.session.get('user_site_type') PAYS = Pays.options_list(self.user_country,self.user_site_type,self.language) SEXE = [(None,''),(1,'Male'),(2,'Female')] STRATE_1 = [(None,''),(1,'strate 1 condition 1'),(2,'strate 1 condition 2')] STRATE_2 …