Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django variables won't render in templates
Django version 2.1.3 Python version 3.7 Writing out sample code just to get an understanding of Django. Right now I'm on Templates and I'm having 0 luck when it come to rendering variables. In views.py folder I've created a little dictionary and passed it through under the variable content from django.shortcuts import render # Create your views here. posts = [ { 'Title': 'Challanger 1', 'Name': 'Sammy', 'Age': '33', 'Food': 'Seafood' }, { 'Title': 'Challanger 2', 'Name': 'Sammy', 'Age': '33', 'Food': 'Seafood' } ] def home(request): content = { 'posts': posts } return render(request, 'blog/home.html', content) In my home.htmlfile, I've added a few 123 next to my {{variable}}to make sure the .html file is connecting to the view.py. When I py manage.py runserver, only the 123 is displayed but none of my {{variables}} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> {% for post in posts %} <p>123 {{ post.name }}</p> <h1>123 {{ post.title }}</h1> <h1>123 {{ post.age }}</h1> {% endfor %} </body> </html> localhost:8000 produces: 123 123 123 123 123 123 When I open view-source from the browser: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta … -
Python: var['key']['key'] or var['key'].get('key') [duplicate]
This question already has an answer here: Why dict.get(key) instead of dict[key]? 9 answers I wonder what's the better way to write it. Is there a recommended way? self.event = kwargs['form_kwargs'].get('event') self.event = kwargs['form_kwargs']['event'] -
Create a user with email which has been processed from the previous page with UserCreationForm Django
I am trying to create a user with email as username and the email is first screened, i.e., the email is not registered then create a user. How can I pass or set the email in forms.py as it is already processed in the previous page? Models.py from django.contrib.auth.models import AbstractBaseUser from django.db import models class CUserManager(models.Manager): def _create_user(self, email, password, **extra_fields): now = timezone.now(); if not email: raise ValueError(_('Email is required')) user = self.model( email = email, date_joined = now, **extra_fields ) user.set_password(password) user.save(using = self._db) return account def create_user(self, email, password=None, **extra_fields): return self._create_user(email, password, **extra_fields) def get_by_natural_key(self, email): return self.get(email=email) def create_superuser(self, email, password, **extra_fields): return self._create_user(email, password,**extra_fields) class CUser(AbstractBaseUser): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=255) last_name = models.CharField(_('last name'), max_length=255) date_joined = models.DateTimeField(_('date created'), auto_now_add=True) is_active = models.BooleanField(default=True) objects = CUserManager() USERNAME_FIELD = 'email' ... Forms.py from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): class Meta: model = CUser fields = ('first_name', 'last_name', 'password1', 'password2') in HTML <form action="" method="post" role="form"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> The email comes from session['email'] which is saved in the previous page. How can I pass this session['email'] to forms.py? -
how to use django-clamd in windows
I am trying to integrate CalmAv with Django in my Windows machine. I have done everything as per documentation given in the below url https://pypi.org/project/django-clamd/ While running the application I am getting the below error. AttributeError at /admin/iic/student/add/ 'ClamdUnixSocket' object has no attribute 'clamd_socket' Request Method: POST Request URL: http://127.0.0.1:8000/admin/iic/student/add/ Django Version: 1.11 Exception Type: AttributeError Exception Value: 'ClamdUnixSocket' object has no attribute 'clamd_socket' Exception Location: D:\mypersonalfiles\vire\env\lib\site-packages\clamd__init__.py in _close_socket, line 260 Python Executable: D:\mypersonalfiles\vire\env\Scripts\python.exe Python Version: 3.6.0 Python Path: ['D:\mypersonalfiles\vire\antivirus', 'D:\mypersonalfiles\vire\env\Scripts\python36.zip', 'D:\mypersonalfiles\vire\env\DLLs', 'D:\mypersonalfiles\vire\env\lib', 'D:\mypersonalfiles\vire\env\Scripts', 'c:\users\735252\appdata\local\programs\python\python36\Lib', 'c:\users\735252\appdata\local\programs\python\python36\DLLs', 'D:\mypersonalfiles\vire\env', 'D:\mypersonalfiles\vire\env\lib\site-packages'] Server time: Thu, 22 Nov 2018 04:59:22 +0000 -
Django Displaying Images Not Found
This has been driving me crazy for 2 days now and I cannot find an answer to this. I have looked through countless posts and cannot get this to work. I am trying to display a profile picture for a user using Django ImageField in my model. For some reason it keeps on coming up with 404 not found, even though I can see that the path to the image file is correct. For example: My model: class KPILead(models.Model): name = models.CharField(max_length=255) position = models.CharField(max_length=255) company = models.ForeignKey(KPICompany) profile_pic = models.ImageField(upload_to='profile_pics/') def __str__(self): return self.name This is indeed uploading the image file to the media/profile_pics folder in my root directory. The view: @login_required(login_url='/') def eftlead_detail(request, eftlead_id): context = dict() context['eftlead'] = KPILead.objects.get(pk=eftlead_id) context['team_names'] = KPITeam.objects.filter(eft_lead__id=eftlead_id) context['incidents'] = KPIIncidentReport.objects.filter(eft_lead__id=eftlead_id) context['image_url'] = context['eftlead'].profile_pic.url return render(request, 'templates/eftlead.html', context) The static and media settings in my settings file: STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') And I have added: + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to my urls file. It just gives an error of 404 not found, even when I check the source in Chrome or Firefox I can see that correct path is being shown. If I try and … -
Django 400 Bad request after pulling update from Github
I had a working page running Django with channels via Nginx, Daphne, Redis, and Gunicorn. After pulling an update from Github my index page now shows "Bad Request (400)" with nothing helpful in the console except for missing favicon. My settings.py has DEBUG = False and ALLOWED_HOSTS = ['AWS_IP']. Can anyone help me figure out what might be causing this? -
pycharm unable to load django apps
In The PyCharm I have Django configured in virtual environment, what I did is: Previously I had python 3.6 on my windows 10 so I uninstalled it and Installed Python 3.7 pip install virtualenv vertualenv venv and then activated it pip install django also installed djangorestframework, coreapi and requests via pip django-admin startproject hasslefreeaccounts opened project in PyCharm, then: Files > settings > Language & Framework and Configured my project as: entered project root, settings.py and manage.py path (see image below) and then created 2 apps named customer and master and then configured the run configurations as: after this (am using pycharm professional) everything works fine except while importing apps PyCharm Gives me error when I import my django apps in other as: from masters.models import some_class pycharm says cant find module, thought when I run project it works fine with no error. so I tried doing: from ..master.models import some_class This makes PyCharm import apps (see image below) this in pycharm doesn't shows any error but on run gives error as: ValueError: attempted relative import beyond top-level package Other Details: and here is the project interpreted settings: and Settings.py as: import os # Build paths inside the project like … -
Best approach for multiple Django projects and async emails
I'm using Django 2 with Python 3.5 in a Ubuntu server. I have multiple Django projects, this projects are using the same virutalenv, because they have the same source code. For making the email sending async, I'm using post-office app for Django, this requires to run a crontab every minute to send the queued emails in database. But this approach is getting hard to maintain with a great number of Django projects in the same server, so every minute I have a great CPU demand spike. The emails are being handled by AWS SES. I'm thinking in use Celery with RabbitMQ, but this is getting confusing for me. Will I have multiple Celery and one RabbitMQ instances? Can this be done without interference? Are there a way to use just one async task process, an alternative for Celery and RebbitMQ? -
How can I integrate a machine learning algorithm in py file into django website?
I'm working with random forest algorithm to predict college dropouts with python, the algorithm is finished and now I have to use that file and be able to run it from a website, I'm using django but I don't know how I can make it work, I import the file in views but it only display a line, it doesn't even have an structure like it has when I run the file in jupyter, so if anyone knows something I'll be very thankful. Sorry if is a little difficult to understand, english is not my first language. This is the algorithm import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn import metrics import pandas as pd from sklearn.feature_selection import SelectKBest dataset = pd.read_csv('C:/Users/danni/OneDrive/Documents/Universidad/2018/Tesis/encuestas/Nueva carpeta/Nueva carpeta/SinRanking/2005_2017_SOLO_PRIMERO_Y_SEGUNDO.csv', delimiter=";") datos2 = dataset['F_Nac'] i = 0 a = [] while i < len(datos2): value2 = datos2[i] first = value2[6:10] year = first a_ingreso = dataset['A_Ingreso'] a.append(a_ingreso[i] - int(year)) i += 1 dataset['edad_ingreso']=a; #calculamos la edad de ingreso a la universidad def calcula_dif_years_eg_in(anio,cuando): return anio - cuando dataset['a_egresado_colegio']=dataset.apply(lambda x: calcula_dif_years_eg_in(x['A_Ingreso'],x['A_Egreso_Colegio']), axis=1); dataset = dataset.drop(["F_Nac","A_Ingreso","A_Egreso_Colegio","Via_Ingreso"], axis=1) # cargamos las variables predictoras predictors = dataset.drop(['Deserto'], axis=1) # y estos son los resultados que se obtienen, en … -
How to perform the delete method in drf django
How to perform the delete request in Django drf? How will I pass the params for the request? Kindly help with the solution. I am very new in this drf-django-python programming. -
Django specific error on running code in settings.py
I am trying to create an html file when the django project is started, by including code in the project/settings.py as follows: def Brander(): import configparser config = configparser.ConfigParser() config.read('settings.ini') version = config['PROJECT']['version'] APPNAME = config['BRANDING']['appname'] APPCOMPANY = config['BRANDING']['appcompany'] APPCOMPANYLINK = config['BRANDING']['appcompanysite'] APPLINK = config['BRANDING']['appsite'] from django.contrib.staticfiles import finders filen = finders.find('clinic/brandedfooter.html') f = open(filen, "w") s = f""" <div class="col-lg-8 col-md-8 d-none d-md-block d-lg-block"> <span class="text-muted float-right"><i>My OP and IP Clinic - <a href="{APPLINK}">{APPCOMPANY} by </a><a href="{APPCOMPANYLINK}">{APPCOMPANY}</a></i></span> </div> """ f.write(s) My project/settings.ini contains: [PROJECT] version = 0.0.1 [BRANDING] appname = MyOPIP appcompany = Droidzone appcompanysite = https://droidzone.in appsite = https://myopip.com When the above code is run as standalone python script, everything works fine, and the html file is generated. However, when this is executed as part of manage.py runserver, I get the following error: joel@hp:~/myappointments$ ./manage.py runserver Traceback (most recent call last): File "./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/joel/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/joel/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 325, in execute settings.INSTALLED_APPS File "/home/joel/.local/lib/python3.6/site-packages/django/conf/__init__.py", line 57, in __getattr__ self._setup(name) File "/home/joel/.local/lib/python3.6/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/home/joel/.local/lib/python3.6/site-packages/django/conf/__init__.py", line 107, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File … -
NoReverseMatch at /blog/2018/
Help me please. I don't know this problem... What's the problem? html code image : enter image description here error page image : enter image description here blog/urls.py urlpatterns = [ -- skip -- # Example: /2018/nov/ url(r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$', PostMAV.as_view(), name='post_month_archive'), -- skip -- ] blog/views.py from blog.models import Post from django.views.generic.dates import --skip--, YearArchiveView, --skip-- -- skip -- class PostYAV(YearArchiveView): model = Post date_field = 'modify_date' make_object_list = True -
How to do SSO with Django and ReactJS?
I need to bootstrap a Django application with ReactJS. Authentication needs to work through Siteminder (SSO). How can ReactJS components know what user is authenticated? What are the common techniques for client side components to know the authenticated user, if any? -
Django calling a specific field in a table
So basically I have this for loop which pulls each individual professor based on the specific attributes of that table. <ul> {% for major in major_choice %} <li>{{major.ProfessorName}}, {{major.ProfessorRating}}, {{major.Major}}</li> {%endfor%} </ul> The thing is I wanted to basically create a header tag and simply add the major from one of the results so my goal was something like this.. <h1> {{major_choice.Major}} </h1> Also this specific template, already has a filter set so the database only has for instance ALL of one major, ill post an image so you can see what I mean. So I was hoping that h1 tag would make a "Asian American Studies" header -
How to use lambda function with dictionary?
How can I use lambda function with map for create a object? I receive 1 or more objects in my serializer by Json, then I want iterate this json and create a object. Here is my code from models.py, and my serializers.py. # Models.py class ModelA(models.Model): ... @classmethod def insert_car(self, i, user): car = i.get('car') item = i.get('item') quantity = i.get('quantity') ModelA.objects.create(user=user, car=car, item=item, quantity=quantity, status=self.STATUS_PENDING) return True # serializers.py class ModelASerializer(ModelSerializer): class Meta: model = Order fields = ['car', 'item', 'quantity'] class MultipleOrderSerializer(ModelSerializer): items = ModelASerializer(many=True) class Meta: model = Order fields = ['items'] def create(self, request, *args, **kwargs): list = self.data.get('items') user = self.context.get('request').user a = map(lambda i : ModelA.insert_car(i, user), list) return self.data I tryed print anything inside my insert_car, but doesn't print nothing, the method insert_car doesn't called -
Passing an initial value into a form field from previous detail view
I a bit confused how to do this, I have a "contact user" button on a user detail page. I am trying to set the initial form value for the email field as the users email from the previous detail page view, so that it pre-populates. Would I pass the user.email as a kwarg into the button url? views.py def Contact(request): form_class = ContactForm # new logic! if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): contact_name = request.POST.get( 'contact_name' , '') contact_email = request.POST.get( 'contact_email' , '') form_content = request.POST.get('content', '') # Email the profile with the # contact information template = get_template('contact_template.txt') context = { 'contact_name': contact_name, 'contact_email': contact_email, 'form_content': form_content, } content = template.render(context) email = EmailMessage( "New contact form submission", content, "Your website" +'', ['youremail@gmail.com'], headers = {'Reply-To': contact_email } ) email.send() return redirect('contact_form') return render(request, 'portal/contact_form.html', { 'form': form_class, }) forms.py from django import forms class ContactForm(forms.Form): contact_name = forms.CharField(required=True) contact_email = forms.EmailField(required=True, initial='{ kwarg }') content = forms.CharField( required=True, widget=forms.Textarea ) user_detail.html <div class="col-lg-4 text-center p-5" style="padding-right:20px; border-right: 1px solid #e5e5e5;"> <a href="{% url 'portal:contact_form' kwarg.user.email %}"> <h1><i class="fa fa-2x fa-envelope-o text-success" aria-hidden="true"></i></h1> <p class="text-muted mt-3 ">Contact Customer</p> </a> </div> -
Django: send email on form submition
I need to send an email after user submits a form on my page (this is still in development, but it'll be in production soon). I've read this other answer but after my form is submitted I'm not reciving any email (I've used my personal email as the sender and the receiver, for testing). What I need to modify? PLUS: How to send images on emails? Any tutorial on this? I need to send professional emails after form submition. settings.py EMAIL_HOST = 'smtp.gmail.com' # since you are using a gmail account EMAIL_PORT = 587 # Gmail SMTP port for TLS EMAIL_USE_TLS = True EMAIL_HOST_USER = 'oma.oma@gmail.com' #Not my actual email EMAIL_HOST_PASSWORD = 'MyPassword' #Not my actual password views.py: # here we are going to use CreateView to save the Third step ModelForm class StepThreeView(CreateView): form_class = StepThreeForm template_name = 'main_app/step-three.html' success_url = '/' def form_valid(self, form): form.instance.tamanios = self.request.session.get('tamanios') # get tamanios from session form.instance.cantidades = self.request.session.get('cantidades') # get cantidades from session del self.request.session['cantidades'] # delete cantidades value from session del self.request.session['tamanios'] # delete tamanios value from session self.request.session.modified = True return super(StepThreeView, self).form_valid(form) form.py: from django.core.mail import send_mail class StepThreeForm(forms.ModelForm): instrucciones = forms.CharField(widget=forms.Textarea) class Meta: model = TamaniosCantidades fields … -
Django ticket form
So am trying to build an event ticket system but just got stuck at iterating over the ticket types in my model. Basically a user can decide to choose whichever version of ticket they want e.g VIP, Regular, Advance e.t.c. My problem lies in iterating over these types and letting someone pick the number of tickets they wish to buy. My code so far to handle this is less than stellar but i would really appreciate some help. from django.shortcuts import render from django.http import HttpResponse, HttpResponseNotFound, HttpResponseBadRequest from .models import * from django.shortcuts import render, get_object_or_404 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def allevents(request): event_list = Event.objects.all() carousel = Carousel.objects.filter(show_carousel=True) page = request.GET.get('page', 1) paginator = Paginator(event_list, 12) try: events = paginator.page(page) except PageNotAnInteger: events = paginator.page(1) except EmptyPage: events = paginator.page(paginator.num_pages) return render(request, 'event/index.html', {'events':events, 'carousel':carousel}) def event_details(request, event_id=None): try: event = Event.objects.get(pk=event_id) context = { 'event': event, 'ticket_form': TicketsForm(), 'cart' : request.session.get('cart', []) } return render(request, 'event/event_detail.html', context) except Event.DoesNotExist: return HttpResponseNotFound('<h1>This event does not exist or has already taken place, sorry for the inconvinience</h1>') my current template to handle that view is <div class="grid-container" style="padding-top: 2%;"> <div class="work-feature-block grid-x grid-margin-x"> <div class="cell medium-6"> <img class="work-feature-block-image" src="{{ … -
Filter django queryset with multiple variables
I would like to pass one or many GET variables to filter a queryset. I have tried the following code to create a dictionary of the variables and apply the filter, but testing with two variables it appears to only be filtering on the final dictionary variables. for k,v in mydict.items(): qs = mymodel.objects.filter(**{"%s__contains" % k: v}) Can anyone point me in the right direction as to where I am going wrong? Any help is much appreciated! -
test form is vaild with valid data without posting data django
I want to ask a question, is there any possible to test form is valid with post data, which means it can generate dictionary of data automatically according to form. because I have a lot of form to test. I dont want to write data = {'A':'a', 'B':'b'}, too complicated. -
File Watcher cant find *.sass file in static folder
I have a django project and I'm using PyCharm. I wanted to add sass in my project. I have added new sass wather in File Watchers but it cant found any files in folder "static". In any other folder all is good but when I'm trying to do this in static folder nothing works. How to fix it? -
Splitting a django model using property and setters
In trying to split a model in an already working application, I used property and setters to prevent making potentially hundreds of updates within the code base. Model setup: class A(models.Model): name = models.CharField() type = models.CharField() spec = models.SmallIntergerField() @property def salary(self): self.b.salary @salary.setter def salary(self, value): self.b.salary = value self.b.save() class B(models.Model): a = models.OneToOneField(A) salary = model.IntergerField() height = model.IntergerField() Model usage model_a = A(salary=129980, height=6.00, type="several types") model_a.save() Again I"m using property and setters to avoid changing queries in old migration files and several other places where the query occur in the code. Question: Does using property / setters in this way trigger inadvertently lot of queries when model A properties are called? i.e. are there cons to this? Is there a better way this could be done? Using: Django 1.11 -
ValidationError in django Views
I'm new at django and I want to raise a ValidationError in the form, but I don't know how to do it. Right now. Most important of all I need to verify if the first 3 digits of the idItem correspond to the Category and SubCategory id. I have my Models code like this: class Categoria(models.Model): idCategoria = models.IntegerField(primary_key=True) nombreCategoria = models.CharField(max_length=200) desCategoria = models.CharField(max_length=200, blank=True) def _str_(self): return str(self.idCategoria._str_()+" --> "+self.nombreCategoria) class SubCategoria(models.Model): id = models.IntegerField(primary_key=True) idCategoria = models.ForeignKey(Categoria, on_delete=models.CASCADE) idSubCategoria = models.IntegerField() nombreSubCategoria = models.CharField(max_length=200) desSubCategoria = models.CharField(max_length=200, blank=True) def __str__(self): return str(self.nombreSubCategoria) class Item(models.Model): idItem = models.IntegerField(primary_key=True) idSubCategoria = models.ForeignKey(SubCategoria,on_delete=models.CASCADE) idAutor = models.ForeignKey(Autor,on_delete=models.CASCADE) nombreItem = models.CharField(max_length=50) descrpcionItem = models.TextField(max_length=100) imagenUrl = models.ImageField(upload_to='itemImages', blank=True) nombreImagen = models.CharField(max_length=10, blank=True) fechaPublicacion = models.DateField(auto_now=False, auto_now_add=False, blank=True) And my view: def itemCreate(request): if request.method == 'POST': form = itemForm(request.POST, request.FILES) subcategoria = request.POST.get('idSubCategoria') message = ERROR_MESSAGE subcateg = SubCategoria.objects.get(idSubCategoria=subcategoria) cat = subcateg.idCategoria.idCategoria id = request.POST.get('idItem') if id[0] == str(cat) and id[1:3] == str(subcategoria): print("hi") form.save() else: raise forms.ValidationError(message) return redirect('sgb:itemListar') else: form = itemForm() return render(request, 'itemCrear.html', {'form': form}) Thanks in advance -
How to set Django channels self.scope["user"] with Javascript (React)
I am using the following technologies: Django Channels 2.1.2, ReactJS + reconnecting-websocket package For consumers.py class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): me = self.scope['user'] print(str(self.scope['user'])) For routinig.py application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r"^chat/(?P<user_id>[0-9]+)/$", ChatConsumer), ] ) ) ) }) For ReactJS, I'm connecting with the socket with import ReconnectingWebSocket from 'reconnecting-websocket' ... const rws = new ReconnectingWebSocket('ws://127.0.0.1:8000/chat/30/') But Django is not picking up any user in scope? For React, I'm storing user and token in cookies. I believe it's a ReactJS fault but can somebody please help me out? Thanks! -
Is it possible to apply Djnago wagtail to my existing Django project?
I recently found wagtail, which is a very cool Django CMS library. I tried to use it following its documentation, but its installing documentation is based on starting-over Django project. I'm using ReactJS for frontend and Django as API backend. I was wondering if it's possible for me to apply wagtail to my existing Django project.