Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pisa.CreatePDF vs national characters
i'm using pisa.CreatePDF to generate pdf file from an HTML template in the following way: template = get_template('/app/templates/pdf/sth.html') html = template.render(dt) f = open('/tmp/sth.pdf', 'wb') pisa.CreatePDF(BytesIO(html.encode('UTF-8')), dest=f, encoding='UTF-8') . The sth.html has the following code to get Hungarian national characters: <style type="text/css"> @page { size: A4; margin: 1cm; } @font-face { font-family: Arial; src: url({{ font_link }}); } ... </style> , where font_link is an URL to a TTF font (Vera.ttf). When I generate the pdf file, and I open it with chrome, it works fine, but if I open the same file with an external pdf viewer (for instance xpdf) it shows rectangles instead of the special Hungarian characters which are not in ASCII. I've never seen that a pdf is opened differently with different viewers, but I guess it's because of the link to the font. How could I use the same font file, but in a way that the content of the font file will be included in the pdf file? So I can open correctly the generated pdf file without having access to the Vera.ttf itself? -
Django Rest API for simple python dictionary
I'm new to Django and I want to make a simple restful API that will return the python dictionary in JSON format upon calling it from the postman. I have set up my project folder and have installed the RestfulAPI frame and also I have configured my settings.py For example, In dictionary.py I have the following code dataDictionary = { 'hello': 'World', 'geeks': 'forgeeks', 'ABC': 123, 456: 'abc', 14000605: 1, 'list': ['geeks', 4, 'geeks'], 'dictionary': {'you': 'can', 'send': 'anything', 3: 1} } and I want to return this dict upon calling it from Postman by entering the URL http://127.0.0.1:8000/getdata/ by using Method POST. I have attached the Django APP VIEW picture. Django_APP -
How can I fill a pdf with previously created dynamic data. with django
I have a small form that takes approximately 15 fields from the user, I want to use those 15 fields and dynamically pass them to a PDF (a report with images, approximately 10 pages, and a lot of text), and fill it with certain fields that the client gave me, which It would be the most optimal way to do it thanks -
Getting an error during AJAX POST in DJANGO
I have a POST request from ajax. At the backend some records are updated in the django view, this is done fine but an error comes up and the page isnt reloaded. This is the error: SyntaxError: Unexpected token O in JSON at position 0 This is the ajax: $.ajax({ headers: { "X-CSRFToken": token }, "url": '/articulos/massup/', "type": "POST", "dataType": "json", data: data, success: function(e){ if(e="OK"){ location.reload(true); } }, error: function(a,b,c){ alert(c); } }); }); Thi is the view: @csrf_exempt def massup(request): template_name = "articulos/articulos_ok.html" contexto={} if request.method=="GET": cat = Articulos.objects.all().order_by("codigo") contexto={"obj":cat} if request.method=="POST": codigos=request.POST.getlist("codigos[]") porcentaje = codigos[0]#el primer elemento de la lista es el porcentaje porcentaje=Decimal(porcentaje) codigos= [int(x) for x in codigos]#Convierte la lista en integer art_change = Articulos.objects.filter(pk__in=codigos) i=0 for item in art_change: if i!=0: #Excluye el primer item ( el porcentaje) precioant=item.precio precionuevo=(precioant + (porcentaje * precioant/100)) item.precio=precionuevo item.save() i=i+1 return HttpResponse("OK") return render(request,template_name,contexto) -
How do I display context of render() on a new html page?
Creating an app to access data from an API, SpotifyAPI. The API returns a dictionary when I call query methods, also defined a route in my urls.py to map to a view a form is instantiated in. After typing in an input to the form and submitting, I want the input(which is an ID) as an argument to a method which returns a dictionary. Now, I try to access a value in a key and render that value into a template named display.html but after submitting the form, nothing actually happens. I get directed back to the form page but with an altered URL with this included in the URL /&SpotifyForm=Jay+Z if input was "Jay Z", rather than being directed to display.html with the rendered data. forms.py class SpotifyForm(forms.Form): SpotifyForm = forms.CharField(label= "Spotify Form") urls.py urlpatterns = [ path("home/" , Search.as_view() , name= "home"), ] views.py class Search(View): form = SpotifyForm template_name = "spotify_calls/homepage.html" context = {"form": form} def get(self, request): return render(request , self.template_name, self.context) def post(self, request, *args , **kwargs): form = self.form(request.POST) template_name= "spotify_calls/display.html" if form.is_valid(): _id = form.cleaned_data["SpotifyForm"] SpotifyAPI(self.client_id , self.client_secret) get = SpotifyAPI.get_artist(self, _id) artiste_name = get["name"] context = {"context" : artiste_name} return render(request , … -
Django REST Serializer make all fields allow_null or not required
I need to apply extra_kwargs on all fields in a model (Over 20 fields), except one or two. I know one method is: class MySerializer(serializers.ModelSerializer): field1 = serializers.CharField(allow_null=True,required=False) or class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' extra_kwargs = { 'field1': {'required': False, 'allow_null': True},} But it gets too inefficient when I have to apply this to each field one by one. Is there anything that can help me do something like this ? extra_kwargs = { '__all__': {'required': True, 'allow_null': False}, -
How do you execute an external python script using an html button/form
Basically, I'm wondering if in my HTML document I can reference my python script in the same project and execute it at the push of a button. I'm using Django if that holds any relevance, thanks in advance! -
Emails with attachments in Django Python
I am currently programming a blog in which users can send me post requests through a formular I implemented on the website. I also would like them to send me attachments, that is why I put in my form the possibility to load image files. However, the email that I receive from the form does not display the image, it just displays the name of the attachment. I need to add some line of codes to my sendemail function. Any suggestion? <3 ''' def publicationmemoria(request): if request.method == "POST": inputEmail = request.POST['inputEmail'] inputNome = request.POST['inputNome'] inputCognome = request.POST['inputCognome'] inputImmagine1 = request.POST['inputImmagine1'] send_mail( 'Richiesta di pubblicazione - Memoria', #subject 'Dati persona di contatto:' + '\n' + 'Email:' + ' ' + inputEmail + '\n' + 'Nome:' + ' ' + inputNome + '\n' 'Cognome:' + ' ' + inputCognome + '\n' + inputImmagine1 , # message inputEmail, # from email ['myemail.com'], # to email ) return render(request, 'publication-memoria.html', {'inputEmail': inputEmail, 'inputNome': inputNome, 'inputCognome': inputCognome, 'inputImmagine1': inputImmagine1, }) else: return render(request, 'publication-memoria.html', {}) ''' -
Django: Filter for month with timezone (after switching from SQLite to PostgreSQL)
In preparation for deployment, I switched from SQLite to PostgreSQL (following this advice). Now I have some trouble filtering certain items for timestamp by month which I didn't have before with SQLite. The problem is, that I get the items of the previous month instead of the current one. Look, this is what my code basically looks like: models.py class Dummy(models.Model): … timestamp = models.DateTimeField() … views.py … current = datetime.date.today().replace(day=1) dummies = Dummy.objects.values(month=TruncMonth('timestamp')). filter(month__year=current.year). filter(month__month=current.month) … I actually have several Dummy entries for the current month (which is 10), but dummies remain empty. If I replace current.month with 9, I get exact these entries. Like I said before, this is only the case with PostgreSQL. As long as I used SQLite, everything was OK. After some research I understand where the problem apparently comes from: there seems to be a difference how these different types of databases handle the timezones, see e.g. this answer. The timestamp of the Dummy entries is stored as UTC in the database itself. If I look at one item of dummies (which I get with 9 as mentioned above), it has month values like that: datetime.datetime(2020, 10, 1, 0, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>) … -
How to use pytest fixtures with django TestCase
How can I use a pytest fixture within a TestCase method? Several answers to similar questions seem to imply that my example should work: import pytest from django.test import TestCase from myapp.models import Category pytestmark = pytest.mark.django_db @pytest.fixture def category(): return Category.objects.create() class MyappTests(TestCase): def test1(self, category): assert isinstance(category, Category) But this always results in an error: TypeError: test1() missing 1 required positional argument: 'category' I realize I could just convert this trivial example into a function, and it would work. I would prefer to use django's TestCase because it includes support for importing traditional "django fixture" files, which several of my tests require. Converting my tests to functions would require re-implementing this logic. package versions: Django==3.1.2 pytest==6.1.1 pytest-django==4.1.0 -
How to manage multiple views and urls in django?
I want to add multiple charts in one web page as we do to make dash-boards. I made two views for two charts. **def index(request): gapminder = px.data.gapminder() plot_div = plot(px.scatter(gapminder.query("year==2007"), x="gdpPercap", y="lifeExp", size="pop", color="continent", hover_name="country", log_x=True, size_max=90),output_type='div') return render(request, "index.html", context={'plot_div': plot_div}) def indexx(request): random_x = [100, 2000, 550] names = ['A', 'B', 'C'] plot_div = plot(px.pie(values=random_x, names=names),output_type='div') return render(request, "index.html", context={'plot_divv': plot_div})** and two URLs too. **from django.urls import path from . import views urlpatterns = [ path('', views.index), path('', views.indexx), ]** but in result only one chart is visible, the one which URL is on top. I am a newbie kindly help. -
Django: How to run python scripts on a running env with gunicorn
I was wondering how I could run some external python scripts on my django application while it is running with gunicorn and nginx ? Locally without gunicorn and web server, I would just open a python shell using the below: python manage.py shell Then run my python script on my django application with the following: exec(open('myscript.py').read()) Can you please advise ? Kind regards. -
Django Environment Variables coming from docker-compose.yml but don't effect the project
I have been working on this all day and I am completely confused. I have create a Django project and using docker and a docker-compose.yml to hold my environment variables. I was struggling to get the DEBUG variable to be False. But I have since found out that my SECRET_KEY isn't working either. I have added a print statement after the SECRET_KEY and it prints out (test) as that is what I currently have in the docker-compose.yml file but this should fail to build... If I hard code the DEBUG I can get it to change but I have completely removed the secret key and the project still starts. Any ideas where Django could be pulling this from or how I am able to trace it back to see? settings.py SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = os.environ.get('DEBUG') docker-compose.yml version: '3.8' services: web: build: . container_name: django command: gunicorn config.wsgi -b 0.0.0.0:8000 environment: - ENVIRONMENT=development - SECRET_KEY=(test) - DEBUG=0 - DB_USERNAME=(test) - DB_PASSWORD=(test) volumes: - .:/code ports: - 8000:8000 depends_on: - db - redis celery: build: . image: celery container_name: celery command: celery -A config worker -l INFO volumes: - .:/code environment: - SECRET_KEY=(test) - DEBUG=0 - DJANGO_ALLOWED_HOSTS=['127.0.0.1','localhost'] - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=redis://redis:6379/0 … -
How can i get date from multiple table in django
how can i get data from this below django html template <form action="{% url 'purchase_order_item' p_order.id %}" method="post" enctype="multipart/form-data" class="form-group"> {% csrf_token %} <table id="example-datatable" class="table table-vcenter table-condensed table-bordered"> <thead> <tr> <th>#</th> <th>Name</th> <th>Brand Name</th> <th>Product Type</th> <th>Category</th> <th>SubCategory</th> <th>Quantity</th> <th>Unit Price</th> <th>Action</th> </tr> </thead> <tbody> {% for p in product %} <tr> <td>{{p.id}}</td> <td> {{p.name}} </td> <td>{{p.brand}}</td> <td>{{p.ptype}}</td> <td>{{p.catname}}</td> <td>{{p.supplier}}</td> <td> <input type="text" id="quantity" name="quantity" value="1" class="form-control"> </td> <td> <input type="text" id="unitprice" name="unitprice" value="1" class="form-control"> </td> <td> <button type="submit" class="btn btn-primary btn-xs">Add</button> </td> </tr> {% endfor %} </tbody> </table> </form> views.py def purchase_order_item(request,id): now = datetime.datetime.now() year = now.year month = now.month day = now.day if (len(str(day))) == 1: day = '0' + str(day) if (len(str(month))) == 1: month = '0' + str(month) date = str(year) + '-' + str(month) + '-' + str(day) randstrn = "" for i in range(5): randstrn = randstrn + random.choice(string.digits) # catid = Cat.objects.get(name=name).pk # news = News.objects.filter(ocatid=catid) # showing post based on master category supplier = Supplier.objects.all() p_order = Purchase_order.objects.get(pk=id) product = Parts.objects.all() # this is the form for getting data from html if request.method == 'POST': quantity = request.POST.get('quantity') unit_price = request.POST.get('unitprice') # itemid = pk type nameid = request.POST.get('quantity') ref_num … -
csv.writer writing each character of word
I am trying to export a list of names from a Model like this: def export(request): response = HttpResponse(content_type='text/csv') writer = csv.writer(response) writer.writerow(['Location']) #header for launch in Location.objects.all().values_list('L_name'): export_data = zip_longest(*launch, fillvalue='') writer.writerows(export_data) response['Content_Disposition'] = 'attatchment'; return response Writerow is iterating on the characters of each name, producing a column of characters rather than names. Instead, I would like each name in its own row. Any ideas on how to achieve this? Thank you for any input. -
django websocket connection failed during web socket handshake in js console
I am trying django channels in my django projects. i have to fetch data from redis server and populate it in a datatable. I tried and established the code in my custom signin page, and the list of objects was printing there without an error. even connection had no error. but when i tries to connect it after logged in . it shows this error below in console. WebSocket connection to 'ws://localhost:8000/ws/data/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET -
How to auto-populate database field using data from other fields in the same model
I have a model called Coverletter with 4 fields: company, role, job_posting, content. I am trying to use the data from the first 3 fields to populate data in the 4th field. Right now, the user inputs values for 3 fields in a form: (company, role, job_posting) using a class based view CreateView. class CoverletterCreateView(LoginRequiredMixin, CreateView): model = Coverletter fields = ['company', 'role', 'job_posting'] template_name = 'coverletter/coverletter_create_form.html' def form_valid(self, form): form.instance.owner = self.request.user return super().form_valid(form) def get_success_url(self): return reverse('coverletter:coverletter-create-content', kwargs={'pk': self.object.pk,} ) The user is then redirected to another class based view UpdateView via get_success_url, where the first three fields are showing with populated values. class CoverletterCreateContentView(LoginRequiredMixin, UpdateView): model = Coverletter fields = ['company', 'role', 'job_posting', 'content'] template_name = 'coverletter/coverletter_create_content_form.html' Right now the 4th field (content) is blank, but I am trying to populate the content field when the user submits the data from the first CreateView. The data is an html string that would look something like this: <p>Dear {{ company }} I am excited to be applying for the {{ role }} role.</p> I am very new to Django and web development, and am struggling to understand how to do this. I am unsure where in the app … -
I cant not get my data from my django form
I can't print my form.cleaned_data. Look like it the button that it not working correctly. When I press the buttom 'send' nothing is printed on my terminal. Thank you for the help im new to django. views.py from django.shortcuts import render from .forms import NameForm def get_name(request): if request.method == "POST": form = NameForm(request.POST) if form.is_valid(): name = form.cleaned_data["your_name"] message = form.cleaned_data["message"] print(name) print(message) else: form= NameForm() return render(request, "pools/home.html", {"form": form}) forms.py from django import forms class NameForm(forms.Form): your_name = forms.CharField(label="Your name" ,max_length=100) message = forms.CharField(widget=forms.Textarea) home.html {% extends "pools/base.html" %} {% load crispy_forms_tags %} {% block content %} <h1>Hello world</h1> <div class="content-section"> <form method="POST"> {% csrf_token %} {% crispy form %} <button class="btn btn-outline-info" type="submit">Send</button> </form> </div> {% endblock content %} -
How get only games with support json
I have a code def get_current_user_steam_games(user_id): return requests.get( f'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key={settings.STEAM_API_KEY}&' f'steamid={get_steam_id(user_id)}&format=json&include_appinfo=1').json()['response'] and this code show me on html it how i can get only name names of games? Thank you -
Django unit test "matching query does not exist"
I'm trying to unit test a model but I keep getting "Donation matching query does not exist," with the traceback pointing to the first line in the test_charity function. I tried getting the object with charity='aclu' instead of by ID, but that did not fix it. from django.test import TestCase from .models import Donation class DonateModelTest(TestCase): def init_data(self): #print("got here") x = Donation.objects.create(charity='aclu', money_given=15) # print(x.id) def test_charity(self): donation = Donation.objects.get(id=1) field_label = donation._meta.get_field('charity').verbose_name self.assertEquals(field_label, 'charity') My models.py: from django.db import models class Donation(models.Model): DONATE_CHOICES = [ ('aclu', 'American Civil Liberties Union'), ('blm', 'Black Lives Matter'), ('msf', 'Medecins Sans Frontieres (Doctors Without Borders)') ] charity = models.CharField( max_length=4, choices=DONATE_CHOICES, default='aclu' ) money_given = models.IntegerField(default=0) -
str vs repr, in django documentation shows str return instead of repr return
In the django doc https://docs.djangoproject.com/en/3.1/intro/tutorial02/ they add the str dunder but when they type the class in cmd, instead of showing the repr ugly object it shows the str return. My question is,why aren't we seeing the repr we simply see the class on cmd? shouldn't it show the str return text only when i print(class)? class Question(models.Model): question_text=models.CharField(max_length=200) pub_date=models.DateTimeField('date published') def __str__(self): return self.question_text #Make sure our str() addition worked. Question.objects.all() <QuerySet [<Question: What's up?>]> -
Django 404 error GET Request URL: http://localhost:8000/ keeps popping up when blank url is requested
I was following this tutorial by tom artyn. My code was exactly as his in the book, however, everytime i try to render my web page on the localhost server, i keep getting Page not found (404) Error. Here is my project(config) url: from django.urls import path, include from django.contrib import admin import core.urls urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls', namespace = 'core')), ] Here is my app(core) url: from django.urls import path from . import views app_name ='core' urlpatterns = [ path('movies', views.MovieList.as_view(), name = 'MovieList'), ] Here is my app(core) view: from django.views.generic import ListView from core.models import Movie # Create your views here. class MovieList(ListView): model = Movie Here is my app(core) admin: from django.contrib import admin # Register your models here. from core.models import Movie admin.site.register(Movie) I have no clue why request doesn't match the '' url. Page not found (404) Request Method: GET Request URL: http://localhost:8000/ Using the URLconf defined in config.urls, Django tried these URL patterns, in this order: admin/ movies [name='MovieList'] The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display … -
django makemessages does nothing
When I run django-admin makemessages -l en nothing happens and no po files are created This is my folder structure /myproject myapp/ locale/ media/ static/ templates/ db.sqlite manage.py settings.py urls.py wsgi.py settings.py import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', ] 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', 'django_user_agents.middleware.UserAgentMiddleware', ] ROOT_URLCONF = 'urls' WSGI_APPLICATION = 'wsgi.application' LANGUAGE_CODE = 'fr' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [os.path.join(BASE_DIR, 'locale')] My folder structure is different because I moved settings.py, urls.py and wsgi.py to the project root, and I'm not sure if this is why makemessages is not working. -
Regular expressions and russian symbols in Django
I have the one url like this url(ur'^gradebook/(?P[\w\-А-Яа-я])$', some_view, name='some_view') and I expect it to process a request like ../gradebook/group='Ф-12б' but I get an error and the server crashes. Please help me figure out the Russian symbols -
Retrieving URL parameters in the order they are passed - django
I am trying to retrieve the URL parameters that are passed into the function, in the order they are acutally passed. The reason this matters, is its a payment provider integration, which calculates a hash from concatenating the values that are passed (in the order they are passed). So based on this, i need to access the parameters in the order they are passed in the actual URL, concatenate them and then add a MD5 key that is secret to my account to verify the request. For example: http://example.com/order/callback?date=20200101&currency=USD&txnid=1234567&hash=thegeneratedhas If i access the request through request.GET I get ordered dict. pseudo-code def callback(request): keys_concatenated = "" for value in request.GET: if value == "hash": pass else: keys_concatenated = keys_concatenated + request.GET[value] This generates a string like: USD202001011234567 The hash generated from the provider that the order is kept, and thus is expecting the value 20200101USD1234567 Defining the parameters within urls.py is not really something I want as the payment provider is openly saying that they might change parameters passed, and thus it would break the implementation. I also dont know the actual order they are passing it in from time to time.