Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
cannot add event in Fullcalendar Django
I cannot add event to the Fullcalendar. It seems like add_event in index.html and add_event in urls.py are not connected. I don't know how to connect between both of them. Every time I insert data in index.html, data that is saved in database is always empty but it is saved somehow. Please help me. I have tried so many things and it still doesn't work. index.html <!DOCTYPE html> <html> <head> <title>カレンダーサンプル</title> <link rel="stylesheet" href="{% static 'fullcalendar/calendar/css/fullcalendar.min.css' %}"/> <link rel="stylesheet" href="{% static 'fullcalendar/calendar/css/style.css' %}"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript" src="{% static 'fullcalendar/calendar/js/moment.min.js' %}"></script> <script type="text/javascript" src="{% static 'fullcalendar/calendar/js/fullcalendar.min.js' %}"></script> <script type="text/javascript" src="{% static 'fullcalendar/calendar/lang/ja.js' %}"></script> <script> // ページ読み込み時の処理 $(document).ready(function () { // カレンダーの設定 $('#calendar').fullCalendar({ height: 550, lang: "ja", header: { left: 'prev,next today', center: 'title', right: 'month,basicWeek,basicDay' }, events: [ {% for event in events %} { title: "{{ event.title}}", start: '{{ event.start|date:"Y-m-d" }}', end: '{{ event.end|date:"Y-m-d" }}', id: '{{ event.id }}', }, {% endfor %} ], timeFormat: 'HH:mm', selectable: true, selectHelper: true, navLinks: true, // eventSources: [{ // url: '/fullcalendar/calendar', // dataType: 'json', // async: false, // type : 'GET', // error: function() { // $('#script-warning').show(); // } // }], select: function(start, end, resource) { var title = prompt("予定タイトル:"); var … -
How to access the selected option in an select tag with Django (not using Javascript)?
I have a form that has a select tag and dynamically created options for that tag as shown below. I want to access the selected tag if it is included in the POST request as part of the form in my Python/Django code: <form action="{% url 'newprogram' %}" method="post" novalidate> {% csrf_token %} TODO: Add Program to School <select name="schooloptions"> {% for school in schools %} <option value="{{ school.name }}">{{ school.name }}</option> {% endfor %} </select> <div class="form-group"> <input autofocus class="form-control" type="text" name="programname" placeholder=""> </div> <input class="btn btn-primary" type="submit" value="Post"> </form> I want to select the option that the user selects from the drop-down menu as follows but it does not work: @login_required def newprogram(request): if request.method == "POST": programname = request.POST["programname"] school = request.POST["schooloptions"].selected() #This does not work and is what I need help with schoolobj = School.objects.get("school") school = Program(School=schoolobj, name=programname) school.save() return render(request, "network/index.html") Any thoughts as to how I can access the selected option from a select HTML tag within a form? -
django.db.utils.DataError: (1406, "Data too long for column 'barcodes' at row 1")
I'm trying to make a program which take values of barcodes with barcode scanner and save the values of barcodes in db, problems occurs when I try to add more than 5-6 barcodes. It gives me "django.db.utils.DataError: (1406, "Data too long for column 'barcodes' at row 1")" error. I've made sure that its a model.textfield() but that doesn't solve my problem. My models look like this: id = models.IntegerField(primary_key=True) barcodes = models.CharField(max_length=255) to_warehouse = models.CharField(max_length=255) from_warehouse = models.CharField(max_length=255) total_count = models.IntegerField() approval_flag = models.IntegerField(default=0) current_status = models.CharField(max_length=50, blank=True, null=True) error_message = models.CharField(max_length=255, blank=True, null=True) created_by = models.CharField(max_length=50, blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) class Meta: managed = False db_table = 'transfer_inventory' def __str__(self): return "%s" % self.id My view function that creates the obj for that looks like this: def change_status(self, barcodes, warehouse_id, request, is_error="", msg=""): barcode_count = barcodes.count(',') _list_barcodes = barcodes.split(",") print("list: ", list) list_barcodes = [] to_warehouse = Warehouse.objects.filter(id=warehouse_id).values_list('key', flat=True)[0] try: current_warehouse = UserWarehouseMapping.objects.filter( user=request.user).values_list('warehouse__key', flat=True).first() except: current_warehouse = "-" for i in _list_barcodes: list_barcodes.append(i) list_barcodes = list_barcodes.pop(len(list_barcodes) - 1) available_barcodes = list( Inventory.objects.filter(inventory_status='available').values_list('barcode', flat=True)) InventoryTransfer.objects.create(barcodes=barcodes, to_warehouse=to_warehouse, total_count=barcode_count, created_by=request.user.username, from_warehouse=current_warehouse, current_status="Pending") In which specific this part is used to create obj: InventoryTransfer.objects.create(barcodes=barcodes, to_warehouse=to_warehouse, total_count=barcode_count, created_by=request.user.username, from_warehouse=current_warehouse, current_status="Pending") … -
Django Dynamic Object Filtering issue in Template
I have a page which lists the posts along with the photos associated with each post. However I am having trouble in filtering and sending photos from photo lists QuerySet as it us under loop of posts list query set. Any idea how to run filters for getting the photos as only the associated post in a template? <h2> Posts: </h2> {% for post in post_list %} {% include 'posts/list-inline.html' with post_whole=post post_photos=photo_list %} {% endfor %} Here from photo_list in need to filter out multiple objects having foreign key relationship with individual post. The QuerySet filter is not working here in the template. -
Store data programatically in django database once and exclude from running each time server starts
I want to fetched data from URL to database in Django but don't want execute each time server runs. What is good way to achieve this ? -
Navigation Links in Django
I would like to kindly ask you, because since 2 days I'm pretty concerned about that, how to set proper navigation on navigation bar to go back to the homepage or to go into further section such as e.g "contact" or "prices", Ill show quick example what I really mean: Home -- Prices -- Contact Being at the homepage I press "Home" button and of course it refreshes the site, because we are at the homepage. I press the Prices button and it goes into 127.0.0.1:8000/prices and everything seems to be okay now we are in the prices section page - Home -- Prices -- Contact but now when i press "Contact" it goes to 127.0.0.1:8000/prices/contact ,but I would like that to be 127.0.0.1:8000/contact, or by pressing now "home" it refreshes the site, its not going back into the homepage. Can you please give me tip what shall i do now? my urls.py (whole project) urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls') ), ] my urls.py (application) urlpatterns = [ path('', views.home, name="home-page"), path('prices/', views.prices, name="prices-page"), path('contact/',views.contact, name="contact-page"), ] my views.py (application) def home(request): return render(request, 'home.html', {}) def prices(request): return render(request, 'prices.html', {}) def contact(request): return render(request, 'contact.html', {}) -
Django, Zappa - RuntimeError: populate() isn't reentrant
I am beginner of django and zappa. And I am trying to deploy django application using zappa on AWS lambda. Also, I'd like to connect RDS database (postgres). To create database, I entered "zappa manage dev create_db" Then, error message occurred as below. And I don't know how to solve this. Other solutions on the Internet didn't work for me. populate() isn't reentrant: RuntimeError Traceback (most recent call last): File "/var/task/handler.py", line 509, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 240, in lambda_handler return handler.handler(event, context) File "/var/task/handler.py", line 372, in handler app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS) File "/var/task/zappa/ext/django_zappa.py", line 20, in get_django_wsgi return get_wsgi_application() File "/var/task/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/var/task/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/task/django/apps/registry.py", line 81, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant zappa_settings.json is { "dev": { "django_settings": "test_zappa_13.settings", "aws_region": "ap-northeast-2", "profile_name": "default", "project_name": "test-zappa-13", "runtime": "python3.6", "s3_bucket": "zappa-rw2difr3r" } } django settings.py is INSTALLED_APPS = [ 'zappa_django_utils', ... ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'blah', 'USER': 'blahblah', 'PASSWORD': 'blahblah', 'HOST': 'postgres-instance-1.test1234.ap-northeast-2.rds.amazonaws.com', 'PORT': 5432, } } ... And, Django version == 2.2, Python version == 3.6, Zappa version == 0.45.1 Please help me to solve this problem. … -
How to return a response while method is still running
I have uploaded a Django App on Heroku (Free Tier) where the user can upload some .xlsx files and generate a final spreadsheet based on them. The main page consists of three buttons, Upload, Generate, Download and everything works perfectly when it has to do with small files. But When I upload bigger files the Generate process takes a lot longer which leads to error: H12 in Heroku. I tried working with rq as suggested by Heroku, but with no success. What am I doing wrong? Here is my views.py file def main(request): q = Queue(connection=Redis()) if request.method == "POST" and 'cta-button-generate' in request.POST: q.enqueue(webControl.generate_files()) return render(request, template_name='main.html') -
In Django/Javascript While showing all the values from db, check the checkboxes of few of these which were already selected for each row
I am a newbie to django. I have tried various options. Any help would be highly appreciable. Below is my code,I have pasted only required lines from my code. This is not the complete code: Note: section_data is of list type ( while adding from django, these are added via checkboxes only to DB ) I have this in my template.html <table class="table table-striped table-bordered zero-configuration"> <thead>//table headings here</thead> <tbody> {% for row in data %} <tr><td>{{row.class_name}}</td><td>{{row.section_data}}</td> <td><a href="#" data-toggle="modal" data-academic_year="{{row.academic_year}}" data-class_name="{{row.class_name}}" data-section_data="{{row.section_data}}" data-id="{{row.id}}" class="ls-modal"><i class="icon-note menu-icon"></i></a></td></tr> {% endfor %} </tbody> </table> On clicking 'icon-note' above, a popup will be opened, showing classname and section - This icon is utilized for edit. So,In this pop up I am showing all the sections available in DB, but with the help of JS I wanted to check all those values which were already selected for this while adding in DB via django itself : below is the code of the popup, which was written in the same html template as above <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <div class="modal-body"> <div class="form-group"> <div class="form-check form-check-inline"> {% for row in section_vals %} <input type="checkbox" name="sections_checkbox_edit" … -
Why is my class-based view only working with GET?
I wanted to ask a question, but I kind of found an answer myself and wanted to share it here. Perhaps someone can even tell me what was happening. I created an UpdateView subclass like several times before. But when I got to the page via a button that was part of method=post form I only got an empty form. Was driving me mad. In the end, I found just incidentally that when I entered the URL again in the address bar the values were received from the database. I changed the form with the button from post to get and when I now click it to go to the UpdateView page, it works. But to be honest, I do not know why. CVBs are still mysterious for me ;) -
Reverse for 'newsdate' with no arguments not found. 1 pattern(s) tried: ['newsdate/(?P<year>[0-9]+)$']
I was trying Django Tutorials. I have used a navbar template and used it in base html file. And all other pages are inheriting that base file. But when on linking the newdate(name given in urls.py) I am getting this error NoReverseMatch at /newsdate/2020 Reverse for 'newsdate' with no arguments not found. 1 pattern(s) tried: ['newsdate/(?P<year>[0-9]+)$'] I visited http://127.0.0.1:8000/newsdate/2020 My database with contain one entry with date 2020, The selection of objects from database is getting completed as print("lol",artice_list) prints the item matching from database. Error: NoReverseMatch at /newsdate/2020 Reverse for 'newsdate' with no arguments not found. 1 pattern(s) tried: ['newsdate/(?P<year>[0-9]+)$'] Request Method: GET Request URL: http://127.0.0.1:8000/newsdate/2020 Django Version: 3.0 Exception Type: NoReverseMatch Exception Value: Reverse for 'newsdate' with no arguments not found. 1 pattern(s) tried: ['newsdate/(?P<year>[0-9]+)$'] Exception Location: /home/rishabh/anaconda3/lib/python3.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 676 Python Executable: /home/rishabh/anaconda3/bin/python Python Version: 3.7.4 Python Path: ['/home/rishabh/Documents/DjangoWorks/Learning/src', '/home/rishabh/anaconda3/lib/python37.zip', '/home/rishabh/anaconda3/lib/python3.7', '/home/rishabh/anaconda3/lib/python3.7/lib-dynload', '/home/rishabh/anaconda3/lib/python3.7/site-packages'] Server time: Sun, 26 Apr 2020 17:11:09 +0000 Error during template rendering In template /home/rishabh/Documents/DjangoWorks/Learning/src/templates/navbar.html, error at line 6 Reverse for 'newsdate' with no arguments not found. 1 pattern(s) tried: ['newsdate/(?P<year>[0-9]+)$'] 1 <nav> 2 <ul> 3 <li><a href="{% url 'home' %}">Home</a></li> 4 <li><a href="{% url 'news' %}">News</a></li> 5 <li><a href="{% url 'contact' %}">Contact</a></li> … -
Rendering bs4.Tag's text with Django Templates
I'm trying to render the text from bs4 Tags using Django Template Language. For some reason bs4.Tag.text isn't accessible from template. I can render it's text only if I get it before and pass it to template itself instead of Tag object. Here is code that I used: from django.template import Template, Context from bs4 import BeautifulSoup html_string = '<p>Some text.</p>' soup = BeautifulSoup(html_string) tag = soup.find('p') template = Template('{{ tag.text }} - {{ tag_text }}') context = Context({'tag': tag, 'tag_text': tag.text}) print(template.render(context)) Expected output: Some text. - Some text. Actual output: - Some text. I feel confused a bit. For my purposes it's necessary to pass raw bs4.Tag objects to extract text and other attributes after. Hope you can help me -
Displaying Django page views in my detail page
I want to display the number of times a page have been viewed in my details page. I also want to increment the pageview by 1 anytime the page is anytime the page is loaded. I have a code that does but it also updates my DateTime attribute. How can I achieve this without having to alter everything? models.py class Music(models.Model): artist = models.CharField(max_length=300) title = models.CharField(max_length=200, unique=True) slug = models.SlugField(default='', blank=True, unique=True) thumbnail = models.ImageField(blank=False) audio_file = models.FileField(default='') uploaded_date = models.DateTimeField(default=timezone.now) description = RichTextUploadingField() views = models.IntegerField(default=0) class Meta: ordering = ['-uploaded_date'] def save(self): self.uploaded_date = timezone.now() self.slug = slugify(self.title) super(Music, self).save() def __str__(self): return self.title + ' by ' + self.artist def get_absolute_url(self): return reverse('music:detail', kwargs={'slug': self.slug}) views.py def detail(request, slug): latest_posts = Music.objects.order_by('-uploaded_date')[:5] song = get_object_or_404(Music, slug=slug) song.views = song.views + 1 song.save() -
Django FTP client Name Error: name TEST_HOST not defined
so i tried to use this (https://github.com/author135135/django-ftp-client) django app in my project. Everything is fine, but when i tried to connect to my remote ftp server, i get this error on my terminal. manager.add_connection(TEST_HOST, TEST_USER, TEST_PASSWD) NameError: name 'TEST_HOST' is not defined nothing seems to be mentioned on the github readme file, so seems like i am doing it wrong. where am i wrong? -
virtualenv can't create env in project
I'd like to create virtual environment in my distribution project on Catalina OS Mac. I receive this feedback from terminal: user@MBP-zen distribution % virtualenv env Traceback (most recent call last): File "/usr/local/bin/virtualenv", line 6, in <module> from pkg_resources import load_entry_point File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3241, in <module> @_call_aside File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3225, in _call_aside f(*args, **kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3254, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 585, in _build_master return cls._build_from_requirements(__requires__) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 598, in _build_from_requirements dists = ws.resolve(reqs, Environment()) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 786, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'zipp>=0.4' distribution was not found and is required by importlib-resource user@MBP-zen ~ % which virtualenv /usr/local/bin/virtualenv this is my python installed: user@MBP-zen ~ % python Python 3.7.7 (default, Mar 10 2020, 15:43:33) [Clang 11.0.0 (clang-1100.0.33.17)] on darwin Type "help", "copyright", "credits" or "license" for more information. I tested many answers given here as well as over internet but no success as for now. Any ideas why is this happening? -
CORS issue with react and django-rest-framework
I'm using react on the frontend side and Django on the backend. I using django-cors-headers for managing CORS in my Django app. I have added the package in INSTALLED_APPS like this:- INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework.authtoken', 'rest_framework', 'corsheaders', 'services', 'feeds', 'knox', 'users', ] then I have also added same in MIDDLEWARE MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', 'django.middleware.common.CommonMiddleware', ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ['*'] and I'm passing CORS headers from my client-side React app like:- const Axios = axios.create({ baseURL: `${BASE_URL}/api`, timeout: 1000, headers: { 'X-Custom-Header': 'foobar', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }) -
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: DLL load failed while importing _psycopg: module could not be found
I have installed psycop2 on my virtualenv. Then after running python manage.py makemigrations command in my pycharm terminal got this error: (venv) C:\Users\ADMIN\PycharmProjects\django_pro_postgres\django_project>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\django\db\backends\postgresql\base.py", line 25, in <module> import psycopg2 as Database File "C:\Users\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\psycopg2\__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: The specified module could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\ADMIN\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 "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> … -
Having a problem redirecting with the correct pk value in django
So, I am having trouble redirecting using other_user pk. I can't figure out to pass that pk in. I am either passing request.user pk, or I am getting a 'local variable 'other_user' referenced before assignment' error. I can pass other_user into my template, but , I don't how to combine the href link WITH the button to submit the form. I wonder if that's even possible? I did try doing it via the redirect method with other_user.id, but I can't. So, basically I am getting the other_user when I query for it, but I don't know how to pass it to my redirect so it take my user where it needs to go. How would I go about solving this problem? views.py/message def message (request, profile_id): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): form.save() return redirect('dating_app:messages') else: conversation, created = Conversation.objects.filter(members = request.user).filter(members= profile_id).get_or_create() other_user = conversation.members.filter(id=profile_id).get() form = MessageForm({'sender': request.user, 'conversation': conversation}) context = {'form' : form, 'other_user': other_user } return render(request, 'dating_app/message.html', context) message.html <form method="post" action="{% url 'dating_app:message' user.id %}" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button name="submit">login</button> {% endbuttons %} <a href="{% url 'dating_app:messages' other_user.id %}">Start messaging </a> <input … -
Guessing Game where players have to correctly guess the name of a specific NBA player given their image (Python)
I would like to create a game for my friends where we are given a random NBA player's head shot and we would have to guess his name correctly. I want to be able to display a wide range of players, including mainstream players and even obscure players. Each correct guess would score more points and whoever has the most points wins the game. I plan on using this website to get all the head shots that I need: (https://sportradar.us/2018/10/nba-headshots-now-available/). I am a beginner in Python and would like some ideas on where to even start. What frameworks should I use? I have dabbled in Django and could imagine creating a web app for this game. I've tried looking up similar tutorials but mostly I've only found basic number guessing games. I don't need a complete solution, maybe just some ideas on where to start so I can figure out the rest. Any advice or resource is appreciated! -
Add new line (and bullet points) in Django forms response label text?
I have a form: class FormFood(forms.Form): CHOICES = [ (1,'Yes'), (2, 'No')] response = forms.ChoiceField(widget=forms.RadioSelect, label="Would you like some pasta, bread or rice?", choices=CHOICES) It appears like this in my browser: The problem I would like 'pasta', 'bread' and 'rice' to appear on different lines with bullet points like this: Would you like: Pasta Bread Rice What I've tried Adding \n in the label text and skipping a line using 'enter'. Neither have worked. Could somebody point me in the right direction as to how best to do this? -
What is the proper syntax to import view in urls.py in django3?
What is the proper syntax to import view.py into urls.py I am trying to add pagination and search and have run into a SyntaxError "SyntaxError: invalid syntax" . I tried my best to debug it the last few days. I can see it is the way I am importing view. I tried a bunch of combinations and made it worse any guidance extremely appreciated. File "C:\Users\taylo\Desktop\pybox\blogdemo\blog\urls.py", line 3 blogdemo/blog/urls.py from django.urls import path from . import views from .views index, single, SearchResultsListView urlpatterns = [ path('', views.index, name='index'), path('<int:id>/', views.single, name='single'), path('search/', SearchResultSingleView.as_view(), name='search_results'), #added ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) blogdemo/blogdemo/URLS.PY from .views index, single, SearchResultsListView from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include # imported include module urlpatterns = [ path('', include('blog.urls')), #added path('admin/', admin.site.urls), path('search/', SearchResultListView.as_view(), name='search_results'), #added ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) blogdemo/VIEWS.PY from django.core.paginator import Paginator from django.shortcuts import render from .models import Article def index(request): articles = Article.objects.all() paginator = Paginator(articles,3) page = request.GET.get('page') posts = paginator.get_page(page) return render(request, 'index.html', {'posts': posts}) def single(request, id): single = Article.objects.get(id=id) nextpost = Article.objects.filter(id_gt=single.id).order_by('id').first() prevpost = Article.objects.filter(id_lt=single.id).order_by('id').last() return render(request, 'single.html', {"single": single, "prevpost": prevpost, "nextpost": nextpost}) class SearchResultsListView(SingleView): model = Article … -
Django - What is the best approach to handle multiple user types...and route the HTML pages based on this?
I'm making a small test project with below user types: School Admin, Teacher, Student, Parent. And each user type will have different Permissions like School Admin has full access... Parents can only view their Childern's Activity. Teacher can see all students but can add / edit marks for their respective students only. Teachers can setup Exam etc.. Students can take exam and submit the exam, but cannot edit / add any other information. Just can edit his profile detail. Approach 1: Do i need to create a Custom User calss and apply to each user type (ie one Custome Class.. and 4 user type calss).. and similarly have 4 different view and html pages? Approach 2: Just have one custome class and have an field with UserType which will have the have as "SchoolAdmin", "Teacher", "Student","Parent".. and one view and html (as the data page would remain same and only data record will restrict), and somehow identify the User Type in View, and filter the record? Definately some view or html pages will be specific to one user type only which is i am able to handle, the issue is to use same view / html page to handle all … -
Django: validation of restricted Foreign keys forms in Mixins Class views
Context: how I handled foreign keys restrictions on GET I have some trouble validating this form: class RecordConsultationForm(forms.ModelForm): class Meta: model = Consultation fields = ["fk_type", "fk_client", "duration", "date"] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(RecordConsultationForm, self).__init__(*args, **kwargs) self.fields['fk_client'].queryset = Client.objects.filter(fk_owner=self.user) # <=====HERE The queryset restricts the available clients to users. Pretty effective, I just had to add the following to get_context_data(): @method_decorator(login_required, name='dispatch') class BrowseConsultations(BrowseAndCreate): template_name = "console/browse_consultations.html" model = Consultation form_class = RecordConsultationForm success_url = 'browse_consultations' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.form_class(user = self.request.user) #<=====HERE return context Form validation on BrowseConsultations Despite what I added in get_context_data(), form data on POST does not seem valid, as if user were None (so it seems): Invalid fk_client: Select a valid choice. 2 is not one of the available choices. Maybe get_context_data() was not the proper place to set the user? Is there a way I could tweak the form in post()? Is it the proper way to do it? Additional details BrowseAndCreate BrowseConsultations inherits from is a Mixing class I created to handle common ordering tasks and messages. Here is a portion of it: @method_decorator(login_required, name='dispatch') class BrowseAndCreate(CreateView, TemplateView): """display a bunch of items from … -
Multiply two fields together in django database
I am new to Django and i have been trying to do this for sometime now. models.py class Majitele(models.Model): cena_p = models.DecimalField(decimal_places=2, max_digits=10, null=True) cena_l = models.DecimalField(decimal_places=2, max_digits=10, null=True) lv = models.IntegerField(null=True) katastr = models.CharField(max_length=40, null=True) jmeno = models.CharField(max_length=40, null=True) ulice = models.CharField(max_length=30, null=True) mesto = models.CharField(max_length=30, null=True) psc = models.IntegerField(null=True) v_pole = models.DecimalField(decimal_places=4, max_digits=10, null=True) v_les = models.DecimalField(decimal_places=4, max_digits=10, null=True) v_celkem = models.DecimalField(decimal_places=4, max_digits=10, null=True) cena_pole = models.DecimalField(decimal_places=4, max_digits=10, null=True) cena_les = models.DecimalField(decimal_places=4, max_digits=10, null=True) cena_rok = models.DecimalField(decimal_places=4, max_digits=10, null=True) nevyplaceno = models.IntegerField(null=True) podil = models.CharField(max_length=5, null=True) hlasu = models.IntegerField(null=True) poznamka = models.CharField(max_length=200, null=True) prezence = models.BooleanField(null=True) vyplatni = models.BooleanField(null=True) postou = models.BooleanField(null=True) osobne = models.BooleanField(null=True) def __str__(self): return '%s'%(self.jmeno) Here is what would i like to do: Take v_pole value then cena_p value and multiply them together and the result should then be saved in the cena_pole field. I tried this: Majitele.objects.all().annotate(vypocet_c=F('cena_p') * F('v_pole')).update(cena_pole=vypocet_c) Is there even a way how to do it? Thanks for any advice. -
Get Item from Django Annotated Queryset With Dynamic Database Functions
I'm encountering something unexpected, and I'm sure it must be a simple solution. I'm trying to use the CUME_DIST() function to annotate a django SQL query. This part is working fine and giving me a proper output. The challenge I'm having is, when I try to fetch a specific item from the annotated queryset using .get(user=request.user) it will give me back the correct item, but the annotated column seems to be re-evaluated. I want to get the item with the same annotated value as in the original query. Note that I can access this correctly with index notation (ex: annotated_queryset[10] gives the correct output for item at index 10), but I'm not sure at which index the desired item will be. Example of my code: annotated_queryset = Profile.objects.annotate(score_cume=RawSQL(""" CUME_DIST() OVER ( ORDER BY score ) """, ())) Above gives me the correct queryset. user_profile = annotated_queryset.get(user=request.user) print("score cum : ", user_profile.score_cume) Printing out the above always gives 1.0 because (I believe) it's evaluating the score_cume filed against the one object it's retrieving. How can I retrieve this object by request.user from the original annotated queryset and keep the annotated value? FWIW: I'm using postgres with django