Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make all the 'inlines' collapsible items in Django Admin to default open?
I am new to Django and Python programming and I have looking in circles to solve this problem I have. I wrote following codes...whenever the below codes were executed, the inline filter is always default as 'close'. How can I default to 'open' or 'show' instead of default 'close'? Thank you. class ArInvoiceSimpleInlineForeign(admin.TabularInline): model = ArInvoice extra = 2 classes = ('collapse open',) inline_classes = ('collapse open',) -
How to set the templates directory in django .?
I am having a hard time finding the explanation how to set templates directory in django settings.py. -
Using Django settings file configurations dynamically in case of muliple settings file
So, I have multiple environment specific settings file in my Django project which has different values for "TYPE" in each one of them. The value of TYPE is being used in some of my python files and don't want to import different settings files to use the value of "TYPE" while running in different environments. Are there any possible ways to do this? Any links to resources will be good too. -
Getting error NoReverseMatch at / Reverse for 'login' with no arguments not found. 1 pattern(s) tried: ['accounts/$login/$']
URLS.PY from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ url(r'^login/$',auth_views.LoginView.as_view(),name='login'), url(r'^logout/$',auth_views.LogoutView.as_view(),name='logout'), url(r'^signup/$',views.SignUp.as_view(),name='signup'), ] base.html <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Star Social</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{% static 'simple_clone/css/master.css' %}"> </head> <body> <nav class="navbar mynav" role="navigation" id="navbar"> <div class="container"> <a class="navbar-brand" href="{% url 'home' %}">Star Social</a> <ul class="navbar-nav ml-auto"> {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="#">Post</a> </li> <li class="nav-item"><a class="nav-link" href="#">Groups</a> </li> <li class="nav-item"><a class="nav-link" href="#">Create Group</a> </li> <li class="nav-item"><a class="nav-link" href="{% url 'accounts:logout' %}">Logout</a> </li> {% else %} <li class="nav-item"><a class="nav-link" href="#">Groups</a> </li> <li class="nav-item"><a class="nav-link" href="{% url 'login' %}">Log In</a> </li> <li class="nav-item"><a class="nav-link" href="{% url 'accounts:signup'%}">Sign Up</a> </li> {% endif %} </ul> </div> </nav> {% block content%} {% endblock %} </body> </html> On trying to access http://127.0.0.1:8000/ Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.11.29 Exception Type: NoReverseMatch Exception Value: Reverse for 'login' with no arguments not found. 1 pattern(s) tried: ['accounts/$login/$'] -
Python Django: Ho to pass modelsdata to Admin default Startpage (index.html)?
I have created a Python Django application and would like to build a kind of dashboard on the ADMIN startpage/defaultpage (index.html). For this purpose I want to display e.g. different data of my models. I have tried to access the data of my models outside the admin area and to display them as I like. It worked there. However, it did not work with the same code in the admin area on the default startpage. I don't know how to access my models/objects in the index.html/Admin startpage. I am grateful for any help. -
Problem with Django One-to-One Table Primary Key Assignment - "ID" not found and "NOT NULL CONSTRAINT FAILED"
I'm going crazy trying to figure this out. I simply have a table with a one-to-one relationship with the User table. The code for the model, in part, is: class Client(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) When the table is created and I try to access the table information from within admin, it says no "id" is assigned, but it does assign a field that it generates automatically called 'user_id' and that field is populated with the primary key. It just doesn't seem to be recognizing it as the primary key, or accessing data because the "id" is not found. When I delete primary key=True, and leave it as a OnetoOneField without assigning it as the primary key,as follows class Client(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) it doesn't save and I get an Integrity error: IntegrityError at /client_intake/1/ NOT NULL constraint failed: intake_client.user_id Apparently without the primary key set it tries to save the user_id field as a null value. So, I cannot set the OnetoOne as primary key and I can't set it without it being the primary key without getting an error. It only saves when the primary key is true but then I can't access the data even though … -
django form save jsonfield by checkbox
As title I have a Model with several jsonfield fields and I want to use checkbox to store jsonfield How can I achieve this through django form? -
Creating Django model objects from HTML
In Django, I have a model called Exercise. Then, on an HTML page, I have a table with all of the exercises that belong to that user. In the following (shortened) code, you can see that I have a table that displays all of the exercises that the user currently has. Also, it has buttons to add new rows to the table. Goal: when I add a new row to a table, I want to also create a blank instance of the Exercise model. $('.deleteButton').on('click', function () { if ($(this.parentNode.parentNode.parentNode).find('tr').length > 3) { $(this.parentNode.parentNode.parentNode).find("tr:nth-last-child(2)").remove(); } }) $('.addButton').click(function () { $(this.parentNode.parentNode.parentNode).find('tr:last').before('<tr><td>name</td><td>sets</td><td>reps</td><td>weight</td></tr>') }) {% block content %} <div class="row" style="margin-top: 1%;"> {% for workout in workouts %} <div class="col-6 col-lg-3" style="margin-right: 50px;"> <table class="mytable"> {% for exercise in workout.exercise_set.all %} <tr> <td>{{ exercise.name }}</td> <td>{{ exercise.sets }}</td> <td>{{ exercise.repetitions }}</td> <td>{{ exercise.weight }}</td> </tr> {% endfor %} <tr id="editrow"> <td colspan="2"> <input class="addButton" type="button" value="Delete" /> </td> <td colspan="2"> <input class="deleteButton" type="button" value="Delete" /> </td> </tr> </table> </div> {% endfor %} </div> {% endblock %} -
How to define django templates folders?
I want to build my project with regards to html templates like this: ├───app1 │ ├───... │ └───... ├───app2 │ ├───... │ └───... ├───project │ ├───... │ ├───templates │ │ └───navbar.html │ │ └───footer.html │ │ └───sidebar.html │ │ └───conbined.html │ │ └───content_app1.html │ │ └───content_app2.html The reason is that I want to devide my site into several parts as shows below. Thus in every app folder there are no html files. The navbar, footer and sidebar are always shown, while the content_appN.html can be activated accordingly. The conbined.html conbines them all. My try (in settings.py): PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT, 'templates').replace('\\','/'), ) TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) In app1: views.py: def app1_content(request): return render(request, 'templates/combined.html') Actually I have tried almost every methods I could find online, but still dont know how to do it. Please dont laugh me for this idea to build the website like this. Could anyone please give me some hints? -
ValueError at /blogcat/Music/ invalid literal for int() with base 10: 'Music'
I am getting the above error while requesting : http://127.0.0.1:8000/blogcat/Music/ urls.py This is my projects urls .py from django.contrib import admin from django.urls import path from django.conf.urls.static import static from blogs import views from django.conf import settings urlpatterns = [ path('blogcat/<str:cat_title>/',views.blogcat,name='blogcat'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Files(models.Model): files=models.FileField(upload_to='blog/',blank=True,null=False) title=models.CharField(max_length=30) des=models.TextField() def __str__(self): return self.title class Category(models.Model): title=models.CharField(blank=True,max_length=20) des=models.TextField() image=models.ImageField(upload_to='cat/') def __str__(self): return self.title class Blog(models.Model): title=models.CharField(max_length=40) cre_date=models.DateField() pub_date=models.DateField() desc=models.TextField() image=models.ImageField(upload_to='blog/',blank=True,null=True) author=models.CharField(blank=True,choices=author,max_length=30) cat=models.ForeignKey(Category, verbose_name="Category", blank=True,on_delete=models.CASCADE,null=True) files=models.ForeignKey(Files, verbose_name="Files",on_delete=models.CASCADE,blank=True, null=True) def __str__(self): return self.title views.py views.py of app blogs Getting error with query : blogs=Blog.objects.filter(cat=cat_title) from django.shortcuts import render, redirect, get_object_or_404 from .models import Blog,Category def blog(request): blog= Blog.objects.all() cat= Category.objects.all() return render(request, 'blogs/allblogs.html', {'blog':blog,'cat':cat}) def post(request,post_id): post= Blog.objects.filter(pk=post_id) cat= Category.objects.all() return render(request, 'blogs/post.html', {'post':post}) def blogcat(request,cat_title): print(cat_title) blogs=Blog.objects.filter(cat=cat_title) print(blogs) return render(request,'blogs/blogcat.html',{'blogs':blogs}) I am having posts in database with category Music in it.Post in category Music -
Django HTML make random data generator with start and stop button and show shuffle script
I am new in django and i want to make a random data generator like https://numbergenerator.org/randomnumbergenerator but with data from database so i use sql in my view and not using any model at all views.py @csrf_exempt def index_random(request): query = "SELECT * FROM TABLE_EMPLOYEE" //i didnt use random from query because i need a data list to show a random suffle data employee = execute_query(query) //i have function to execute query and it works fine return(request, 'employee_random/random.html', {'employee':employee}) i want to random the employee.id so i can update and mark it i know i can random with python random.choice() or using javascript but i want to show the randomize employee.id to make it more real thankyou in advance -
"to" argument must be a list or tuple
Not sure why my contact form is not working. When I am trying to send an message thru the contact form it is giving me an Exception Type: TypeError It says "to" argument must be a list or tuple If someone could explain whats the problem I would appreciate it a lot:) This is the code: views.py def kontakt(request): if request.method == "POST": message_name = request.POST['fname'] message_lname = request.POST['lname'] message_email = request.POST['eaddress'] message_tel = request.POST['tel'] message = request.POST['message'] send_mail( message_name, message_lname, message_email, message_tel, message, ['mail@gmail.com'], ) return render(request, 'kontakt.html', {}) else: return render(request, 'kontakt.html', {}) settings.py # Email Settings EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 578 EMAIL_HOST_USER = 'mail@gmail.com' EMAIL_HOST_PASSWORD = 'pasword' EMAIL_USE_TLS = True Contact form html form action="{% url 'kontakt' %}" method="post"> {% csrf_token %} <div class="site-section"> <div class="container"> <div class="row"> <div class="col-md-6 form-group"> <label for="fname">Ime</label> <input type="text" name="fname" id="fname" class="form-control form-control-lg"> </div> <div class="col-md-6 form-group"> <label for="lname">Prezime</label> <input type="text" name="lname" id="lname" class="form-control form-control-lg"> </div> </div> <div class="row"> <div class="col-md-6 form-group"> <label for="eaddress">Email Adresa</label> <input type="text" name="eaddress" id="eaddress" class="form-control form-control-lg"> </div> <div class="col-md-6 form-group"> <label for="tel">Broj Tel.</label> <input type="text" name="tel" id="tel" class="form-control form-control-lg"> </div> </div> <div class="row"> <div class="col-md-12 form-group"> <label for="message">Poruka</label> <textarea name="message" id="message" cols="30" rows="10" class="form-control"></textarea> </div> … -
Vuex and Django Datepicker
I'm new to Vuex and Vue in General, I'm currently stuck where I need my data filtered using particular dates. I've already implemented all the logic in Django, the only problem is when I pick the date ranges, I am unable to pass the parameters to the URL and view on the backend. Maybe some code would help, <template> <div> <NavBar></NavBar> <div class="grid-container"> <div class="grid-x"> <div class="cell medium-12"> <div class="callout large"> <h5>This is a large callout</h5> <p>It has an easy to override visual style, and is appropriately subdued.</p> <a href="#">It's dangerous to go alone, take this.</a> </div> </div> </div> <div class="grid-x"> <div class="cell medium-6"> <form v-on:submit.prevent="weeklyData"> <date-picker v-model="start_date" value-type="format" format="YYYY-MM-DD"></date-picker> <date-picker v-model="end_date" value-type="format" format="YYYY-MM-DD"></date-picker> <button class="button" type="submit">Filter</button> </form> </div> <div class="cell medium-6"> </div> </div> </div> </div> </template> <script> import DatePicker from 'vue2-datepicker'; import 'vue2-datepicker/index.css'; import NavBar from '../components/Navbar' import { mapState } from 'vuex' export default { name: 'weekly', onIdle () { // dispatch logoutUser if no activity detected this.$store.dispatch('logoutUser') .then(response => { this.$router.push('/login') }) }, components: { NavBar, DatePicker }, data () { return { start_date: '', end_date: '', fil_comm: [] } }, methods: { weeklyData () { this.$store.dispatch('weeklyData', { start_date: this.start_date, end_date: this.end_date }) } }, computed: mapState(['Weekly']), … -
postgres: invalid option: -- '='
Creating the PostgreSQL Database and User psql -U username -h host -p port -d database -set=sslmode=require Here is the original guide on DigitalOcean: https://www.digitalocean.com/community/tutorials/how-to-set-up-a-scalable-django-app-with-digitalocean-managed-databases-and-spaces -
Django AttributeError: type object 'Rooms' has no attribute 'objects'
When trying to query or adding any data in the modals, I get the error saying type object 'Rooms' has no attribute 'objects'. Here's what I have: modals.py: class Rooms(models.Model): room_no = models.AutoField(primary_key=True) room_name = models.TextField(max_length=40) views.py: class HomePage(TemplateView): template_name = 'home/index.html' def get(self, request, *args, **kwargs): rooms = Rooms.objects.all() ...... ...... return render(request, self.template_name) Here's a full stacktrace of the error: Traceback (most recent call last): File "E:\Uni\Year 3\Professional Development\Esteem_v2\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "E:\Uni\Year 3\Professional Development\Esteem_v2\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "E:\Uni\Year 3\Professional Development\Esteem_v2\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Uni\Year 3\Professional Development\Esteem_v2\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "E:\Uni\Year 3\Professional Development\Esteem_v2\venv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "E:\Uni\Year 3\Professional Development\Esteem_v2\Home\views.py", line 62, in get rooms = Rooms.objects.all() Exception Type: AttributeError at / Exception Value: type object 'Rooms' has no attribute 'objects' If I try to query these modals from Python console, it works: from Home.models import Rooms Rooms.objects.all() <QuerySet [<Rooms: Rooms object (1)>]> But in Django it doesn't. I cannot figure out what is going on. Any help will be really appreciated. -
Serialized Data Displaying Letter by Letter Django
I'm learning to work with JSON and so I'm running a simple example to create a list item in my template for each object in my django model. My output looks like this: So I wanted each <li> to show just the actual value in Name. How can I amend my code to achieve that? views.py def Ajax(request): if request.is_ajax(): exporter = serializers.serialize("json", Proforma.objects.all()) print(exporter) data = json.dumps(exporter) return HttpResponse(data, content_type='application/json') $("#populate").click(function() { $.ajax({ url: "/ajax/more", success: function(data) { for(i = 0; i < data.length; i++){ $('ul').append('<li>'+data[i]+'</li>'); } } }); }); -
Encrypting Rest API response (Django)
Good day guys, I will like to get ideas on how I get encrypt my Rest API response I built with django. I know about using SSL but I will like to explore API end to end encryption between backend server (django/python) and Frontend client (angular/javascript) Thank you. -
'ImportError: No module named 'crispy_forms' in production
I'm deploying a Django application with Apache2 and WSGI. I get the following 'ImportError: No module named 'crispy_forms' in my /var/log/apache2/myproject-error.log. I have run pip3 install django-crispy-forms and with my virtual environment active python -V returns Python 3.5.3 I have a strong feeling this is version related. /etc/apache2/sites-enabled/myproject.conf <VirtualHost *:80> ServerName myproject.com ErrorLog ${APACHE_LOG_DIR}/myproject-error.log CustomLog ${APACHE_LOG_DIR}/myproject-access.log combined WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess myproject processes=2 threads=25 python-path=/svr/myproject WSGIProcessGroup myproject WSGIScriptAlias / /svr/myproject/myproject/wsgi.py Alias /robots.txt /svr/myproject/static/robots.txt Alias /favicon.ico /svr/myproject/static/favicon.ico Alias /static /svr/myproject/static/ Alias /media /svr/myproject/media/ <Directory /svr/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /svr/myproject/static> Require all granted </Directory> <Directory /svr/myproject/media> Require all granted </Directory> </VirtualHost> -
I keep getting Error while trying to deploy my django app to heroku:[ remote rejected] master -> master (pre-receive hook declined)
Below is the build log. Git Repo: https://github.com/omolojakazeem/prosoftmaker.git Python app detected ! Python has released a security update! Please consider upgrading to python-3.8.2 Learn More: https://devcenter.heroku.com/articles/python-runtimes cp: cannot create regular file '/app/tmp/cache/.heroku/requirements.txt': No such file or directory -----> Installing python-3.8.1 -----> Installing pip -----> Installing SQLite3 Sqlite3 successfully installed. -----> Installing requirements with pip Collecting asgiref==3.2.7 Downloading asgiref-3.2.7-py2.py3-none-any.whl (19 kB) Collecting certifi==2020.4.5.1 Downloading certifi-2020.4.5.1-py2.py3-none-any.whl (157 kB) Collecting dj-database-url==0.5.0 Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) Collecting Django==3.0.5 Downloading Django-3.0.5-py3-none-any.whl (7.5 MB) Collecting django-crispy-forms==1.9.0 Downloading django_crispy_forms-1.9.0-py2.py3-none-any.whl (107 kB) Collecting django-phone-field==1.8.0 Downloading django_phone_field-1.8.0-py3-none-any.whl (7.4 kB) Collecting django-taggit==1.2.0 Downloading django_taggit-1.2.0-py3-none-any.whl (45 kB) Collecting gunicorn==20.0.4 Downloading gunicorn-20.0.4-py2.py3-none-any.whl (77 kB) Collecting Pillow==7.1.1 Downloading Pillow-7.1.1-cp38-cp38-manylinux1_x86_64.whl (2.1 MB) Collecting psycopg2==2.8.5 Downloading psycopg2-2.8.5.tar.gz (380 kB) Collecting pytz==2019.3 Downloading pytz-2019.3-py2.py3-none-any.whl (509 kB) Collecting sqlparse==0.3.1 Downloading sqlparse-0.3.1-py2.py3-none-any.whl (40 kB) Collecting whitenoise==5.0.1 Downloading whitenoise-5.0.1-py2.py3-none-any.whl (20 kB) Collecting wincertstore==0.2 Downloading wincertstore-0.2-py2.py3-none-any.whl (8.8 kB) Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py): started Building wheel for psycopg2 (setup.py): finished with status 'done' Created wheel for psycopg2: filename=psycopg2-2.8.5-cp38-cp38-linux_x86_64.whl size=483304 sha256=bdfbf0467dc64bcd7dc084244fa49a1acb6058ac992b962770b9c470ece03bd6 Stored in directory: /tmp/pip-ephem-wheel-cache-my833lsg/wheels/35/64/21/9c9e2c1bb9cd6bca3c1b97b955615e37fd309f8e8b0b9fdf1a Successfully built psycopg2 Installing collected packages: asgiref, certifi, dj-database-url, sqlparse, pytz, Django, django-crispy-forms, django-phone-field, django-taggit, gunicorn, Pillow, psycopg2, whitenoise, wincertstore Successfully installed Django-3.0.5 Pillow-7.1.1 asgiref-3.2.7 certifi-2020.4.5.1 dj-database-url-0.5.0 django-crispy-forms-1.9.0 django-phone-field-1.8.0 django-taggit-1.2.0 … -
How to raise an error on a field that takes request.user as value
Thanks for your time: I've got a model(Pets) that has a foreign key to other (People) and people has a OnetoOne (User). I'm trying to call the errors on a ModelForm doing the clean method on Models.py. although the foreign key field of Pets is set to be the request.user.person (reversed OneToOne field of User with People). When i try to save the form i get the error: "Pets has no Pessoa" and pointing to if form.is_valid(): on views i've been trying with clean_fields method: models.py: class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='person') birthday = models.DateField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.user) class Pets(models.Model): pessoa = models.ForeignKey(People, on_delete=models.CASCADE, related_name='peop') nome = models.CharField(max_length=150) custo = models.DecimalField(max_digits=7, decimal_places=2) tipo = models.SmallIntegerField() def __str__(self): return '%s - %s' % (self.pessoa, self.nome) def clean_fields(self, exclude=None): super().clean_fields(exclude=exclude) slug = slugify(self.pessoa) if slug.startswith('a') and self.tipo == 2: if exclude and 'pessoa' in exclude: raise ValidationError('pessoas com a nao podem ter gatos') views.py: def create_pet_form3(request): if request.method == 'POST': form = PetForm5(request.POST) if form.is_valid(): pet = form.save(commit=False) pet.pessoa = request.user.person pet.save() else: raise ValidationError('corriga os erros') else: form = PetForm5() context = { 'form': form } return render(request, 'petform2.html', context) forms.py: class PetForm5(forms.ModelForm): … -
How to use Exclude in a FilterSet (Django) conditionally?
I have this field (that has it's own CharFilter). When the field is blank, I want to exclude all records with a certain value. How do I do that? I have something like this currently: post_code = django_filters.CharFilter(field_name="author__type") I want to do something like if not post_code: valid_entries = exclude(author__type = 'amateur') I know that won't work, but how can I accomplish this? -
How do I execute raw SQL queries on Django?
I have a mysql databbase already created and linked my django app Model.py looks like this class Student(models.Model): id_student = models.AutoField(primary_key=True) first_name = models.CharField(max_length=45) last_name = models.CharField(max_length=45) date_of_birth = models.DateField() nationality = models.CharField(max_length=45) gender = models.CharField(max_length=1) street_name = models.CharField(max_length=45) street_number = models.CharField(max_length=45) postal_code = models.CharField(max_length=45) city = models.CharField(max_length=45) phone = models.CharField(max_length=45) email = models.CharField(max_length=45) study_id_study = models.ForeignKey('Study', models.DO_NOTHING, db_column='study_id_study') start_year = models.CharField(max_length=45) teacher_id_teacher = models.ForeignKey('Teacher', models.DO_NOTHING, db_column='teacher_id_teacher') class Meta: managed = False db_table = 'Student' class Study(models.Model): id_study = models.IntegerField(primary_key=True) study_name = models.CharField(max_length=45) description = models.CharField(max_length=45, blank=True, null=True) language = models.CharField(max_length=45) number_of_years = models.CharField(max_length=45) class Meta: managed = False db_table = 'Study' I am trying to execute raw sql queries like this def home_view(request, *args, **kwargs): #obj = Study.objects.all() obj = Study.objects.raw('SELECT * FROM dashboard_study;') context = { 'obj':obj } return render(request, "home.html", context) but this doesn't really work, I keep receiving this error InvalidQuery at / Raw query must include the primary key Is there a better way I can use to execute raw sql queries ? Thanks in advance -
Is there any good mongodb GUI to view image data?
I am very new to mongodb. Recently I just start a python project on animal habitat analysis.My data is in form of images and texts. I would like to have a table view on my data. One of the column is image and all other columns are string. The image are stored in local path. I would like to ask is there GUI viewer already offer this feature. In case there is no such GUI, if I write simple html table view will it be very difficult? (I know html structure but only a little bit on server backend) I am thinking of use flask (I know a little bit) to create a html table view. But I am also a very beginner on flask. Any there any good suggestions (like what kind of framework) to start with? -
How to handle post request of a ModelChoiceField form in django? Attribute Error?
I want to create a form where the user can select a model object, but the choices are filtered based on the user. I want to then pass that object to the html template page, so I can display the object fields on the page. I got the form to display the objects correctly, so the get function is working, but when the user submits the form, I'm getting an Attribute Error that says "'QueryDict' object has no attribute 'user'". So I'm assuming there's something wrong with my post function. Error Stack Trace File "/Users/wsm-app/env/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/Users/wsm-app/polls/views.py", line 244, in post form = calendarForm(request=request.POST) File "/Users/wsm-app/polls/forms.py", line 25, in __init__ user = request.user AttributeError: 'QueryDict' object has no attribute 'user' forms.py class calendarForm(forms.Form): inputDate = forms.ModelChoiceField(label="Select a date", queryset = None, empty_label="No date selected") def __init__(self, *args, **kwargs): request = kwargs.pop('request', None) super().__init__(*args, **kwargs) if request: user = request.user self.fields['inputDate'].queryset = Analysis.objects.filter(user=user).order_by('sessionID__startDate') views.py class MultiView(generic.TemplateView): template_name = 'polls/analysis.html' def get(self,request): if self.request.user.is_authenticated: form = calendarForm(request=request) userid = self.request.user.id args = {'form': form,'obj':Analysis.objects.filter(user=userid).order_by('sessionID__startDate').last()} else: args = {'form': form} return render(request, self.template_name,args) def post(self,request): form = calendarForm(request=request.POST) if self.request.user.is_authenticated: if form.is_valid(): obj = form.cleaned_data['inputDate'] … -
Django: Display a value from a foreign key model in a combo box and select it
So I have the following requirement: I need to display a value from a combo box in Django, the Project Description specifically, but I just can't figure out to get the correct way to render it as I see nothing. Here's my configuration: models.py class Project(models.Model): projectID = models.AutoField(primary_key=True, db_column="Id", db_index=True, verbose_name='Project ID') description = models.CharField(max_length=900) def __str__(self): return str(f'{self.projectID}, {self.description}') def get_description(self): return str(self.description) class PM(models.Model): PMid = models.AutoField(primary_key=True, db_column="Id", db_index=True) PMNumber = models.CharField(max_length=50, unique=True, db_column="PMNumber") description = models.CharField(max_length=600) projectId = models.ForeignKey(Project, on_delete=models.CASCADE, db_column="ProjectID", related_name='+') def __str__(self): return str(f'{self.PMid}, {self.PMNumber}, {self.description}') def get_project_description(self): Project.objects.all().values_list('projectID', 'description') These are the forms: forms.py """ PM Forms """ #Django imports from django import forms #Project imports from pm.models import PM class PMForm(forms.ModelForm): """PMForm""" class Meta: model = PM fields = ('PMNumber', 'description', 'projectId') And this is the view: views.py """Pm Views """ #Django imports from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import CreateView #Forms import from pm.forms import PMForm #Models import class CreatePMView(LoginRequiredMixin, CreateView): template_name = 'pm/new.html' form_class = PMForm success_url = reverse_lazy('project:feed') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['user'] = self.request.user return context def get_description(self): return self.request.project.description Here's the HTML that I'm trying to render to display the Project …