Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF API not linking foreign key via signal
I have a model which has a post_save signal that creates another "default" model when it is created. This "default" model is linked via a foreign key, like so: @receiver(post_save, sender=Theme) def create_default_style(sender, instance, *args, **kwargs): if not instance.styles.exists(): style = Style(theme=instance) style.save() This signal works totally fine when the "Theme" model is created in a dev environment. However, when I try to save the "Theme" model via DRFs API, the "Style" model is linked (as per above code), then somehow the FK relationship is removed. I can't for the life of me figure out what is happening, except that it has something to do with the use of a PrimaryKeyRelatedField in the "Theme" serializer, as follows: class ThemeSerializer(serializers.ModelSerializer): styles = serializers.PrimaryKeyRelatedField(queryset=Styles.objects.all(), many=True, allow_null=True, required=False) If I change the PKRelatedField to a SerializerMethodField, the signal works correctly from both the app and DRF's API. While the workaround (SerializerMethodField) is fine, I am still interested to find out what is causing the problem with the PKRelatedField. -
Three.js and Django?
somebody knows if can i upload a Three.js project to Django? i did a project to upload jpg and png images in Django, but i have another project in three.js to use .OBJ images, but now i neet to include my Three.js project to my Django project but i don't know how and if its posible to do it... Thank u so much! enter image description here files to Django project files to Three.js project -
Django Localization: How to prevent translator from adding CSS or template filters?
For example: Lorem Ipsum <a href="%(ipsum_url)s"><u>Something something</u></a>. Would be an item in django-rosetta. The translator could do something like: Lorem Ipsum <a style="color: red;" href="%(ipsum_url)s"><u>Something something</u></a>. and it would change the styling found on the site. I am also not sure if more malicious things could be done with this. -
django-configurations can't find my configuration when using uwsgi
I'm trying to migrate a Django==2.1 project from one AWS instance to another. I did not create the project so I'm not sure exactly all the steps that they followed for deployment. I see that uWSGI==2.0.19.1 is in the requirements.txt file, so I'm trying to use that to run the project at port 8000. The project also uses the library django-configurations==2.1 to manage multiple configurations. They are in a folder called config with this structure. project/ config/ __init__.py common.py development.py local.py production.py staging.py manage.py wsgi.py ... The __init__.py file inside the config folder contains the following: from __future__ import absolute_import from .local import Local from .staging import Staging from .production import Production from .development import Development I'm trying to run the following command: uwsgi --http :8000 --module wsgi:application --chdir=/path/to/project And I'm getting this error: Traceback (most recent call last): File "./wsgi.py", line 16, in <module> from configurations.wsgi import get_wsgi_application File "/path/to/project/.env/lib/python3.6/site-packages/configurations/wsgi.py", line 14, in <module> application = get_wsgi_application() File "/path/to/project/.env/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/path/to/project/.env/lib/python3.6/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/path/to/project/.env/lib/python3.6/site-packages/django/conf/__init__.py", line 57, in __getattr__ self._setup(name) File "/path/to/project/.env/lib/python3.6/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/path/to/project/.env/lib/python3.6/site-packages/django/conf/__init__.py", line 107, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/path/to/project/.env/lib/python3.6/importlib/__init__.py", … -
Datatable next page not accepting array
I sent some values to the django backend using ajax. I am now trying to pass result as array on ajax success which is working fine on datatable first page. But next page only reads the first value of the array. I have been been working on this for past weeks now. Any help will be appreciated. See my javascript code below on ajax success; var str = ""+response['counting']+""; var myarray = str.split(','); for(var i = 0; i < myarray.length; i++) { alert(myarray[i]); } Datatable next page couldn't read all array content say array is [3,5,11,13]. -
The Black Formatter - Python
I just started using the Black Formatter module with VSCode everything was going well till I just noticed that it uses double quotes over single quotes which I already was using in my code.. and it overrode that.. So, is there an Black Argument that I could add to VSCode which solves this problem? Thanks. -
Plotting multiple JSON subobjects in Chart.js Line chart ( with Time as x-axis)
I'm trying to plot data from multiple channels in Django. My JSON file looks like this: { "Channel1":[ { "Value":123, "Timestamp": someUnixTime }, { "Value":456, "Timestamp": someUnixTime }, { "Value":789, "Timestamp": someUnixTime } ], "Channel2":[ { "Value":312, "Timestamp": someUnixTime }, { "Value":654, "Timestamp": someUnixTime }, { "Value":987, "Timestamp": someUnixTime } ] } How can I plot a line for each channel? P.S. My actual dataset has somewhat around 73 channels and +100k entries. -
ForeignKey is not working django, I am using custom user model and I try both MySQL and PostgreSQL
in my SubUser model ForeignKey is not working when I add some sub user it does not get main user id to its user_id field. I try all solutions from stack overflow and I try this in both MySQL and PostgreSQL, here my codes: dashboard/model.py from django.db import models from django.conf import settings from django.contrib.auth.models import BaseUserManager from account.models import Account from django.contrib.auth import get_user_model # Create your models here. class CustomUserAdmin(BaseUserManager): ordering = ('email',) class SubUser(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True) email = models.EmailField(verbose_name="email", max_length=60, unique=True) fullname = models.CharField(max_length=220) phone_number = models.CharField(max_length=100, unique=True) address = models.CharField(max_length=220) user_role = models.CharField(max_length=220) def __str__(self): return self.fullname dashboard/views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from . import forms from django.conf import settings # Create your views here. @login_required(login_url='account:index') def dashboard(request): return render(request, 'dashboard/table.html') @login_required(login_url='account:index') def add_sub_user(request): form = forms.AddSubUserForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.save() print(settings.AUTH_USER_MODEL) context = {'form':form} return render(request, 'dashboard/add_subuser.html',context) account/modules.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=220, unique=True) fullname = models.CharField(max_length=220) phone_number = models.CharField(max_length=220, unique=True) address = models.CharField(max_length=220) date_joined = models.DateTimeField(verbose_name='data joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) username = models.CharField(max_length=220, unique=True, blank=True) … -
adding initial value to Django model form
I just want to add an initial value to one field when it gets populated, this is my view def add_program(request): module = Module.objects.all() last_item = Programme.objects.filter(module_id__in=module).last() if last_item: day = last_item.day + 1 else: day = 1 initial_data = { 'day': day } if request.method == 'POST': form = ProgramAddForm(request.POST or None, request.FILES or None, initial=initial_data) if form.is_valid(): instance = form.save(commit=False) instance.save() return redirect('program_add') else: form = ProgramAddForm() return render(request, 'client_apps/program/form.html', {'form': form}) and form class ProgramAddForm(forms.ModelForm): class Meta: model = Programme fields = ['module', 'day', .........] even though initial value is passed nothing is visible in day field when form populates, is there any alternative method? -
DJANGO EMAIL CONFIRMATION: [WinError 10061] No connection could be made because the target machine actively refused it
I'm trying to send an email verification code for account confirmation. Now, the thing is that I am trying to send an email to myself first, and my other email. I have turned off my antivirus, so that shouldn't be a problem. Other than this I can't figure our what I did wrong that it is not sending emails on the gmail account. Please point out what I'm doing wrong. I even applied all the fixes mentioned by this thread. views.py from django.core.mail import send_mail from django.shortcuts import render,redirect from django.contrib import messages,auth from django.contrib.auth.models import User # this table already exists in django we import it from django.contrib.auth import authenticate, login from django.conf import settings from django.core.mail import EmailMessage def register(request): if request.method=='POST': fname = request.POST['fname'] lname=request.POST['lname'] #request.post[id of the input field] email = request.POST['email'] password = request.POST['pass'] password2 = request.POST['confirmpass'] agree=request.POST.get('agree') if fname == '': messages.warning(request, 'Please enter First name!') return redirect('register') if lname == '': messages.warning(request, 'Please enter Last name!') return redirect('register') if email == '': messages.warning(request, 'Please enter Email!') return redirect('register') if password == '': messages.warning(request, 'Please enter Password!') return redirect('register') if password2 == '': messages.warning(request, 'Please enter Confirm Password!') return redirect('register') if ('agree' not in … -
Django and Bootstrap Modal
Please help me to progress with my project. I'm new to Django and bootstrap and i'm currently working on a project. For the Registration of the user i'm using a modal. I've set up the following: The modal: <!-- Login/Register Starts --> <!-- Modal --> <div class="sign_up_modal modal fade" tabindex="-1" role="dialog" aria-hidden="true" id=bd-example-modal-lg> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body container pb20"> <div class="row"> <div class="col-lg-12"> <ul class="sign_up_tab nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Login</a> </li> <li class="nav-item"> <a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Register</a> </li> </ul> </div> </div> <!-- Register Modal Starts --> <div class="row mt25 tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab"> <div class="col-lg-6 col-xl-6"> <div class="regstr_thumb"> <img class="img-fluid w100" src="{% static 'images/resource/regstr.jpg' %}" alt="regstr.jpg"> </div> </div> <div class="col-lg-6 col-xl-6"> <div class="sign_up_form"> <form action="{% url 'register' %}" method="POST" id="register-form"> {% csrf_token %} {{form.as_p}} <div class="heading"> <h4>Register</h4> </div> <div class="row"> <div class="col-lg-12"> <button type="submit" class="btn btn-block btn-fb"><i class="fa fa-facebook float-left mt5"></i> Login with Facebook</button> </div> <div class="col-lg-12"> <button type="submit" class="btn btn-block btn-googl"><i class="fa fa-google float-left mt5"></i> Login with Google</button> </div> </div> <hr> <div class="form-group ui_kit_select_search mb0"> <select class="selectpicker" data-live-search="true" data-width="100%"> <option data-tokens="SelectRole">Landlord</option> … -
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 …