Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django sending email with html and embedded image only showing images
I tried to send html rendered email with images. I tried two methods send_mail(subject='', message='', from_email='noreply@test.com', recipient_list=[email], fail_silently=True, html_message=render_to_string('mail_template.html', context)) and html file used cid on to shows image. when I checked mail, this shows html template but images or not loaded. To embed image, I use different method basepath = os.path.dirname(__file__) + '/templates/' mailpath = basepath + 'mail_template.html' html_content = render_to_string(mailpath, context) msg = EmailMultiAlternatives(subject='', body='', from_email='noreply@test.com', to=[email]) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' for f in ['logo.png', 'logo2.png']: imagepath = basepath + f fp = open(imagepath, 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(f)) msg.attach(msg_img) msg.send(fail_silently=False) This does not contain html rendered template, but only include two images. So I want to know if I send html email with embedded image. -
using django context processor to display a form with post method allowed
I have created an email form, using django context processor and included it in base template. The Idea is to be able to send email from all web pages. So far I can render form but cannot submit it. How do I handle post? Or is there other better way to do it? -
Django_Tables2 Not Loading Default Bootstrap Styles
I am following the tutorial on django-tables2 website (https://django-tables2.readthedocs.io/en/latest/pages/tutorial.html) and I am unable to get my tables to display using bootstrap styles. I followed the exact tutorial and was successful in getting bootstrap styled tables, however, when implementing within my main project, it keeps the base formatting without bootstrap. Here is my html that includes the table: {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block extra_head %} <link rel="stylesheet" type="text/css" href="/adminEdits/tatic/mainStyles.css" /> <script type="text/javascript" src="/static/scripts.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> {% endblock %} {% block content %} {% if user.is_authenticated %} {% load render_table from django_tables2 %} <h1>Edit Drivers</h1> {% render_table table %} {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">login</a> {% endif %} {% endblock %} And my tables.py import django_tables2 as tables from tickets.models import User class UsersTable(tables.Table): class Meta: model = User template_name = "django_tables2/bootstrap.html" fields = ("user_id",)#"first_name", "last_name", "position", "admin_level", "email", "distribution_company_id") And my views.py from django_tables2 import SingleTableView from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from django.views.generic import ListView from tickets.models import User from .tables import UsersTable # Create your views here. def index(request): return render(request, 'adminEdits/index.html', context) class UsersListView(SingleTableView): model = User table_class … -
I built an image using docker, but an error was reported when I tried to run the image
I used dockerfile to build a Django image. Here's my dockerfile. An error was reported when I executed the docker run. enter image description here enter image description here -
Django Max DateTime Aggregation
What is the best way of getting the max datetime of related objects of related objects of a Django instance? I need this value as an instance property. For example, with these models, class Show(Model): is_live = BooleanField() ... class Season(Model): show = ForeignKeyField(Show, on_delete=CASCADE, related_name='seasons') is_live = BooleanField() ... class Episode(Model): season = ForeignKeyField(Season, on_delete=CASCADE, related_name='episodes') is_live = BooleanField() live_date = DateTimeField(blank=True, null=True) ... How could I get the most recent episode live_date of a show instance, including only episodes where the season is_live == True and the episode is_live == True? I have tried this in the Show model: @property def max_episode_live_date(self) return self.seasons.filter( is_live=True ).aggregate( max_=Max( 'episodes__live_date', filter=Q(episodes__is_live=True) ) ).get('max_') but I get this error AttributeError: 'str' object has no attribute 'tzinfo' I've tried using Django SubQuery expressions, @property def max_episode_live_date(self) episodes = Episode.objects.filter( is_live=True, season=OuterRef('pk') ).values('live_date') return self.seasons.filter( is_live=True ).aggregate( max_=Max(Subquery(episodes)) ).get('max_') but then I get django.db.utils.OperationalError: (1242, 'Subquery returns more than 1 row') I believe this is due to some episodes containing null live_date, but I'm not sure how to work around. Any insight would be appreciated. -
How can I circumvent Suspicous UserAgent error using Django and Selenium with headless option set to Chrome
I am trying to launch a "Headless" version of Selenium using Django. When I run this script using python manage.py <script> using the command prompt through Django and adding 'headless' to Chrome options chrome_options.add_argument("headless"). I am getting this error because of the headless chrome option I can see but am unsure if I actually need to write Javascript to handle the issue or what is the best solution. How can I circumvent this problem using Django and Selenium? [0304/182708.625:INFO:CONSOLE(2919)] "A parser-blocking, cross site (i.e. different eTLD+1) script, https://ssl.google-analytics.com/ga.js, is invoked via document.write. The network reques t for this script MAY be blocked by the browser in this or a future page load due to poor network connectivity. If blocked in this page load, it will be confirmed in a subsequent console me ssage. See https://www.chromestatus.com/feature/5718547946799104 for more details.", source: https://shop.tcgplayer.com/magic/lorwyn/oonas-prowler (2919) [0304/182708.625:INFO:CONSOLE(2919)] "A parser-blocking, cross site (i.e. different eTLD+1) script, https://ssl.google-analytics.com/ga.js, is invoked via document.write. The network reques t for this script MAY be blocked by the browser in this or a future page load due to poor network connectivity. If blocked in this page load, it will be confirmed in a subsequent console me ssage. See https://www.chromestatus.com/feature/5718547946799104 for more … -
vue.js array into Django
So I want to go through my array which ive crated on vue.js and then check against the arrary to decide where to save it. To explain it a bit more here's the code i have so far Vue.js var app= new Vue({ el: '.con', data:{ posts: [ { title:'', content:'', type:'' } ], }, methods:{ addHead(index){ this.posts.push({ content:'', type:'header', }) }, addPara(index){ this.posts.push({ content:'', type:'para', }) }, removeForm(){ this.posts.splice(index, 1) } } }) HTML <div class="con"> <button type="button" name="button" @click='addHead()'> header </button> <button type="button" name="button" @click='addPara()'> Para </button> <input type="text" name="" placeholder="Title" v-models='posts.title'> <div id="body-fields"> <div class="car-body" v-for="(post, index) in posts"> <input type="textbox" name="" placeholder='{{post.type}}' v-models='post.content'> <span style="float:right;background-color:green" @click='removeForm(index)'> x </span> </div> </div> </div> So i want to save the posts array depending on the type so if its a header save it to one model and if its the other type save it to another, i'm using python and django, thanks for any help -
Django Deployment - the lack of access from outside of network (VPN / Proxy Issue)
I've developed a Django app for an organization that connection to their servers is only possible via VPNs. I tried to deploy it on the server (First I needed to connect to the VPN they provided to me), following digitalocean's instructions found here. I had deployed some other django projects using it and there was no problem. According to the instructions everything works and there is no error in up and running gunicorn + nginx. However, the connection to the websites could not be established (after about 20 secs, the browser throws timout error). I found that the problem is not about nginx + gunicorn config as the issue still appears when Django's development server is running. So I thought it is probably due to the VPN. I mean the website could not be accessed because the server is not accessible from the outside world. I would be grateful if you could provide a solution to this, or express your experiences. -
Adding Text to an Image in Django 2
I have added text to image using PIL in a python script. from PIL import Image, ImageDraw, ImageFont image = Image.open('my_img.png') draw = ImageDraw.Draw(image) myfont = ImageFont.truetype("calibrib.ttf", 40) points = 20,20 string = "My text for my_img.png" draw.text(points, string, "black", font=myfont ) image.save('my_img_WithTxt.png') image.show() exit() I was hoping to use the above script in Django when I am uploading images to the media folder. The script below works fine for uploading and retrieving images. def create_room(request): if request.method=='POST': form = RoomForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/core/roomlist') else: form =RoomForm() return render(request, 'create_room.html', { 'form':form }) The issue I have is that before I execute 'form.save()', I want to write some text on the image. Is there a way to extract the image field from 'request.FILES before saving it, write the text on image and then save it. -
Django - working with a 3rd party API along with pagination
Currently trying to learn Django. As a side project, I am trying to build a site that utilizes a 3rd party API. The user does a search, and my site displays photos based on that search once the search parameters are passed onto the 3rd party API and a response is received. The photos are displayed in a paginated manner. The API itself gives me a result in the form of: { page: 1 pages: 60000 photos: [...] //could contain anywhere from 10-100 items. Each item is a dict containing id, photo URL, as well other info } At the moment I have it set so that with each 'previous' or 'next' page, a new request is made to the API, after which the response could look like: { page: 2 pages: 60000 photos: [...] } Of course, this isn't really ideal as it involves constantly making calls to the API. My question is: would it be bad practice to convert these items into django models and store them in my database? Considering the number of items that would have to be stored. However, the advantage of having them in makes it easier to do things like 'liking' the photo, … -
get_user_model() vs settings.AUTH_USER_MODEL usage
I am new to Django and I am following a video tutorial to learn django. I am trying to understand get_user_model() and setting.AUTH_USER_MODEL. my directory looks like below: | simplesocial | accounts | | models.py | | views.py | | forms.py | | simplesocial |settings.py # models.py from django.db import models from django.contrib import auth from simplesocial import settings # Create your models here. class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return '@{}'.format(self.username) #forms.py from django.forms import forms from django.contrib.auth.forms import get_user_model from django.contrib.auth.forms import UserCreationForm from simplesocial import settings class UserCreateForm(UserCreationForm): class Meta: model = settings.AUTH_USER_MODEL fields = ('username', 'email') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].label = 'Display Name' self.fields['email'].label = 'Email Address' #settings.py AUTH_USER_MODEL = 'accounts.User' I am getting below error ERRORS: accounts.User.user_ptr: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. Since I have a custom user model to be used. What am I doing wrong. If I replace settings.AUTH_USER_MODEL with get_user_model() will it use my custom User class? I could not understand how get_user_model() works -
Having problems installing django in a new virtual env
(DJANGO~1) C:\Users\NIKITA PRO\Desktop\my_django_stuff\DJANGOBASICS>pip install django Requirement already satisfied: django in c:\users\nikita pro\desktop\my_django_stuff\djangobasics\lib\site-packages (3.0.4) Requirement already satisfied: sqlparse>=0.2.2 in c:\users\nikita pro\desktop\my_django_stuff\djangobasics\lib\site-packages (from dj ango) (0.3.1) Requirement already satisfied: pytz in c:\users\nikita pro\desktop\my_django_stuff\djangobasics\lib\site-packages (from django) (2019 .3) Requirement already satisfied: asgiref~=3.2 in c:\users\nikita pro\desktop\my_django_stuff\djangobasics\lib\site-packages (from djang o) (3.2.3) -
Using %(class)s in a 'default' field
I know when you have a foreign key/many to many relation, it is advisable to use related_name='%(app_label)s_%(class)s_related', or something similar. I have a scenario where I want to set the field value to a value based on the current class. Essentially what I want to do is something like this: class Parent(models.Model): child_name = models.TextField(default='%(class)s') class ChildA(Parent): . . . class ChildB(Parent): . . . Is this possible at all? -
Modifying data models in order to add sizing and quantity to the product
I wanna be able to choose a size of frame for every bike and every size would have to have its own quantity. What would be the best model to get this to work? Would that be hard to accomplish? I assume that the simplest way would be to put the size in the title and then the quantity of that item? Here's what I currently got in my Models: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) label = models.ManyToManyField(Label, blank=True) slug = models.SlugField(unique=True) description = models.TextField() class Bike(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) category = models.ManyToManyField(Category, blank=True) image = models.ImageField(upload_to='bikes') brand = models.ManyToManyField(Brand) What would have to be done, to get the sizing and quantity to work? -
Django modelformset_factory not saving POST data to database
I am trying to use a modelformset_factory formset that will show multiple rows from the same model, and allow adding and/or updating and/or deleting rows. For a long time I was getting ['ManagementForm data is missing or has been tampered with'] error. Then I read some more of the documentation where I'm being told to add "data" at the end of the formset. https://docs.djangoproject.com/en/3.0/topics/forms/formsets/ I'll trust the documentation more than every youtube tutorial I watch...however...not one single tutorial I've found does this lol. Regardless. I've added that to my code in my view, and now I get no error...but I get no posting of data either. Been googling like a mad man to no avail. I'm fairly new to Django and any help would be greatly appreciated. Note, my model has drop down "choices". Not sure if that makes a difference. Everything displays correctly in my template, and my submit button redirects correctly...but no data is written to the database at all. MODEL Discipline_Choices = ( ('Unarmed-Contemporary Violence','Unarmed-Contemporary Violence'), ('Rapier and Dagger','Rapier and Dagger'), ('Broadsword','Broadsword'), ('Quarterstaff','Quarterstaff'), ('Single Rapier','Single Rapier'), ('Small Sword','Small Sword'), ('Knife','Knife'), ) Rank_Choices = ( ('1.0 Certificate of Participation','1.0 Certificate of Participation'), ('1.1 Introductory Combatant','1.1 Introductory Combatant'), ('1.2 … -
Read excel from ui and pass it as dataframe to python
I currently having a choose file option in which a user can upload an excel file. How do i read this excel and pass it as data frame to python via Ajax/JQUERY POST call? HTML <input type="file" class="form-control" id="excel_gsheet" name="excel_gsheet"> Please suggest a workaround for this. I am building this in my Django web app. -
Does values_list prevent you to access to field names?
I'm trying to use {{ field.name }} in my template but I can't get access to it. I'm using values_list. views.py: objects = Ingredient.objects.select_related('stock').filter(account=account, exists=True).values_list('id', 'name', 'stock__stock', 'comments')[:50] template.html: {% for object in objects %} {% for field in object %} {% if field.name != 'id' %} <td>{{ field}}</td> {% endif %} {% endfor %} {% endfor %} As you can assume I'm showing every field in values_list except by id which I'm using only for JavScript functions but I don't want to show it in my for loop iteration. But I can't get access to {{ field.name }}, I tried by printing it in the html but I get nothing. -
How can I configure my Django/Python docker instance so that updates are reflected immediately?
I'm have Docker 2.0/Python 3.7 application, which I load into a docker container, along with its accompanying web and database images (below is the docker-compose.yml file) ... version: '3' services: mysql: restart: always image: mysql:5.7 environment: MYSQL_DATABASE: 'maps_data' # So you don't have to use root, but you can if you like MYSQL_USER: 'chicommons' # You can use whatever password you like MYSQL_PASSWORD: 'password' # Password for root access MYSQL_ROOT_PASSWORD: 'password' ports: - "3406:3406" volumes: - my-db:/var/lib/mysql web: restart: always build: ./web ports: # to access the container from outside - "8000:8000" env_file: .env environment: DEBUG: 'true' command: /usr/local/bin/gunicorn maps.wsgi:application -w 2 -b :8000 depends_on: - mysql apache: restart: always build: ./apache/ ports: - "9090:80" links: - web:web volumes: my-db: Here is the web/Dockerfile that controls the Django portion of the stack ... FROM python:3.7-slim RUN apt-get update && apt-get install RUN apt-get install -y libmariadb-dev-compat libmariadb-dev RUN apt-get update \ && apt-get install -y --no-install-recommends gcc \ && rm -rf /var/lib/apt/lists/* RUN python -m pip install --upgrade pip RUN mkdir -p /app/ WORKDIR /app/ COPY requirements.txt requirements.txt RUN python -m pip install -r requirements.txt COPY entrypoint.sh /app/ COPY . /app/ RUN ["chmod", "+x", "/app/entrypoint.sh"] ENTRYPOINT ["/app/entrypoint.sh"] My question is, … -
Use Saved ModelForm as Foreign Key in New Model Instance Django
I'm trying to pass the primary key of a saved ModelForm instance as the foreign key to a new inquiry instance on Django. I'm not quite sure why its not working. I tried breaking up getting the foreign key id and it returns a number but its still not working. Any insight about what I'm doing incorrectly would be greatly appreciated. Views.py def customer_inquiry(request): submitted = False if request.method == 'POST': form = CustomerForm(request.POST) if form.is_valid(): customer = form.save() identity = customer.pk obj = Customer.objects.get(cust_id=identity) inquiry = Inquiry.objects.create( cust_id = Customer.objects.get(cust_id = obj.pk), inquiry_date = datetime.now) return HttpResponseRedirect('/customer_inquiry/?submitted=True') else: form = CustomerForm() if 'submitted' in request.GET: submitted = True return render(request, 'customer_inquiry.html', {'form': form, 'submitted': submitted}) Model.py inquiry_id = models.AutoField(primary_key=True) cust_id = models.ForeignKey(Customer, on_delete=models.CASCADE) inquiry_date = models.DateField() class Inquiry(models.Model): inquiry_id = models.AutoField(primary_key=True) cust_id = models.ForeignKey(Customer, on_delete=models.CASCADE) inquiry_date = models.DateField() Error Request Method: POST Request URL: http://127.0.0.1:8000/customer_inquiry/ Django Version: 3.0.3 Python Version: 3.8.1 Installed Applications: ['database', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/Users/alessandrolou/.local/share/virtualenvs/CascadeBicycleClubCapstone-xHaG2iwn/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/alessandrolou/.local/share/virtualenvs/CascadeBicycleClubCapstone-xHaG2iwn/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/alessandrolou/.local/share/virtualenvs/CascadeBicycleClubCapstone-xHaG2iwn/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in … -
when trying to write your project with registration. I can’t find the link name I tried everythingю Django urls
I have 2 chat and account applications but I don’t understand why urls are not found account.urls app_name = 'account' urlpatterns = [ path('login/', Login_proverka, name='Login'), path('<int:user_id>/profile/', Profil, name='Profil'), path('exit/', Exit, name='Exit'), path('register/', Register, name='Register'), path('<int:user_id>/chat/', include('chat.urls')) ] chat.urls app_name = 'chat' urlpatterns = [ path('', ListCHat, name='ListCHat'), path('<int:chat_id>', Chat, name='Chat'), path('<int:chat_id>/send_message', CreateMessage, name='CreateMessage') ] chat.html <form action="{% url 'chat:CreateMessage' %}" method="post"> {% csrf_token %} <div class="row"> <div class="col"> <textarea class="form-control" id="exampleFormControlTextarea1" rows="3" style="resize: none; margin: 3px; height: 114%; }"></textarea> </div> <div class="col-1"> <button type="button" class="btn btn-primary btn-lg btn-block" style="margin-left: -39%;width: 127%; margin-top: 8%;"><i class="fa fa-hand-peace-o" aria-hidden="true"></i></button> <button type="submit" class="btn btn-primary btn-lg btn-block" style="height: 57%;width: 123%;margin-left: -35%;"> <i class="fa fa-commenting-o" aria-hidden="true"></i> </button> </div> </div> </div> </form> chat.views def CreateMessage(request, chat_id, user_id): if request.method == 'POST': message_text = request.POST['message_text'] try: user_get = Account.objects.get(user_id=user_id) user_name = user_get.user_name except: return HttpResponseNotFound('Пользователь не найден, скорее всего вы пытаетесь зайти туда куда вам не льзя') if request.user.is_authenticated: if request.user.username == user_name: y = Chat_group.objects.get(chat_group_id=chat_id) user_chat = Chat_user.objects.filter(chat_user_id=user_id[0]) name_user = user_chat.chat_user_name last_name_user = user_chat.chat_message_user_last_name x = Chat_message(chat_message_user_name=name_user, chat_message_user_last_name=last_name_user, chat_message=message_text, chat_message_group=y) x.save() return HttpResponseRedirect('/chat/{}'.format(chat_id)) I'm sorry that the names of the changes are so crooked. I’ll be blogging if you tell me where the newcomer made mistakes … -
How to implement different users in django rest framework?
I am building an app using django rest framework and react. I have installed rest auth, all auth for user authentication. When i create a super user from console using manage.py createsuperuser or manually add from django admin panel then i can login from route 'rest-auth/login' & get a generated token. But now i want add a different user called Doctor who can access limited features.I want to register the doctor user from django admin. But here i want to register the doctor by only email address & password not user name & password. So the question is how to make a custom user called doctor in django rest framework. Last thing, i have no user model in models.py cause django rest auth handling all staff about user.Important thing is i want to differ all users by email & user name. If i get the user by username & password then i will assume it as a hospital owner & if i can login using email & password then it will be a doctor. -
Django input box problem, url encoded output
def results(request): inp_value = request.GET.get('get_url', '') return HttpResponse(inp_value) The following functions basically gets the input from the html form which is a text field and submit button. To test it out I enter youtube.com/any_video_link but when I render the inp_value variable it prints out the the slash as "%2F" and = as "%3D" What can I do to get the input in the original format? Thanks in advance -
How do I display same form in multiple pages using a single method in django?
I have a table with atrributes, and I'm displaying each attribute as a checkbox in html view. I want to show them in different pages, but I don't want to make different functions for each category. Is there an efficient way to do so? Here is what I tried so far. def questions(request): # start session page for the user to test questions = Attribute.objects.all() realistic = Attribute.objects.filter(holland_code=1) investigative = Attribute.objects.filter(holland_code=2) artistic = Attribute.objects.filter(holland_code=3) social = Attribute.objects.filter(holland_code=4) enterprising = Attribute.objects.filter(holland_code=5) conventional = Attribute.objects.filter(holland_code=6) left = [realistic, investigative, artistic, social, enterprising, conventional] for attribute in left: # get all the values form the form submitted if request.method == "POST": # THIS WILL GET ALL THE RECOMMENDAITONS rAttributes = request.POST.getlist('realistic') print(rAttributes) return render(request, "main/questions.html", {"questions": attribute}) context = { "questions": realistic, } return render(request, 'main/questions.html', context) This is my html template to display the checkboxes <form action="" method="POST"> {% csrf_token %} <div class="form-check"> {% for question in realistic %} <input type="checkbox" class="form-check-input" id="exampleCheck1" name="realistics" value="{{ question.attribute_name }}"> <label class="form-check-label" for="exampleCheck1">{{ question.attribute_name }}</label> <br> {% endfor %} </div> <input type="submit" class="btn btn-danger" value="Next"> </form> -
attributeerror module django db models has no attribute
Every time showing this problem... attributeerror module django db models has no attribute Please help me. `from django.db import models Create your models here. class Student(models.model): name = models.CharField(max_length = 50) age = models.CharField(max_length = 2)` -
How to set IntegerField's max_value in view
This is my form: class GameForm(forms.Form): bid = forms.IntegerField(widget=forms.NumberInput (attrs={'placeholder': 'bid'})) and I would like to set bid max_value according to request.user's amount of money.