Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using the request object in forms.py
I am working on an e-voting system where there are aspirants vying for particular positions. I am trying to create a form where the aspirants are displayed per position in RadioSelect buttons. To do this, I have tried to initialize a for loop through all the objects in the Position() class and used an if statement to compare the current url path to the get_absolute_url() of each object. I have trouble getting the request module to work. class VotingForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(VotingForm, self).__init__(*args, **kwargs) def get_url(self): self._ = [] for post in Position.objects.all(): if self.request.get_full_path() == "/post/pro": no_ = Position.objects.get(post='PRO') self._.clear() for i in Aspirant.objects.filter(post=no_): self._.append(tuple([i.name, i.name])) elif self.request.get_full_path() == "/post/gen-sec": no_ = Position.objects.get(post='General Secretary') self._.clear() for i in Aspirant.objects.filter(post=no_): self._.append(tuple([i.name, i.name])) return _ CHOICES = self.get_url() aspirants = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) class Meta: model = Aspirant fields = ['aspirants'] I'm getting this error. I'm not sure what I am doing wrong. CHOICES = self.get_url() NameError: name 'self' is not defined -
Python Generate PDF with HTML Contents
I want to use reportlab PDF library (community version) to generate a PDF report from MySQL table. There is a text field which contains HTML tags (edit using Tinymce Editor) I want to include into the PDF report. I tried but seems reportlab could not recognized those html tags so that error was produced when running the report. My question is does it correct that html text field could not be included into the reportlab PDF to generate formatting of the output? Or is there any other solution for generate the PDF include html tags? Thank you! -
Display custom form in Django admin
I created a custom user model with country in it: models.py class CustomUser(AbstractUser): country = models.CharField(max_length=50, default="None") Then added custom forms with form field country which is a ChoiceField and shows all the countries: forms.py class CustomUserCreationForm(UserCreationForm): country = forms.ChoiceField(choices=sorted(COUNTRIES.items()), label="Country") class Meta(UserCreationForm): model = CustomUser fields = '__all__' class CustomUserChangeForm(UserChangeForm): country = forms.ChoiceField(choices=sorted(COUNTRIES.items()), label="Country") class Meta(UserChangeForm): model = CustomUser fields = '__all__' Then I registered it in the admin with: admin.py class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username', 'is_staff',] admin.site.register(CustomUser, CustomUserAdmin) It registered and everything is working fine, I am able to save the model with Django shell and programmatically, but I am not able to display it in the admin console. When I try to try to create a new user from the admin, I just see three fields - username, password and password confirmation. Do I have to extend the admin template for this new field to show up? -
Protection against malicious PNG in Django
I found following security notice on Django website: Django’s media upload handling poses some vulnerabilities when that media is served in ways that do not follow security best practices. Specifically, an HTML file can be uploaded as an image if that file contains a valid PNG header followed by malicious HTML. This file will pass verification of the library that Django uses for ImageField image processing (Pillow). When this file is subsequently displayed to a user, it may be displayed as HTML depending on the type and configuration of your web server. Unfortunately there is no addition information how to protect website agains that malicious PNG so i have some questions: How should i configure my webserver (nginx)? How can i generate html as PNG to upload it on server and ensure it will not displayed as html? Should i add additional image check on upload and what is best solution/library (libmagick probably) for that? -
How I get User ID if logged in Django?
I need to get User ID inside from my code (not in Django template). I've success in template, but not inside the App. Someone can help me? -
How to solve operationError: no such table
I'm setting up my new website,but the web have some problem . It prompt me that OperationalError at /topics/ and no such table:toms_topic This is a heroku web,running django2.2,python3.7.3, I have execute 'python manage.py migrate', and I go to the db.sqlite , find the table'toms_topic' is exist. -
Django: How to save checkbox choice?
I'm trying to save the user's choice of the checkbox for whether they have completed an event or not. I just want the checkbox to be able to save the user's previous choice on a page refresh. Every time the page refreshes the value is set back to False, or, unchecked. utils.py def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: d += f'<li><label> {event.get_html_url} <input type="checkbox"></label></li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' views.py def event(request, event_id=None): instance = Event() if event_id: instance = get_object_or_404(Event, pk=event_id) else: instance = Event() form = EventForm(request.POST or None, instance=instance) if request.POST and form.is_valid(): event = Event.objects.create(**form.cleaned_data, user=request.user) print(event.title) return HttpResponseRedirect(reverse('cal:calendar')) return render(request, 'cal/event.html', {'form': form}) models.py class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(max_length=350) start_time = models.DateTimeField() end_time = models.DateTimeField() event_checked = models.BooleanField(default=False, blank=True) @property def get_html_url(self): url = reverse('cal:event_edit', args=(self.id,)) return f'<a href="{url}">{self.title}</a>' forms.py class EventForm(forms.ModelForm): #event_done = forms.BooleanField() class Meta: model = Event # datetime-local is a HTML5 input type, format to make date time show on fields widgets = { 'start_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), 'end_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), } fields = ('title', 'description', 'start_time', 'end_time') def … -
the object has no attribute 'is_hidden' with django
i am building a form with django, and i am getting this error: 'CharField' object has no attribute 'is_hidden' but the charField actually it has the attribute, as you can see: class ArticleForm(forms.ModelForm): class Meta: model = Articulo fields = [ 'nombre_producto', 'id_clasificacion_fk', 'Descripcion', 'long_descripcion', 'precio', 'cantidad', ] labels = { 'nombre_producto': 'Nombre del producto', 'id_clasificacion_fk': 'Clasificación del producto', 'Descripcion': 'Corta descipción', 'long_descripcion': 'Larga descipción', 'precio': 'Precio del producto', 'cantidad': 'Cantidad en inventario', } widgets = { 'nombre_producto': forms.TextInput(attrs={'class':'form-control'}), 'id_clasificacion_fk': forms.Select(attrs={'class':'form-control'}), 'Descripcion': forms.TextInput(attrs={'class':'form-control'}), 'long_descripcion': forms.TextInput(attrs={'class':'form-control'}), 'precio': forms.CharField(widget=forms.NumberInput), 'cantidad': forms.CharField(widget=forms.NumberInput), } anyone can help me? Thank you!. -
Django rest framework, what is the difference between mixins and generics?
I'm learning about Django rest framework. And there are two concepts that from my point of view are almost the same, and they are used in different scenarios. rest_framework mixins I think that they are used when we use viewsets. And rest_framework generics are used with APIViews. I'll really appreciate if someone could explain me the difference between these two components. -
Django - suddenly logging to (runserver) console
I can't figure out why Django started to log into the console. When I run django server (in PyCharm), there are log entries in the same console. I've recently installed my fork of pysendpulse but it may be a coincidence. INFO [2019-04-08 00:59:05,331] Initialization SendPulse REST API Class DEBUG [2019-04-08 00:59:05,331] Try to get security token from 'MEMCACHED' DEBUG [2019-04-08 00:59:05,331] Got: 'some string' INFO [2019-04-08 00:59:05,775] Initialization SendPulse REST API Class DEBUG [2019-04-08 00:59:05,775] Try to get security token from 'MEMCACHED' DEBUG [2019-04-08 00:59:05,775] Got: 'some string' Performing system checks... System check identified no issues (0 silenced). DEBUG [2019-04-08 00:59:06,025] (0.001) SELECT c.relname, c.relkind FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r', 'v') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND pg_catalog.pg_table_is_visible(c.oid); args=None DEBUG [2019-04-08 00:59:06,026] (0.000) SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"; args=() April 08, 2019 - 00:59:06 Django version 2.1.7, using settings 'p.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. For example the first line is logged from this: logging.info("Initialization SendPulse REST API Class") settings.LOGGING LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{asctime} {levelname} {module} {message}', 'style': '{', }, }, 'handlers': { 'local_file_debug': { … -
Send two or more parametters in a view based on functions with django
i am developing a webpage with django, but i was wondering if there is a way to send two or more parametters in a view based on functions. Like this: def index(request): categoria = Clasificacion.objects.all() contexto = {'categoria':categoria} articulo = Articulo.objects.all() contexto1 = {'articulo':articulo} return render(request, 'home/index.html', contexto, contexto1) As you can see, i am trying to send "contexto" and "contexto1" to the template, but it receives just one of them (just the "contexto"). This is the part of my urls.py for that function, if you need it: url(r'^home', index, name='home'), So, anyone can help me?. Thanks a lot!. -
Django new dataset in relation from template
in Django Admin i create i new dataset in a Table. On Fields with datatype ForeignKey there are a edit and a create new icon. Now i click create new icon and and i get new pop up with the relation. Now i can create an new dataset in the relation and after save pop up close the window close and in original window in original relation field the new dataset is registered. Now i want in my own form in the frontend exactly the same: new icon for create new dataset in the relation, after click pop up open. User can create new dataset. After submit this dataset must save and after save window close and the new dataset ist registered in the original field. Image from Admin: https://imgur.com/a/yN5eL8i Thanks I google as much i can but i don't find anything. I try with ajax but i have no success. -
How to use database-routers to suggest database to use on basis of active session instead of model?
The official documentation of django, other answers on stackoverflow and other resources provide tutorial/example for database routing on the basis of model. In other words, they assume the scenario as if database selection depends on the model we want to operate. That means, few models get operated on few databases, and remaining models operate on the remaining databases. My scenario or what I want is: I want all models specified in models.py to be stored in all databases. The database selection must be decided by the current session going on of user. Every user has his own database and every database has every model. How do I implement this? (Hope I am clear enough.) What sources says: def db_for_read(self, model, **hints): if model._meta.app_label in ['auth','admin','sessions','contenttypes']: return 'devops' return None I want something like: def db_for_read(self, request, **hints): if request.session.get('username'): # If I name databases as per usernames return request.session['username'] -
How to run scrapy spiders from Django commands
When I try running a crawling command with manage.py crawl I get an error. I have tried to run crawling code without command but it raises another error about Django environment setting. crawl.py from django.core.management.base import BaseCommand from events_scraper.spiders.Bassiani import BassianiSpider from events_scraper.spiders.Khidi import KhidiSpider from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings class Command(BaseCommand): help = "Release the spiders" def handle(self, *args, **options): process = CrawlerProcess(get_project_settings()) process.crawl(BassianiSpider) process.crawl(KhidiSpider) process.start() error I get Error response from daemon: OCI runtime create failed: container_linux.go:344: starting container process caused "exec: \"pyhton\": executable file not found in $PATH": unknown -
In which place should Tensorflow code in Django be added
I am new to Django and I am developing an endpoint that when given some details it executes a deep learning model and send back results as a json. I am having a hard time figuring out where to put this code. I tried putting them in different normal python files in the directory and trying to import them in vie and call functions but that did not work. Please help. given below is my current "views.py file": from django.shortcuts import render from django.http import HttpResponse,JsonResponse from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.parsers import JSONParser from . models import RNNConfig, responseConfig from . serializers import ConfigSerializer,ResultSerializer from django.views.decorators.csrf import csrf_exempt # import create_graph import pandas as pd import tensorflow as tf import numpy as np from .news20 import * from .stockPred import * @csrf_exempt def RNNConfigView(request): if request.method == 'POST': netInfo = JSONParser().parse(request) # netInfo_serialized = ConfigSerializer(netInfo) if netInfo['dataset'] == "Stock Price": resObj = stockPred.RunModelStock(netInfo) elif netInfo['dataset'] == "20 News Groups": resObj = news20.RunModel20News(netInfo) res_serialized = ResultSerializer(resObj) # metric_info = create_graph.runGraph(netInfo) return JsonResponse(res_serialized.data, safe=False) # return HttpResponse(netInfo["rnnNodes"]) Then in that same directory, I created "stockPred.py" with the Tensorfloe code. … -
Can a TextField value of a Django object fail to compile as a regex pattern?
I am trying to build a system where users are able to define and test their own regex patterns. To do this, I have the following setup: import re class ExtendedRegexValidator(models.Model): pattern = models.TextField( _('pattern'), help_text=_('Required. Must be a valid regular expression pattern.') ) def save(self, *args, **kwargs): try: re.compile(self.pattern) except Exception as e: # handle exception super(ExtendedRegexValidator, self).save(*args, **kwargs) Before saving, I try to compile a regex pattern using the value of the pattern field of the model, which is a TextField. Is this actually necessary? Is there a more ideal way to do this? This kinda feels hacky. Thanks. -
Querying multiple tables and returning a combined queryset in Django while hitting the database once
Lets say I have the following models setup: class X(models.Model): ... class Y(models.Model): x = models.ForeignKey(X) class Z(models.Model): x = models.ForeignKey(X) Now, in a method, I want to get all the Y objects and Z objects that are related to a given X object. I want to hit my database once, and return a combined queryset. Right now, I am doing it like this: x = X.objects.get(pk=1) queryset = [] for cls in [Y, Z]: queryset += list(cls.objects.filter(x=x)) Note: running it through a loop is important because there are quite a few models in my actual code, so looping keeps the whole thing DRY. How can I do this? Thanks. -
Issue with Django foreign key assignment
I have a series of related models. Country -> League -> Team -> Player. The model works fine relating country to league and league to team, but the team id is different as teams play in more than one competition. To deal with this I've added a ref column with an id for each team. I would like to use this ref column as the Foreign Key in my player model but I'm getting errors when I try to parse the data to the Postgres database. I've tried using to_field and unique=True but still end up with an error. I've taken a look around but haven't found a solution yet. Here is my models code: from django.conf import settings from django.db import models from django.utils import timezone import datetime class Country(models.Model): objects = models.Manager() name = models.CharField(max_length=50,default="TBA") id = models.IntegerField(primary_key=True,default=0) def __str__(self): return self.name def __unicode__(self): return u'%s' % self.name class League(models.Model): objects = models.Manager() name = models.CharField(max_length=100,default="TBA") id = models.IntegerField(primary_key=True,default=0) country = models.ForeignKey(Country,on_delete=models.CASCADE) def __str__(self): return self.name def __unicode__(self): return u'%s' % self.name class Team(models.Model): objects = models.Manager() name = models.CharField(max_length=100,default="TBA") id = models.IntegerField(primary_key=True,default=0) league = models.ForeignKey(League,on_delete=models.CASCADE) ref = models.IntegerField(default=0) def __str__(self): return self.name def __unicode__(self): return u'%s' % … -
Keep getting 404 errors with django 2.2
I am following this tutorial https://docs.djangoproject.com/en/2.2/intro/tutorial01/ and I am getting 404 errors when I try the first test saying it cannot find "polls/" below is some of my code in mysite/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] in polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] I tried searching but I can't find anything for django 2.2 -
Customizing the user registration flow using django rest-auth for social authentication
I am stuck with a situation and can't seem to find a good solution on how to proceed further. Currently, I am able to authenticate a user using google. So the person is able to create an account and logs in. However, in doing so, the user already has a randomly generated username and all. I want to create a situation where when a user is authenticated via google, they are redirected to a registration form where they can provide a username of their own choice, a small bio and some interesting topics. What is the most efficient way of going about this? My main goal is to ensure that the blacklisted usernames which we can provide in the allauth settings is also utilized when a user provides their own username.So basically, a user is authenticated via socail app, an account is made, and then the person gets to register their personal data. I am not sure about what the best approach would be in this case. -
using marshmallow in flask manipulating data before inserting data in database
I am trying to validate my data which i am posting through post request and i want to check if the data i proper or not and with that i want to do type casting and manipulate the data. I have tried to manipulate the data but its not working and i cant understand what is wrong as i am new in flask so i would like to learn. def check_name(self, obj): if not obj.first_name: return False else: return True @pre_load def process_email_address(self, in_data): in_data['email_address'] = in_data['email_address'].upper().strip() return in_data class InfoSchema(Schema): # first_name = fields.Function(lambda obj: obj.first_name.lower().strip() if obj.first_name else False) # first_name = fields.Method(check_name) first_name = fields.Str(required=True) username = fields.String(required=True) last_name = fields.String(required=True) email_address = fields.String(required=True) phone_number = fields.String(required=True) password = fields.String(required=True) pincode = fields.String(required=True) city_id = fields.String(required=True) class DataSchema(Schema): info = fields.Nested(InfoSchema) auth_token = fields.Nested(AuthTokenSchema) class UserAuthSchema(Schema): meta = fields.Nested(MetaSchema) data = fields.Nested(DataSchema) # @validates('age') # def validate_age(self, data): # if data < 14: # raise ValidationError('Too young!') i want to check if the data is present and its not empty and also remove the spaces from it and and the most important i want to check if the data is in integer and if it is not … -
Multiple environments on one server
What is the best practice or tutorial to set up a droplet to showcase my React/Express and Django fullstack projects on a single server? I've found NGINX server blocks, but not sure if I'm going in the right direction. I want users to go to a React site that will have links to several other React or Django projects running on the same server. -
DRF - MultiPartParse during post request
I'm fairly new to DRF, I am working on a personal project, that consists of an API (DRF) and a front (React). On the front, there will be a form that allows to input some fields (Author, year...), and send a bunch of images together with it. I have two models that look roughly like this class Image(models.Model): image = models.ImageField(upload_to='documents/%Y/%m/%d') ... class Data(models.Model): title = models.CharField(max_length=256) ... images = models.ManyToManyField(Image) Serializers are already created, everything works fine if I upload first images, and then (for instance, on the Django portal), create the Data with the image IDs, but I would like to send only one request from the front, with data and files, and handle all the operations on the server side (instead of sending images one by one, and then making a second request) So, on my views.py, I created one method that handles POST and GET of Data, on the POST part, my intention is to create the following elif request.method == 'POST': data = MultiPartParser().parse(request.data) images = [] for image in data.files: new_Image = Image(image, ...) new_Image.save() images.append(new_Image) data = Data(data.author, ...) data.images.add(images) serializer = DataSerializer(data, many=True) if serializer.is_valid(): instance = serializer.save() return JsonResponse(serializer.data, status=201) return … -
django confg settings import issue
I have the following structure in a django project. I have a providers.py file in which: from django.conf import settings from project.utils.firewalls import fw In providers I need to get some vars defined in settings. Then in firewalls.py, I have: from django.conf import settings Also in firewalls.py, I do have some code which needs to get a variable that is defined in settings. When I try to do: python manage.py --settings=project.settings.local it will complain about not defining SECRET_KEY, although it is defined. It has to do with the fact that I am importing django.conf.settings in both files. How can I avoid that ? For the moment I've hardcoded the value of the var in the firewalls.py, but I would like to avoid that. -
How to securely get time delta between form load and form submit?
In Django, I have a view with the following method: def get(request): if request.method=='POST': # ... Process a filled form else: # ... Render a blank form Tracking the epoch delta between when a form is rendered and returned is crucial to my application. In prototyping, I just used a hidden field to store the epoch of the render, but this is not secure (users can still edit a hidden field).