Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I upgrade bootstrap in my mezzanine's project?
Environments pc: mac os 10.13.1 Versions python: 3.6.2 mezzanine: 4.3.1 django: 1.11.16 bootstrap: 3.3.5 (confirmed in /{my_name}/anaconda3/lib/python3.6/site-packages/mezzanine/core/static/css/bootstrap.css) Here, my mezzanine project has base.html for site interface. There is the code to get the css-code(design). That is bootstrap.css. But the bootstrap.css relies to bootstrap3(3.3.5), and I have to use bootstrap4(4.0.0). (This is my boss's order.) Then, I wanna get(download) bootstrap4, put it to right directory and change bootstrap dependency by linking to the directory which I put earlier. How should I achieve it? -
Django: How to config default Media path is in server, not Local
I want to config default media path in Django, which when uploading a image from Localhost, it will be stored in server path, instead of stored in localhost path. I want all photo will be uploaded in server abc.com. Now my settings.py is: import os DEBUG = True # Application definition INSTALLED_APPS = [ ... ] # Config Diretories BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_DIR = Path(__file__).parent PROJECT_LOCAL_URL = PROJECT_DIR.parent STATIC_ROOT = PROJECT_DIR.parent.child('static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'staticfiles'), ) BASEDIR = os.path.abspath(os.path.dirname(__file__)) MEDIA_ROOT = PROJECT_DIR.parent.child('media') MEDIA_URL = '/media/' My model upload: class Photo(models.Model): user = models.ForeignKey(User, related_name='user_photos', on_delete=models.CASCADE) image = models.ImageField("Uploaded image", upload_to=photo_path) -
Different links within a div using django
I have a list item with a mouse over edit button. I want the list item box to redirect to the item url and the edit button to redirect to the edit page. <a class="list-group-item" href = '{{ the_url }}'> <div class="list-content" > <span class="list-text">{{group_child}}</span> <div class="item-actions"> <span class="btn btn-pure btn-icon" onclick="location.href = '{% url 'mod:editgroup' group_child.id %}'"> <i class="icon wb-edit" aria-hidden="true"></i> </span> </div> </div> </a> The issue with the above code clicking the edit icon also redirects to list item url. How do I make the edit icon link work -
How do I track a request and its corresponding model changes in Django?
Whenever a request is made I'd like to make a unique a tracking number. Within request_started signal, I'm assuming to find out the authenticated user to track with the unique number. If there is any database change, it would store the change set with the tracking number. post_save, post_delete and m2m_changed signals should be ok. My questions are: How do I make (or get if there is any) a unique tracking number for each request? How do I get the authenticated user in request_started signal, like we do request.user in views? How can I get the unique tracking number within post_save, post_delete and m2m_changed signals. I'm on Django2.1 and python3.6. -
Some classess of my CSS file are not rendering into Django templates (most classess render without problems)
I'm starting with Django, I've been throught this several hours, please help me! on my *.html file I have this code (and more): {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"> and since I added that static file, my page has style.. but some classes don't render, for example this div: <div class="nav-profile-image"> If I delete the class .nav-profile-image from style.css, the page still the same, that image has no container, it's very strange. I uploaded all the app on branch "problems": https://github.com/franchodl/robohome/tree/problems view trying to render: home url for home: http://127.0.0.1:8000/propietario/ template: ./own/templates/own/home.html static files: ./static Maybe the problem it's another thing, not the css, i downloaded the frontend from: https://github.com/BootstrapDash/PurpleAdmin-Free-Admin-Template When I open it from index.html, the page works good, the problem is from Django. Any ideas??? I have no idea what else to check. THANKS!!! -
Django How to Timescale With PostgreSQL?
I want to implementation timescale, and I use Django, Is there have any advice about those ? -
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!