Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Syntax Error when trying to makemigrations in django
I am a newbie in web design and I'm trying to design a web server using sentdex's Django Web Development video series. I am running the web server on a Raspberry Pi B+ with all the most recent software. I have followed sentdex's every step so far. The only difference is I was told to use a virtual enviroment when using django on a Pi so that's my only difference(other than updated software). In 12:37 of his second video when he uses the command "python manage.py makemigrations" (after adding the app name to the settings.py) his command prompt comes up with no errors while mine gives the error: Error Message Snip I have looked into adding django to the PYTHONPATH but I've also seen conflicting posts. Any help would be appreciated, thank you. Link for Video: https://www.youtube.com/watch?v=aXxIjeGR6po&list=PLQVvvaa0QuDe9nqlirjacLkBYdgc2inh3&index=2 -
How to display the youtube url stored in django database to display in template,here is the stuff i have done i am getting error of no videos yet
I have been following django-embed-video tutorial by jazzband and everything is setup and i uploaded url in my database ,but when running the database no any videos is displaying in my template .It's throwing error file "\env\lib\site-packages\embed_video\templatetags\embed_video_tags.py", line 196, in embedbackend = cls.get_backend(url, context=context, **options) File "\env\lib\site-packages\embed_video\templatetags\embed_video_tags.py", line 174, in get_backend else detect_backend(str(backend_or_url)) File "\env\lib\site-packages\embed_video\backends.py", line 64, in detect_backend raise UnknownBackendException embed_video.backends.UnknownBackendException here is /app/models.py class youtube(models.Model): video = EmbedVideoField(default="") def __str__(self): return self.video /app/views.py from .models import youtube def display_video(request): videos = youtube.objects.all() context = {'video': videos} return render (request, 'library.html', context) library.html {% load embed_video_tags %} {% video item.video 'small' %} {% block content %} {% if videos %} {% for v in videos %} {{ v.video }} {% endfor %} {% else %} <p>No videos yet</p> {% endif %} {% endblock %} /myproject/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'embed_video', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['template'], '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',** ], }, }, ] STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' Thank you so much for help -
Django HttpResponse working with latin encode
I'm passing a json to the HttpResponse and I'm having problems with some special characters like 'ñ' or 'á'. this is my code in the views.py file: def count_depto(request): time = datetime.now() - timedelta(days=1) df = pd.DataFrame.from_records(RayosDepto.objects.filter(tiempo__gte=time).values()) grouped = df.groupby('dpto').size().to_frame() grouped.columns=[grouped[0].sum()] grouped.rename_axis('Total',inplace=True) grouped=grouped.transpose() grouped = grouped.to_json(orient='records',force_ascii=False) return HttpResponse(grouped,content_type='json') and this is my actual result: is there a way to fix this?Django version:3.0.5, pandas version:1.0.3 -
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