Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python-celery docker container not able to read images and files passed by python-model docker container
docker-compose.yml version: "3" networks: app-tier: driver: bridge services: python-api-celery: &python-api-celery build: context: /Users/AjayB/Desktop/python-api/ networks: - app-tier volumes: - .:/python_api/ - .:/python_model/ environment: - PYTHON_API_ENV=development command: > sh -c "python manage.py makemigrations && python manage.py migrate" python-api: &python-api <<: *python-api-celery ports: - "8000:8000" command: > sh -c "python manage.py runserver 0.0.0.0:8000" python-model: &python-model build: context: /Users/AjayB/Desktop/Python/python/ ports: - "8001:8001" networks: - app-tier environment: - PYTHON_API_ENV=development volumes: - .:/python_model/ - .:/python_api/ depends_on: - python-api command: > sh -c "cd /python-model/server/ && python manage.py migrate && python manage.py runserver 0.0.0.0:8001" python-celery: &python-celery <<: *python-api-celery depends_on: - redis command: > sh -c "celery -A server worker -l info" redis: image: redis:5.0.8-alpine hostname: redis networks: - app-tier expose: - "6379" ports: - "6379:6379" command: ["redis-server"] Application workflow: I hit APIs passing image to python-api on port 8000., python-api then calls python-model at port 8001 to predict the outcome of an image., which is then passed to python-celery to display images and results in mail. The docker-compose build went smooth, I'm able to run all the 5 containers.., output of docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES xxxxxxxxxxxx integrated_python-celery "sh -c 'celery -A se…" 13 minutes ago Up 5 seconds 8000/tcp integrated_python-celery_1 … -
django model from create a new record instead of updating old one
I am newbie in django. Now my issue is that I updating my record but it's adding a new record instead of updating old one. Where I'm wrong? views.py class EditProduct(TemplateView): template_name = 'stock/editproduct.html' def get(self, request, product_id): productedit = get_object_or_404(Product, pk=product_id) data=Product.objects.get(id=product_id) form = EditProductForm(instance=data) args = {'form':form, 'productedit':productedit} return render(request, self.template_name, args) def post(self, request, product_id): form = EditProductForm(request.POST, request.FILES) if form.is_valid(): productadded = form.save(commit=False) productadded.saler = request.user productadded.pub_date = timezone.datetime.now() productadded.save() return redirect('stock') else: args = {'form': form} return render(request, self.template_name, args) Your help will be appreciated. Thank You -
How can i create a re-usable Template
im new to Django and im in this Stage where you try to build some bigger stuff. So i have my Template "Create User" and a Function with Template where i can delete and edit. Delete works fine. But when i Press Edit, i return my CreateUser Template where i load data in the field and the user can edit it. So if i press edit, my CreateUser Page will be loaded, the fields are filled but when i press save it doesnt work. It returns my Edit Page. Can anyone help me a bit? Would be really nice bc im really hardstuck atm. Btw, you can also give me some advice to my lil code if you want!:) Its not finished right now i know, just want to solve the view first Template: <form action="." method='POST'> {%csrf_token%} <div class="container"> <form> <div class="form-group"> <label for="usr">First Name</label> <input type="text" name="first_name" class="form-control" value="{{user.first_name}}" id="usr"> </div> <div class="form-group"> <label for="pwd">Last Name</label> <input type="text" name="last_name" class="form-control" value="{{user.last_name}}" id="pwd"> </div> <div class="form-group"> <label for="usr">Email</label> <input type="text" class="form-control" id="usr" value="{{user.email}}"> </div> My view: if request.user.has_perm('auth.edit_user'): users = Employee.objects.all() if request.method == "POST": if request.POST.get('delete'): selected_item = request.POST.get("delete") todel = Employee.objects.get(id=selected_item) todel.delete() messages.success(request, "User wurde erfolgreich gelöscht") … -
Django REST Framework: definiting parser and renderer classes on a viewsets.ViewSet @action by @action basis
I was wondering ... what is the best practise way to define custom / bespoke parser and renderer classes on an action by action basis for a rest_framework.viewsets.ViewSet class? Say I wrap a method handler with the following @action decorator: class SomeViewSet(viewsets.Viewset): @action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf]) def process(self, request, *args, **kwargs): ... Is it as simple as adding something like: class SomeViewSet(viewsets.Viewset): @action( detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf], renderer_classes=(PlainTextRenderer,), parser_classes=(MultiPartParser,) ) def process(self, request, *args, **kwargs): ... -
Django Initial value for date picker
Is there a way to set initial value for date picker? I would like to get today's date. My code: class DateInput(forms.DateInput): input_type = 'date' value = date.today() class testerForm(forms.ModelForm): class Meta: model = Tester fields = ('phandlowy', 'data_wypozyczenia') widgets = {'data_wypozyczenia': DateInput(),} -
Django - Modify a foreign key field when updating primary field
I have a question. I have a relation (many-to-many) between two class and I would like when there is a relation created, update a field. class Question(models.Model): intitule = models.TextField(verbose_name="name") matched = models.BooleanField(verbose_name="matched", default=True) asked = models.IntegerField(verbose_name="was asked", default=1) class Meta: ordering = ['intitule'] def __str__(self): return str(self.matched) + " [" + str(self.asked) + "]" + " - " + self.intitule class Reponse(models.Model): reponse = RichTextField() question = models.ManyToManyField(Question) def __str__(self): return self.reponse Here is my question: When I create an object "Response" in the admin interface and I choose a question, I would like to update the attribute "matched" in question automatically. How can I do that ? Thank you very much. -
Django - What if there are more than 100 models in single app
I'm working on Django project that uses more than 200 models. Is it good to have more than 100 models in single models.py?. -
Prevent Force Download of AWS S3 Files Django
I am using storages.backends.s3boto3.S3Boto3Storage storage backend to upload files in my django project. field declaration in model: document = models.FileField(upload_to=s3_directory_path.user_directory_path) user_directory_path def user_directory_path(instance, filename): # TODO: Try to include this along with check filetype on the request object document = instance.document mime = magic.from_buffer(document.read(), mime=True) extension = mimetypes.guess_extension(mime, strict=False) file_name = str(uuid.uuid4()) + extension document.seek(0) return os.path.join("users", str(instance.user.id), file_name) The saving of the document works perfectly fine, but the link which is generated force downloads the file. How can i avoid that? -
PasswordResetForm doesn't send email
I'm working on a user system on an app. Everything works fine except one thing. When I create a user, I generate a password to keep in database and send an email to the new created user to set his own password. So the password is in the database and I use PasswordResetForm to send an email of password reseting. Here is the code I use: reset_password_form = PasswordResetForm(data={'email': user.email}) if reset_password_form.is_valid(): reset_password_form.save(request=request, use_https=True, from_email="Webmaster@mysite.com", html_email_template_name='main/password_reset/password_reset_email.html', subject_template_name="main/password_reset/password_reset_subject.txt") And here is the problem, no email is sent. So to clarify, I already use this Form in case we click on "I forgot my password" and it works very well. So There is no problems of settings for the email server. As well the reset_password_form.is_valid() is true I can breakpoint in the if. The user.email exists and contain a real and correct email adress. I have the feeling that when I call save() on my form it doesn't send the message, did I do a mistake thinking it will do? -
how do I dynamically(?) add fields in Django model?
So I'm a newbie in Django, and having trouble with model. I'm wondering if creating additional field every time a user does certain action (e.g., click (+) button) is possible. So below is the field that I want the user to add as many as he/she wants. models.py class SimpleInput(models.Model): each_input = models.CharField(max_length=200) I have the (+) button in my html file, as well as JavaScript code that enables the function--adding fields with id's increasing by +1. But I'm not sure how I can connect this with model. I very much appreciate your help. Thanks :) For your information, I'm attaching the JS code. $(document).ready(function(){ var addNum = 0; $("#addButton").click(function(){ var currentId = $("#simple_input"+addNum.toString()); var newId = currentId.clone(); newId.attr('value', ''); newId.attr('class', "addedLine"); newId.attr('id', "simple_input"+(addNum+1).toString()).prependTo(".ED_addedHere"); addNum = addNum +1; }); }); -
How to run Django and Spark application
I am working on a Spark Application and I want to create a rest API in Django, below is my code from django.shortcuts import render from django.http import Http404 from rest_framework.views import APIView from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from django.http import JsonResponse from django.core import serializers from django.conf import settings import json from pyspark import SparkContext, SparkConf, SQLContext sc = SparkContext() sql = SQLContext(sc) df = Sql.read.format("jdbc").options( url = "jdbc:mysql://127.0.0.1:3306/demo", driver = "com.mysql.cj.jdbc.Driver", dbtable = "tablename", user = "xyz", password = "abc" ).load() totalrecords = df.count() # Create your views here. @api_view(["GET"]) def Demo(self): try: a = str(totalrecords) return JsonResponse(a,safe=False) except ValueError as e: return Response(e.args[0],status.HTTP_400_BAD_REQUEST) I want to know how will I run this code, as I have directly tried "python manage.py runserver" which is not working, so how to run this spark and django with django api and spark-submit with all required spark jar file? -
How to make a Serial field restart at 1 for every super-item in Django
In my program, there is a structure like so (the items discussed aren't real, but should get the structure across): We have multiple super items, let's call them posts (like a blog). The Post-class has a UUID as its PK. Every Post can have multiple comments. The Comment-class also has a UUID as its PK. However, I'd like to add a SERIAL-like field (let's call it Index) to the Comment class, but not so that every new comment counts on the "same counter", but rather that the Comment's Index starts at 1 for each Post, so Post 1 has three comments with unique UUIDs, and Indices 1, 2 and 3. Post 2 should have other comments, but these should still have indices 1, 2, 3, 4 ... I don't have any code to show, but the problem is more technical than syntactical, so this should suffice. Any ideas? -
Django project Using mod wsgi and apache - ImportError: No module named 'encodings'
I am able to run my django project in development mode using python3.7 manage.py runserver However when tried to run the same project using apache mod wsgi configuration, I am getting the below error: Fatal Python error: initfsencoding: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' Below is the httpd.conf file configuration LoadModule wsgi_module "/TomCatWeb/app/projects/myproj/myenv/lib/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so" WSGIPythonHome "/TomCatWeb/app/projects/myproj/myenv" WSGIPythonPath /TomCatWeb/app/projects/myproj WSGIScriptAlias /hello /TomCatWeb/app/projects/myproj/proj/wsgi.py DocumentRoot /TomCatWeb/app/projects/myproj/proj/ <Directory /TomCatWeb/app/projects/myproj/proj> <Files wsgi.py> Require all granted </Files> </Directory> -
Which linux distro docker image I can use to connect to MySQL v8.0.12?
I have a redhat server with docker installed I want to create a docker image in which I want to run django with MySQL but the problem is django is unable to connect to MySQL server(remote server). I'm getting following error: Plugin caching_sha2_password could not be loaded: /usr/lib/x86_64-linux-gnu/mariadb19/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory I googled it and found that libraries does not support 'caching_sha2_password'. Can anyone suggest me which distro have libraries that support 'caching_sha2_password'? Thanks in advance. -
how to create rest API for .py file which connects to MySql
I have already created 2 .py files. one is connecting to MySql (dbconnect.py) and the other (app.py) is calling functions defined in the first file. I have uploaded my files on GitHub repository https://github.com/omkarcpatilgithub/Moneytor. can anyone help me creating a rest API for the 1st file (dbconnect.py) with Django? I have no idea about Django framework, what should I actually do or where I should start? -
How to get all details using filter condition in django?
This is my scenario I have user data in the user database. Example { id:1, email:'her@gmail.com' } filter condition sample = user.objects.filter(email='her@gmail.com') print(sample.id) I tried to print user id.but its throwing error.how to print id in the filter condition? and why its throw error any issue?. -
Is it possible in Django model to update a manually created primary key field using a calculated value during save()
In Django, is it possible to update the manually created primary key field of a model with a calculated value during save() method? For example, in the following model: class Siding(models.Model): siding_doc = models.PositiveIntegerField(primary_key=True, unique=True, default=1000, ...) created_date = models.DateField(default=timezone.now, verbose_name='Date Created') eff_date = models.DateField(verbose_name='Effective From') siding_rate = models.DecimalField(max_digits=5, decimal_places=2, ...) will it be possible for me to .get the last siding_doc number, increment the value by 1 and (kind of) insert the calculated value in the primary key field siding_doc for the new record. And if it is possible, can we do this in model's save() method? -
How to create comment form
I'm Django beginner. I am trying to implement a code on how to implement a comment form in home page. In all tutorials I have come across, it is advisable to pass an ID in views.py. How can I create a form in homepage without an ID? class Comments(models.Model): user=models.ForeignKey(settings.AUTH_USER_MODEL) commented_image=models.ForeignKey(Image,....) comment_post=models.TextField() def home(request): if request.method == 'POST': form=CommentForm(request. POST) if form.is_valid(): comment=form.save(commit=False) comment.user=request.user comment.commented_image=post comment.save() return redirect.... else: form=CommentForm -
how do I add 'id' to model form in Django?
I'm trying to control some input fields with JavaScript in my Django. So I thought I should assign class and id to each field. I've searched a bit and tried myself but didn't work. Below is my code: forms.py class MyInputForm(forms.ModelForm): format_free = forms.CharField(widget=forms.Textarea (attrs={'class':'formats', 'id':'format_free'}) ) format_simple = forms.CharField(widget=forms.CharField (attrs={'class':'formats', 'id':'format_simple'}) ) class Meta: model=MyInput fields=['format_free', 'format_simple'] widgets = {'authuser':forms.HiddenInput()} But this keeps on giving me error that says "TypeError: init() got an unexpected keyword argument 'attrs'" I have no idea on what went wrong. Thanks in advance :) -
Django deployment using pythonanywhere
So, I have deployed my site successfully on pythonanywhere, but when I try loading the site, I get the following error. TemplateDoesNotExist at / base.html Request Method: GET Request URL: http://devchron.pythonanywhere.com/ Django Version: 3.0.3 Exception Type: TemplateDoesNotExist Exception Value: base.html Exception Location: /home/devchron/.virtualenvs/devchron.pythonanywhere.com/lib/python3.7/site-packages/django/template/backends/django.py in reraise, line 84 Python Executable: /usr/local/bin/uwsgi Python Version: 3.7.5 Python Path: ['/home/devchron/devchron.pythonanywhere.com', '/var/www', '.', '', '/var/www', '/home/devchron/.virtualenvs/devchron.pythonanywhere.com/lib/python37.zip', '/home/devchron/.virtualenvs/devchron.pythonanywhere.com/lib/python3.7', '/home/devchron/.virtualenvs/devchron.pythonanywhere.com/lib/python3.7/lib-dynload', '/usr/lib/python3.7', '/home/devchron/.virtualenvs/devchron.pythonanywhere.com/lib/python3.7/site-packages'] Server time: Fri, 27 Mar 2020 07:01:54 +0000 Now, the statement which I use in the child templates is {% extends "base.html" %}. This is where the error happens. The error also states that: Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/devchron/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/devchron/.virtualenvs/devchron.pythonanywhere.com/lib/python3.7/site-packages/django/contrib/admin/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/devchron/.virtualenvs/devchron.pythonanywhere.com/lib/python3.7/site-packages/django/contrib/auth/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/devchron/devchron.pythonanywhere.com/blogposts/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/devchron/devchron.pythonanywhere.com/useraccounts/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/devchron/.virtualenvs/devchron.pythonanywhere.com/lib/python3.7/site-packages/markdown_deux/templates/base.html (Source does not exist) This makes sense as the file base.html is not present in any of these folders, instead it is present on /home/devchron/devchron.pythonanywhere.com/templates/base.html , django doesn't look here. I want django to look in that folder instead of the others to load the files successfully, any way to resolve this? I saw the file structure on … -
List Index out of range when reading an Excel File
When I'm reading the excel file I get this "List index out of range" error. views.py a_list= studentData list_iterator= iter(a_list) next(list_iterator) for detail in list_iterator: stuname= detail[0] print(stuname) student_batch = Batch.objects.get(name=stuname) email = detail[1] rs_id = detail[2] phone_number = str(detail[3]) dob = detail[4] address = detail[5] age = detail[6] firstName = detail[7] lastName = detail[8] username = detail[9] password = detail[10] print(type(phone_number)) user=User.objects.create( firstName = firstName, lastName = lastName, username = username, ) user.set_password(password) user.is_student = True user.school = request.user.school user.save() user_ins = User.objects.get(username=username) student=Student.objects.create( user = user_ins, email = email, rs_id = rs_id, dob = dob, address = address, age = age, ) It actually works and I tried to print the data and it prints the right data too. I don't know where is the error. Note: studentData is a list containing the data of user. Then I used next() to skip the first iteration and start from 2nd row. -
How to test a view that creates a new Organization(entity) in database in Django?
I'm new to Unit Testing. I have a view which takes an AJAX request and creates a new Organization to my database. How do I test it? Here is my view: @csrf_exempt def newOrg(request): if request.method == 'POST': param = json.loads(request.body) org = param.get('org') Organization.objects.create(orgname=org) return JsonResponse({'status':200}) The url used: ('ajax/newOrg/', views_admin.newOrg, name='ajax_newOrg'), -
How I can insert my django model data in fields for edit a record
I want to edit my product which all data is already in django model. When i add press the "edit" button in option a new form is open to edit a product but I don't know who to insert data in fields. Kindly give me guidance how i display me data in fields there is the image of my product and that is edit form if you see before the edit button data is displaying but i want that data in form fields views.py class EditProduct(TemplateView): template_name = 'stock/editproduct.html' def get(self, request, product_id): productedit = get_object_or_404(Product, pk=product_id) form = EditProductForm() args = {'form':form, 'productedit':productedit} return render(request, self.template_name, args) template.html {% extends 'base.html' %} {% block content %} <div> <h4>Edit Product!</h4> <hr/> <form method="post" enctype="multipart/form-data" > {% csrf_token %} {{ form.as_p }} <h4>{{productedit.pro_name}}</h4> <p>{{productedit.companyName}}</p> <p>{{productedit.Sale_Price}}</p> <p>{{productedit.Quantity}}</p> <button type="submit" class="btn btn-success" >Edit</button> </form> </div> {% endblock %} form.py class EditProductForm(forms.ModelForm): class Meta: model = Product fields = ('companyName', 'pro_name', 'Purchase_Price', 'Sale_Price', 'Quantity', 'Picture' ) def __init__(self, *args, **kwargs): super(EditProductForm, self).__init__(*args, **kwargs) self.fields['companyName'].label = 'Company Name' self.fields['pro_name'].label = 'Product Name' self.fields['Purchase_Price'].label = 'Purchase Price' self.fields['Sale_Price'].label = 'Sale Price' -
How to create a special function when a model instance is created?
I'm making a system wherein when the user creates a log he gains points from how it. How do I go about in trying to make this? I tried making a signal.py function but it's giving me an error of 'DPRLog' object has no attribute 'Points'. Am I doing it right? I just want to add points whenever I create a log so I placed it as signal.py class. Can anyone help me out? Thanks Heres my models.py: from django.db import models from profiles.models import User from django.urls import reverse # Create your models here. class Points(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=0, null=False) def __str__(self): return self.user.username class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' class Manager(models.Model): manager = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.manager.full_name class Member(models.Model): manager = models.ForeignKey(Manager, on_delete=models.CASCADE) member = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=30, null=True) def __str__(self): return self.member.full_name class Job(models.Model): manager = models.ForeignKey(Manager, on_delete=models.CASCADE) member = models.ForeignKey(Member, on_delete=models.CASCADE) title = models.CharField(max_length=30, blank=False, null=False) description = models.TextField() datePosted = models.DateTimeField(auto_now=True) file = models.FileField(null=True, blank=True, upload_to='job_files') def __str__(self): return self.title def get_absolute_url(self): return reverse('job-detail', kwargs={'pk': self.pk}) class DPRLog(models.Model): STATUS_CHOICES = ( ('PENDING', 'PENDING'), ('CANCELLED', 'CANCELLED'), ('COMPLETED', 'COMPLETED'), ) … -
How to give suggestions in the field entry form value from DB
I am doing basic project for small school in small town as charity non-profit (i am not professional devoloper). It is quite basic web for teacher to find student info ( grades and background). I choiced student code as there are students with exactly the same name and surnames so I thought code would be easier to distinct. This everything works good however i want teacher while typing studentcode in the entry field to get studentfullname as suggestion right in the field entry so they can choice from suggestions ( and click OK button) and avoide choicing wrong student. What i did so far: In models.py class ABC(models.Model): name = models.CharField(max_length=150) class Student(models.Model): studentcode=models.CharField(max_length=200) studentfullname=models.CharField(max_length=500) class Meta: managed=False db_table='class09' in forms.py i have : from django import forms from .models import ABC class ABCForm(forms.ModelForm): name = forms.CharField(max_length=150) class Meta: model = ABC fields = ('name',) in views.py : def index(request): if request.method == "POST": form = ABCForm(request.POST) if form.is_valid(): formps = form.save(commit=False) name = formps.name studbackground=Student.objects.get(studentcode=name) context={'background':studbackground ,} return render(request, 'vasagrad/back.html',context) else: form = ABCForm() return render(request, 'vasagrad/index.html', {'form': form}) index.html i have : <form method="POST" class="ticker_area" > {% csrf_token %} {{ form}} <button class = "ticker_button" type="submit">OK</button> </form> I …