Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Why does Django give me a 404 error for only one url pattern?
I'm following thenewboston's Django tutorial and no one seems to be running into this problem. I have created a music app with an index view which works fine. Now I want to create detailed views for music albums. music.urls.py: from django.urls import path from . import views urlpatterns = [ # /music/ path(' ', views.index, name='index'), # /music/21/ path('music/<int:album_id>/', views.detail, name='detail'), ] music.views.py: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("<h1>This is the music app homepage") def detail(request): return HttpResponse("<h2>Detail " + str(album_id) + "</h2>") I do get a few warnings in Visual Studio Code stating that Django is unable to import some modules. But if that was the cause then url/music should also return a 404 error? -
Read-only file system: '/srv/media/house_preview/question_4.PNG'
I have a simple Django app deployed to App Engine, which connects to Cloud SQL (PostgreSQL) instance. This Django app allows users to login/register and put up items for sale. Login/register works fine, but when putting up items for sale I get the following error: Request Method: POST Django Version: 3.0.3 Python Version: 3.7.7 Installed Applications: ['projects', 'blog', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/env/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/srv/projects/views.py", line 28, in createListing link.save() File "/srv/projects/models.py", line 24, in save super(Listing_Database, self).save(*args, **kwargs) File "/env/lib/python3.7/site-packages/django/db/models/base.py", line 746, in save force_update=force_update, update_fields=update_fields) File "/env/lib/python3.7/site-packages/django/db/models/base.py", line 784, in save_base force_update, using, update_fields, File "/env/lib/python3.7/site-packages/django/db/models/base.py", line 887, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/env/lib/python3.7/site-packages/django/db/models/base.py", line 926, in _do_insert using=using, raw=raw, File "/env/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/env/lib/python3.7/site-packages/django/db/models/query.py", line 1204, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1383, in execute_sql for sql, … -
How to return PDF file in an Graphql mutation?
I'm using React and Graphql on the frontend and Django and Graphene on the backend. I want to be able to download a pdf file of a report. I try to do it using mutation as follows: const [createPdf, {loading: createPdfLoading, error: createPdfError}] = useMutation(CREATE_PDF) const handleCreatePDF = async (reportId) => { const res = await createPdf({variables: {reportId: parseInt(reportId) }}) debugger; }; export const CREATE_PDF = gql` mutation ($reportId: Int!) { createPdf (reportId: $reportId){ reportId } } `; On the backend I have something like this: class CreatePDFFromReport(graphene.Mutation): report_id = graphene.Int() class Arguments: report_id = graphene.Int(required=True) def mutate(self, info, report_id): user = info.context.user if user.is_anonymous: raise GraphQLError("You are not logged in!") report = Report.objects.get(id=report_id) if not report: raise GraphQLError("Report not found!") if user != report.posted_by: raise GraphQLError("You are not permitted to do that!") html_string = render_to_string('report.html', {'report_id': 1}) pdf_file = HTML(string=html_string) response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="rapport_{}"'.format(report_id) return response # return CreatePDFFromReport(report_id=report_id) When I uncomment return CreatePDFFromReport(report_id=report_id) it works fine. But I want to return pdf file. Is there any possibility to do that? Thanks. -
Django/ Django_plotly_Dash (Exception Value: expected string or bytes-like object)
When I try to render a plot by Django_Plotly_Dash, I get a TypeError. Please, see below my code snippets and a taceback that I get. I've been trying to understand where the problem appears for hours but nothing comes into my mind. Could anybody, please, help me you here? simpleexample.py import dash_core_components as dcc import dash_html_components as html from django_plotly_dash import DjangoDash external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = DjangoDash('SimpleExample', external_stylesheets=external_stylesheets) app.layout = html.Div([ html.H1('Square Root Slider Graph'), dcc.Graph(id='slider-graph', animate=True, style={"backgroundColor": "#1a2d46", 'color': '#ffffff'}), dcc.Slider( id='slider-updatemode', marks={i: '{}'.format(i) for i in range(20)}, max=20, value=2, step=1, updatemode='drag', ), ]) welcome.html {% extends 'base.html' %} {% load static %} {% block content %} {% load plotly_dash %} <block> <div> {% plotly_app name='SimpleExample' ratio=0.45 %} </div> </block> {% endblock %} views.py from django.urls import path from . import views from home.dash_apps.finished_apps import simpleexample urlpatterns = [ path('', views.home, name='home') This is the traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0 Python Version: 3.7.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'django_plotly_dash.apps.DjangoPlotlyDashConfig', 'channels', 'channels_redis'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\milos\statisticsofcorona\templates\base.html, error at line 0 expected string or bytes-like object 1 : {% load … -
Why django class based View (DetailView) only works with a specific variable names
my English is not good, I apologize in advance. My following question is to understand why the variable template_name for example, with class by DetailView only works with exactly that variable name. For example in views.py: from django.views.generic import DetailView # /appPruebaDos/detailView/<int:pk> class DetailViewObject(DetailView): model = Articulo template_name = "plantillaDetailView.html" # varible fijado del tipo DetailView Why I can't use other variable like(this don't work): # /appPruebaDos/detailView/<int:pk> class DetailViewObject(DetailView): model = Articulo templateName = "plantillaDetailView.html" # varible fijado del tipo DetailView I think template_name field is defined in the DetailView dependencies, but how and where is defined? -
How do I get all current sessions from django?
I recently struggled to do this so i thought I would answer my own question to help. Found this out after playing with dir(Session.objects), after importing from django.contrib.sessions.models import Session.