Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Related model not updating in save override of a model being saved with ModelFormset
So I have Transaction model that is FK-d to a Share. In an 'Account' view, I have a ModelFormset of these Transactions and I can save multiple transactions by looping through the forms and saving them. On my Transaction's save() method I try and update the balance on the linked Share. this works if I save one transaction, but when I POST my ModelFormset with multiple transactions, everytime I hit the self.share.balance = self.share.balance + amt line in the Transaction save() override (that is for every new Transaction), the share.balance is what it was before any of the previous transactions in the formset were saved. Does anyone know why the added amount to share balance from a previous saved transaction is not carried on the subsequent saves (why only the last Transaction's amount will be added to share balance)? Transaction model which should update balance on parent-model Share class Transaction(models.Model): share = models.ForeignKey(Share, on_delete=models.CASCADE, null=True, blank=True) account = models.ForeignKey(Account, on_delete=models.CASCADE, null=True, blank=True) db_cr = models.CharField(choices=DBCR, max_length=2) amt = models.DecimalField('Amount', max_digits=11, decimal_places=2) post_dt = models.DateTimeField('Post Time', null=True, blank=True) def save(self, *args, **kwargs): if not self.pk: ... if self.share: if self in self.share.transaction_set.all(): logging.error('Transaction %s already posted' % self.id) return False amt … -
In an online game, how do I know which stage player is playing? At the same time, "time" is also important? [on hold]
i want the make a game that in this game a player answer the questions and each question has a "question_id" Each player can only answer a question at a moment And he has 15 seconds to do this how to implement database for know 1,2 ? is database a good why for know it? -
Django channel on IIS server
I write a django application, where I use django channel for real-time communication but it is complicated to run using IIS server. WSGI is working fine but ASGI is not working. Here is my web.config file: <configuration> <appSettings> <!-- <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> --> <add key="WSGI_HANDLER" value="main.wsgi.application" /> <add key="ASGI_HANDLER" value="main.routing.application" /> <add key="PYTHONPATH" value="C:\Project\chatserver\src" /> <add key="DJANGO_SETTINGS_MODULE" value="main.settings.base" /> <add key="WSGI_LOG" value="c:\project\wfastcgi.log"/> </appSettings> </configuration> Can you tell me whats wrong in my approach? One more thing, while I run the project using command prompt both WSGI and ASGI working fine. So, I decided to run the project using cmd, but is it a good idea? -
How can I send OpenCV output to browser with python django?
I want to send an OpenCV output to a browser(web application) that I'm working on. I know how to make a frame appear using my webcam controlled by OpenCV but I want to integrate that frame inside my website. What can I do in order to integrate in my website? Here's the code for OpenCV and thank you in advance! import numpy as np import cv2 import pickle face_cascade = cv2.CascadeClassifier('Cascades/data/haarcascade_frontalface_alt2.xml') eye_cascade = cv2.CascadeClassifier('Cascades/data/haarcascade_eye.xml') recognizer = cv2.face.LBPHFaceRecognizer_create() recognizer.read("trainer.yml") labels = {"person_name": 1} with open("labels.pickle", 'rb') as f: orig_lables = pickle.load(f) lables = {v:k for k,v in orig_lables.items()} cap = cv2.VideoCapture(0) while True: #capture frame-by-frame ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5) for (x, y, w, h) in faces: # print(x, y, w, h) roi_gray = gray[y:y+h, x:x+w] roi_color = frame[y:y+h, x:x+w] id_, confidence = recognizer.predict(roi_gray) if confidence >= 45 and confidence <= 85: print(id_) #print(lables[id_]) cv2.FONT_HERSHEY_SIMPLEX = 0 font = cv2.FONT_HERSHEY_SIMPLEX color = (255, 255, 255) name = lables[id_] stroke = 2 cv2.putText(frame, name, (x,y), font, 1, color, stroke, cv2.LINE_AA) img_item = "captured-image.png" cv2.imwrite(img_item, roi_gray) color = (0, 255, 255) #bgr format stroke = 2 width = x + w height = y + … -
TypeError: sequence item 0: expected str instance, tuple found when adding a news item in Django application
I'm creating a news site and am having trouble with adding a new article. This is the error I get when I click the New link: Internal Server Error: /news/new/ Traceback (most recent call last): File "/Users/paulcarron/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/paulcarron/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/core/handlers/base.py", line 156, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/paulcarron/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/core/handlers/base.py", line 154, in _get_response response = response.render() File "/Users/paulcarron/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/Users/paulcarron/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/response.py", line 81, in rendered_content template = self.resolve_template(self.template_name) File "/Users/paulcarron/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/response.py", line 63, in resolve_template return select_template(template, using=self.using) File "/Users/paulcarron/.local/share/virtualenvs/lakelandcc-6nBitmwo/lib/python3.7/site-packages/django/template/loader.py", line 47, in select_template raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) TypeError: sequence item 0: expected str instance, tuple found [29/Mar/2019 20:55:53] "GET /news/new/ HTTP/1.1" 500 76945 Below are my various files: urls.py from django.urls import path from .views import ( NewsListView, NewsUpdateView, NewsDetailView, NewsDeleteView, NewsCreateView, ) urlpatterns = [ path('<int:pk>/edit/', NewsUpdateView.as_view(), name='news_edit'), path('<int:pk>/', NewsDetailView.as_view(), name='news_detail'), path('<int:pk>/delete/', NewsDeleteView.as_view(), name='news_delete'), path('new/', NewsCreateView.as_view(), name='news_new'), path('', NewsListView.as_view(), name='news_list'), ] views.py from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView, CreateView from django.urls import reverse_lazy from .models import News class NewsListView(ListView): model = News template_name = 'news_list.html' class NewsDetailView(DetailView): model = News template_name = 'news_detail.html' class NewsUpdateView(UpdateView): model = News fields = ('title', 'body',) … -
error: [WinError 3] The system cannot find the path specified: 'C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v8.1\\lib'
While Install Simple-Json and MysqlClient I got this error running build_ext building 'simplejson._speedups' extension error: [WinError 3] The system cannot find the path specified: 'C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1\lib' ---------------------------------------- Command "c:\users\parmi_\desktop\unoapp\funding-backend-django\funding\venv\scripts\python.exe -u -c "import setuptools, tokenize;file='C:\Users\parmi_\AppData\Local\Temp\pip-install-7jvy4cfo\simplejson\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\parmi_\AppData\Local\Temp\pip-record-hbnbqo_d\install-record.txt --single-version-externally-managed --compile --install-headers c:\users\parmi_\desktop\unoapp\funding-backend-django\funding\venv\include\site\python3.7\simplejson" failed with error code 1 in C:\Users\parmi_\AppData\Local\Temp\pip-install-7jvy4cfo\simplejson\ -
Images not being served in django
My media which i have uploaded using the form in this question View does not seem to be saving all the information in my model is being uploaded to the correct /media/images folder that i have defined. However, on access it returns a 404. i have tried to follow the instructions on https://stackoverflow.com/a/39359264 but still am getting a 404. my template code {% for books in object_list %} <img src="{{ books.cover_pic.url }}"> {% endfor %} settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') my model code for the image is cover_pic = models.FileField(null=True, blank=True, upload_to='images/') my media folder is at base dir (next to manage.py). What am i overlooking? -
Ranking Model A by Model B
I have a Game Model and a Subscription Model: class Game(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True) cover = models.ImageField(upload_to='cover_images') def __str__(self): return self.title class Meta: ordering = ['title'] class Subscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) game = models.ForeignKey(Game, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) def __str__(self): return str(self.id) Now I'm trying to figure out how to sort Games by the number of subscribers. -
After getting a form.cleaned_data from POST how to pass it to another view?
as the title says: how can I (in DJANGO) get data from a form in a view (in the code below is the ALIMENTA2 view) and then use that as context in another class-based view (GMO, which is a PDF report built with easy_pdf)? I'm a noob at django, but I've tried redirect and render... I don't seem to understand exactly what I'm doing, really hahaha views.py def alimenta2(request): if request.method == 'POST': form = AlimentaForm(request.POST) if form.is_valid(): day = form.cleaned_data['sign_date'] shipper = form.cleaned_data['shipper'] context = {'day': day, 'shipper': shipper} #HERE IS THE PROBLEM, I WANT TO PASS THE CONTEXT: return redirect('GMO', context=context) else: form = AlimentaForm() return render(request, 'agroex/alimenta2.html', {'form':form}) class GMO(PDFTemplateView): template_name = 'agroex/gmo.html' def get_context_data(self, **kwargs): context = super(GMO, self).get_context_data( pagesize='A4', title='NON-GMO Certificate', day=self.day, **kwargs ) urls.py urlpatterns = [ path('', views.agroex, name='agroex'), path('alimenta2/', views.alimenta2, name='alimenta2'), path('alimenta2/GMO/', views.GMO.as_view(), name='GMO'), ] -
AttributeError: module 'posts.views' has no attribute 'home'
Learning from a Udemy course I am taking by Nick Walter on Django, I am writing my own “Credit Card Redaction” app. The basic functionality is in place. But now I am trying to add a blog post app to go with it. I successfully initiated the app using $ python3 manage.py startapp posts. But as soon as I started filling in the urls.py, template and sub-views, my server has stopped running. I get: File "/home//dev/projects/python/2018-and-2019/CC_Redact/CC_Redact/urls.py", line 10, in url(r'^$', views.home, name='home'), AttributeError: module 'posts.views' has no attribute 'home' This is Django 2.0 with Python 3.6 using the built in test server (no where near production environment yet). I’m running my code inside an activated virtual environment. These are the contents of my requirements.txt: Django==2.0.13 Pillow==5.4.1 psycopg2==2.7.7 psycopg2-binary==2.7.7 pytz==2018.9 Pretty basic, right? urls.py in my primary project folder: from django.contrib import admin from django.urls import path from . import views from posts import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), url(r'^result/', views.result, name='result'), url(r'^james/', views.posts, name='james'), views.py (in app folder): from django.shortcuts import render # Create your views here. def james(request): return render(request, 'posts/james.html') As you can see, I've named my function "james", as well as my template. … -
How to make my class-based view to work in django
am working on a project, its a blog that am building with django. Everything is working fine in the app but i heard of class-based view i read about it but i didnt fully understand it due to am not into OOP. But i just wanted to convert all my function-based view to class-based view and when i tried it, i got this error File "C:\Users\De Stone Of David\Desktop\python\second\projects\eblog\blog\views.py", line 146 def(self, request, **kwargs): ^ SyntaxError: invalid syntax here is the code for the function-based view views.py def newPost(request): deyCat = Category.objects.all() if request.method =='POST': myForm = NewPostForm(request.POST, request.FILES) response_data = { 'SType': 'danger', 'message': "An Error Occured, pls try again later" } if request.POST.get('deyHidden') == 'create_hidden': title = request.POST.get('title') content = request.POST.get('content') category_id = request.POST.get('category') image = request.FILES.get('image') if myForm.is_valid(): if Posts.objects.create(title=title, content=content, category_id=category_id, image=image, author_id=request.user.id): response_data = { 'SType': 'success', 'message': "Saved Successfully" } return HttpResponse(json.dumps(response_data), content_type="application/json") elif request.POST.get('deyHidden') == 'category_hidden': CatNames = request.POST.getlist('CatName[]') for CatName in CatNames: Category.objects.get_or_create(CatName=CatName) response_data = { 'SType': 'success', 'message': "Saved Successfully" } return HttpResponse(json.dumps(response_data), content_type="application/json") context={ 'form':NewPostForm(), 'title':'Create Post', 'category': Category.objects.all() } return render(request, 'blog/form.html', context) here is the code for the class-based view views.py class NewPostView(TemplateView): template_name = 'blog/form.html' deyCat = … -
Display a calculated field value in a ModelForm
I have an object Performance model in my Django project. class Performance(models.Model): performance_id = models.AutoField(primary_key=True) name = models.CharField(_('Nom'), max_length=64) code = models.CharField(_('Code'), max_length=16, db_index=True, default='') type = models.InterField(...) value = models.CharField(...) In the Admin interface, I have a dedicated PerformanceInlineAdmin and a PerformanceInlineForm class. In a Performance object, if the value field starts with "$" then the field contains kind of Reverse Polish Notation expression (such as "100 450 +"...). In this case, the value displayed shall be the calculated expression instead of the field plaintext value. But I still haven't found a reliable solution. Not even sure that it should be handled in the Form object. Any suggestion is welcome. Z. -
How to Load multiple Model to single template in Django 2
How to load multiple models in one template in Django 2? i've read Django Pass Multiple Models to one Template but, i'm lost in the answer and there is no specific answer there to get that view into the template, Im trying to pass 3 models in views to template, which is Info, Slogan & Berita. My views.py from django.shortcuts import render from django.http import HttpResponse from .models import Artikel, Berita, Data, Galeri, Info, Slogan, Profil from django.views.generic import ListView, DetailView def home(request): extra_context : {"info" : Info.objects.all(), "slogan": Slogan.objects.all(), "berita": Berita.objects.all(), #and so on for all the desired models... } return render (request, 'blog/home.html') class HomeListView(ListView): context_object_name = 'slogan' template_name = 'blog/home.html' queryset = Info.objects.all() def get_context_data(self, **kwargs): context = super(HomeListView, self).get_context_data(**kwargs) context['slogan'] = Slogan.objects.all() context['berita'] = Berita.objects.all() # And so on for more models return context my template home.html looks like: {% for slogans in slogan %} <p>{{ slogans.konten }}</p> <p>{{ slogans.author }}</p> {% endfor %} my url urls.py looks like: from blog.views import HomeListView urlpatterns = [ url(r'^$', HomeListView.as_view(), name="home"), ] and page source on browser shows nothing. Im stuck on this, i found at least 3 similar result on this site but not works for me. -
I'm trying to create a FORM for my project but i'm having ERROR when i try to migrate after creating the form fields
I'm having an error when i tried to migrate my form field to the database in my django project i tried the following command app name is "account" python manage.py makemigrations account worked fine then: python manage.py migrate account then i have this error: django.db.utils.OperationalError no such table: account_user thanks.Error messages -
Django extending user model:How to implement different sign up form for different user type.?
I'm am creating an appointment app where patients can register for appointments. Currently I have two models, user, doctor, and patient. The doctor and patient models have a one to one field with the user model. So when I create a user, they are either a doctor or a patient. The problem I'm having is that I register anew doctor, the form only asks for the fields in the user model and not the doctor model. Please advice. I've tried separate signup forms for the two models. First create the user, then use a different form to add information to the doctor model.But when I submit the doctor form, it says "The user already exists". models.py class User(AbstractUser): users = ( ('doctor', 'Doctor'), ('patient', 'Patient'), user_type = models.CharField(choices=users, max_length=9, default='patient') class Doctor(models.Model): upin = models.AutoField(primary_key=True) #unique physician identification number user = models.OneToOneField(User, on_delete=models.CASCADE) user.user_type = "doctor" specialty = models.CharField(max_length=20) appointments_per_hour = models.IntegerField(null=True) class Patient(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user.user_type = "patient" pid = models.AutoField(unique=True, primary_key=True) #patient identification forms.py class CustomCreationForm(UserCreationForm): class Meta(UserCreationForm): model = User fields = ('first_name','last_name','username','email','user_type',) class DoctorForm(UserChangeForm): class Meta: model = Doctor fields = ('specialty','appointments_per_hour',) -
How to make communication between users?
I'm writing a social network and don't know how to add users to my friends list. I will be glad of any help! -
Django - Settings : sensitive settings and different environments (dev, prod, staging). What is the recommended way to do this
I am using django version 2.1.7: I have read a lot of article and questions about this. I found people using various methods. Approches used in the general are: 1) setting environmental variables 2) multiple settings 3) load configuration variables from a file like using django-environ etc Approach 1: I will not be using, because i dont want to use environmental variables to store variables. Approach 3: uses 3rd party library and sometimes they may not be maintained any more. But if there is any standard way to do this i am fine. Approach 2: Here i am not sure how to store the sensitive data seprately. So can someone guide me in this regard. -
Is Python with Django a good start for writing a web app with NoSQL database to store online?
I am going to start a web app project and plan to do it in Django. This web app is gonna have functions of an online store, but also for sign-in & sign-up for users doing questionnaire for very first time of registration, making appointment, and a “back stage” for me to jot the consulting record of the related users. So in this case, I think I need a database to store the web app data and plan to go with mongoDB. The database will be also planned to link to store data of the chatbot that link to some IMs for asking users some daily record, keeping track after the consultation and check the appointment. I did consider Django and mongoDB because of Python language and various of packages for Python and Django. However, I can’t totally figure out how to plan out what to use for the web app and where to store my database. What I did plan is building the web app in Django with some packages for the website part, so that it includes the site, registration & login system for appointment and questionnaire part, also my “consulting backend”. For the chatbot, I did plan … -
django-martor doesn't render level 2 header at admin?
I'm trying to integrate martor to my project, I found h2 header does not seem to display properly in the preview, it is highlighted with a blue bar. I don't know why. Where could be the problem? Or could you suggest some better markdown apps for django? Thanks! -
Can I create a related Django field between two models with a shared foreign key value?
I have two models: class Foo(Model): special_id = IntegerField(primary_key=True) class FooDetail(Model): special_id = IntegerField(primary_key=True) special_id comes from an outside source -- it's a foreign key into another database. Yes, Foo and FooDetail should be combined into a single model -- but assuming I can't -- can I create a related field between the two models such that I can use it in queries (like in values or select_related)? -
Have a different custom domain for each tenant Django tenant with boto3
I am using django tenant for my application. In my settings.py I have AWS_STORAGE_BUCKET_NAME = env.str('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME However, I would like to use a different bucket name for each tenant, how do I go about this? -
Django form keeps complaining required field
The form submits but immediately says this field is required... although it was filled out. What am I doing wrong In my view: def fileupload(request): if request.user.is_authenticated and request.user.is_staff: if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES.getlist('file_field')) return HttpResponseRedirect('/fileupload/') else: form = UploadFileForm() return render(request, 'fileupload.j2.html', {'form': form}) return HttpResponseForbidden('<h1>403 Forbidden</h1>') with this form: class UploadFileForm(forms.Form): kit_number = forms.CharField(label="Kit number", max_length=100, required=True, help_text='Required.') file_field = forms.FileField(label='Upload kit result') and model: class Kit(models.Model): def __str__(self): return self.number + " " + self.reminder user = models.ForeignKey(User, on_delete=models.CASCADE) number = models.CharField(max_length=100) reminder = models.CharField(max_length=500) gender = models.BooleanField() file = models.OneToOneField(Document, on_delete=models.CASCADE, null=True, blank=True) -
remove accents from a string [duplicate]
This question already has an answer here: What is the best way to remove accents in a Python unicode string? 9 answers I have the following example string to make a function which will remove accents string = 'Cotización pruebá ácentos' self.remove_accents(string.decode('utf-8')) the function that I have is the following def remove_accents(self, s): return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn') it removes the accents but it returns something like this =?utf-8?b?q290axphy2nds24=?= =?utf-8?b?ihbydwviw6e -
Django display model content into html template
I have a problem with displaying content from Model in Django. I was created example model with one field which is "title" class Post(models.Model): title = models.CharField(max_length=100) def __str__(self): return self.title Then I am trying to create function in views.py which allow me to get objects from this field created in Django admin field, like this: def post_title(request): title = Post.objects.all() context = {'titles': title} return render(request, 'home.html', context) And I am trying to display it in html file using template: {% extends "base.html" %} {% block content %} <div class="container"> <div class="row"> <p>{{ titles.title }}</p> <div class="row"> <div class="col col-sm-3">col 2</div> <div class="col col-sm-3">col 2</div> <div class="col col-sm-3">col 2</div> <div class="col col-sm-3">col 2</div> </div> <div class="row"> <div class="col col-sm-3">col 3</div> <div class="col col-sm-3">col 3</div> <div class="col col-sm-3">col 3</div> <div class="col col-sm-3">col 3</div> </div> </div> {% endblock %} I would like to achieve displaying single string containt name of title in html. -
Scaling or avoiding migrations when using Django 2.x?
I'm just beginning my journey with Django framework and I read that Django developers have made using migrations mandatory beginning from version 2.0. I might be old school but I like my database separate from my code. I have always kept my database separate from my code models. I think that the migrations won't scale with the engineering team size. So my question is 2 fold. Can you not use Django 2.0 without the migrations as I don't think it will scale well and won't fit the CI/CD pipeline? If we can't avoid the db migrations then how can we integrate them in a robust CI/CD pipeline where a model can be changed by different developers from different teams.