Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to grab context data for Related Model with ManyToManyFiled Relation in Django
I have two models Named Teacher and Class, like below. Where Class and Teacher are related to ManyToManyField in the class_instructor field. That means a class has more than one teacher. Now I wanted to show all the teachers that belong to that particular class instance and in the Class Detail View. My Teacher Model class Teacher(models.Model): teachers_name = models.CharField(max_length=32,help_text="Enter a Teachers Name here") teachers_speciality = models.CharField(max_length=32,help_text="Enter a Teachers Speciality.e.g. Drawing Instructor") teachers_description = models.TextField(max_length=1200,help_text="Enter a Teachers Description") teachers_image = models.ImageField(blank=True, null=True) def __str__(self): return self.teachers_name My Class Model class Class(models.Model): class_name = models.CharField(max_length=120,help_text="Enter the class Name here") class_duration = models.CharField(max_length=30,help_text="Enter class duration",default='1 Year') class_instructor = models.ManyToManyField(Teacher) available_seats = models.PositiveIntegerField(default=30) class_description = models.TextField(max_length=500,blank=True,null=True) course_description = models.TextField(max_length=2500,blank=True,null=True) course_type = models.CharField(max_length=20,help_text="Enter the course type here,e.g. Basic") class_iamge = models.ImageField(blank=True, null=True) class_iamge_detail = models.ImageField(blank=True, null=True) class_added_at = models.DateField(auto_now=False) student_ages = models.IntegerField() tution_fee = models.IntegerField(blank=True, null=True) def __str__(self): return self.class_name def get_absolute_url(self): return reverse("class_detail", kwargs={"pk": self.pk}) I have tried the following way, like using get_context_data where I tried to filter my Teacher model with associated pk of the class detail. But unable to figure out anything that works. Instead, I showed all the teachers in the class detail page, but I wanted to show … -
How to get Django admin urls for specific objects?
I hope my title is enough to understand my question this is my admin.py @admin.register(studentDiscount) class studentDiscount(admin.ModelAdmin): list_display = ('Students_Enrollment_Records', 'Discount_Type','my_url_field') ordering = ('pk',) def my_url_field(self, obj): return format_html("{% url 'record' %}", obj.Students_Enrollment_Records.Student_Users.id) my_url_field.allow_tags = False my_url_field.short_description = 'Students Record' this the result what I want if I click on the Download link it will go to specific html by Student ID this is the result if i click the Download link -
my url in django doesn't return HTTPResponse?
there is a problem with a url i've created in django that it doesn't totally work this is urls.py from django.conf.urls import include, url from django.contrib import admin from pizza import views urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url('', views.home,name='home'), url('order/', views.order,name='order'), ] and this is views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return HttpResponse("Home page") def order(request): return HttpResponse("Order a pizza page") -
Django, mozilla_django_oidc and admin interface
i am trying to connect Okta with a custom Django (v.3.0.2) app i am coding, using the mozilla-django-oidc library. So far the initial user authentication and account creation (using Django's user model) works, but i don't understand what i need to do to have the Django AdminSite work. The Adminsite, before introducing mozilla-django-oidc worked as expected. I created an admin user, named "admin" and the user was able to login. To integrate the mozilla-django-oidc library i followed the instructions here: https://mozilla-django-oidc.readthedocs.io/en/stable/installation.html. The instructions do not have any specific mention of the AdminSite. When i access the AdminSite after the library integration, i have the following: The AdminSite uses the default template - my assumption was that it would also use Okta to authenticate. The admin account "admin" that used to be able to login into the AdminSite does not work anymore My goal is to be able to access the AdminSite. I don't mind if it will be over Okta or over the vanilla interface as long as i can access it. Below are the relevant segments from the files (in order to integrate): urls.py urlpatterns = [ path('', static_site.site_index, name='site_index'), path('admin/', admin.site.urls), path('review/', include('review.urls')), path('oidc/', include('mozilla_django_oidc.urls')), ] settings.py # … -
How to print docstring for class atrribute/ element?
I have a class: class Holiday(ActivitiesBaseClass): """Holiday is an activity that involves taking time off work""" Hotel = models.CharField(max_length=255) """ Name of hotel """ I can print the class docstring by typing: print(Holiday.__doc__) This outputs as: Holiday is an activity that involves taking time off work How can I print the docstring for Hotel which is a Class attribute/ element? What I've tried print(Holiday.Hotel.__doc__) returns: A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed. I've also tried the help() function to no avail. -
Is there a Python library that automatically detects and blurs out faces from photos?
I am currently working on a mobile app about taking photos of some kind and store and share them with other users. Due to privacy reasons, I would like to have persons' faces on these images to be blurred out (same as in the Google Street View photo material). My plan would be to let the user upload his photo and inside my Django environment, I would like to detect faces on photos and blur them out automatically and store this modified photo on the server. Is there a library that can achieve this task out of the box? -
How to make custom imput fileds in django admin that doent related to the model?
Info from input fields i would be to use inside save_model method. I know how to make read only fileds. class InboiceDataAdmin(admin.ModelAdmin): form = CarProductDataForm readonly_fields = ('car_brand', 'car_number', 'year_of_manufacture') def car_brand(self, obj): person_id = get_request().user.person.id car = CarProductData.objects.get(product__customer__person_id=person_id) return car.car_brand but i want to add fields for input info. -
Dynamically expand form fields in Django
I am working on language learning CRUD app in which user can create his set of words and translations. Having following model: class StudyModule(models.Model): NAME = models.CharField(unique=True, max_length=100, primary_key=True) words = JSONField(default=dict) # 'word' : 'translation' and form: class AddModule(Form): name = forms.CharField() word = forms.CharField() translation = forms.CharField() I want to dynamically expand form's word and translation fields without reloading page. I have already achieved this, with some JS and by implementing views that way: def create_module(request): if request.method == 'POST': form = AddModule(request.POST) if form.is_valid(): name = request.POST.get('name') words = request.POST.getlist('words') translations = request.POST.getlist('translations') word_data = {word: translation for word, translation in zip(words, translations)} module = StudyModule.objects.create(NAME=name, words=word_data) module.save() else: form = AddModule() return render(request, 'teacher/create_module.html', {'form': form}) HTML: <form method="post" class="module-form"> {% csrf_token %} <div class="clone-box"> <div class="cloned-element"> {{ form.as_p }} </div> </div> <input type="submit" value="Save" name="save-word" class="submit-button"> <button type="button" class="clone-form-button">Add new</button> <!-- JS clones only word and translation input, without requesting server --> </form> In my solution initialising AddModule instance is almost redundant. Is there a better, clean way to save that data without requesting server each Add new button click? -
django dont raise error if I insert null data in columns
hello I don't used null and blank kwargs in my model for fields but I can insert null value into fields without giving any error this is my model class Project(models.Model): title = models.CharField(max_length=100) body = models.TextField() category = models.ForeignKey(Category, models.SET_NULL, null=True) expertises = models.ManyToManyField(Expertise) language = models.CharField(max_length=35) email = models.EmailField() attachments = ArrayField(models.FileField(), null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_at'] and this is code of creating object project = category.project_set.create( title="a title", body='a body text' ) the data will insert to the database successfully without giving any error -
Sending parameters from return statement to path in Django
Currently, I am using this code to render a page: return render(request, 'appname/bundles_edit.html', context) This works fine. However, I would like to send two integers to my path: path('bundles/<int:bundle_template_number>/<int:bundle_id>/', views.bundles_edit, name='bundles_item'), How would I insert those two integers in my return render statement? -
How to put a delete button beneath each post?
The goal here is to add a delete button beneath every post, and once it is clicked, the corresponding row will be deleted from the table in the database. views.py from django.shortcuts import render, redirect from .forms import CreatePostForm from django.contrib import messages from .models import CreatePost def create_post(request): if request.method == 'POST': form = CreatePostForm(request.POST) if form.is_valid(): post = form.save(commit = False) post.save() messages.success(request, f'The post has been created.') return redirect('home_page') else: form = CreatePostForm() return render(request, 'post/create_post.html', {'form': form}) def view_post(request): context = CreatePost.objects.order_by('-dateCreated') return render(request, 'post/view_post.html', {'context': context}) So far, there is one page, create_post.html, that allows users to create a post. There is a second page, view_post.html, that allows users to see all posts with the most recently added first. I want to put a delete button beneath every post in view_post.html. view_post.html {% extends "home_page/base.html" %} {% load crispy_forms_tags %} {% block content %} <h1>Volunteer Opportunities</h1> {% for x in context %} <h4> {{ x.task }} <small class="text-muted">Date Required: {{ x.dateRequired }}</small> </h4> <blockquote> <p>{{ x.description }}</p> <p>Date Posted: {{ x.dateCreated }}</p> </blockquote> <hr> {% endfor %} {% endblock content %} I'm not sure if this is necessary, but below are models.py and the project … -
Create login page without using Django default login form
I would like to know if it’s possible to create his own login page (from scratch) without using any Django default login forms because I want to add others fields in addition? Thanks in advance -
Tracing Memory Leak in django-rest-framework app
I have a suspected memory leak on an app that uses django + django-rest-framework. I have tried several things but still no success in tracing it to the exact root. The view generates an interactive image of fits files (used in astronomical applications) using Bokeh but it also has an option of using matplotlib.pyplot to generate a png file. There were a couple of events that ended up with the server crashed with memory usage in the order of 35%. Development server is a 12-core intel i7 with 32 GB of ram running Centos 7. Maybe is normal for django to use a lot of memory but it should release it at some point. Memory evolution x-axis is seconds, y-axis memory percent Things that I've tried. Switching Cache backend. I currently have the FileBasedCache backend, but going from LocMemCache to MemcachedCache only improved it a little bit. This is, after a couple of requests it goes up above the GB threshold and then goes down a couple of hundreds of MBs only. And then stays there forever. Implemented Gunicorn as production server, with nginx as proxy (as recommended in the docs). Added tracemalloc in the view to get memory usage … -
Django production server error 13 while saving a pickure
so I start making a server to help a school project and I have not found the anwser to these questions. In geral the code works like these when you first open the site and register an account, the system will check if the account exists. If not then it will create It and make an cracha for it, that is basically an image, but in production server with apache, I can not save the image that the system generates. The server is running in a raspberry machine with ubunto server, I set up the permissions 777 to the media folder that is where the system save the cracha image and a sudo chown www-data:www-data -R base_directory/ and chmod 777 -R Base_directory views: def register(request): if request.method == 'POST': senha1 = EncritpPassword(request.POST.get('senha', 'error')) senha2 = EncritpPassword(request.POST.get('senha-r', 'error')) Email = request.POST.get('email', 'erro') nome = request.POST.get('nome', 'erro') comite = request.POST.get('SelectionCommitee', 'No Committee') NOW = datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S") if ( (senha1 != 'error') and (senha2 != 'error') and (senha1 == senha2) and (Email != 'erro') and (nome != 'erro')): user = CheckUser(Email) if user == False: UserProtocol = EncritpEPR(Email) Cracha_Generator(UserProtocol, nome, comite) with connection.cursor() as cursor: messages.success(request, 'Success creating your account now login please!') … -
PasswordResetConfirmView doen't generate mail
I'm trying to set a "forgot password" link in my django application, using the default auth views but with my own templates inside an specific path. I was able to implement the reset form and the 'Done' wview , but aperantly the mail is not beeing generated. Not errors either. This is my urls.py file: path('password-reset/', PasswordResetView.as_view( template_name='auth/reset_password/reset.html', subject_template_name='auth/reset_password/mail_subject.txt', email_template_name='auth/reset_password/mail_body.html', success_url='/password-reset/done/' ), name='password_reset'), path('password-reset/done/', PasswordResetDoneView.as_view( template_name='auth/reset_password/done.html' ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view( template_name='auth/reset_password/confirm.html' ), name='password_reset_confirm'), path('password-reset-complete/', PasswordResetCompleteView.as_view( template_name='auth/reset_password/complete.html' ), name='password_reset_complete'), My mail_body.html: {% autoescape off %} To initiate the password reset process for your {{ user.get_username }} TestSite Account, click the link below:{% url 'password_reset_confirm' uidb64=uid token=token %} If clicking the link above doesn't work, please copy and paste the URL in a new browser window instead. Sincerely, The Epicups Team {% endautoescape %} I'm thinking that maybe my user model my be the problem, since im using the mail as username, so here it is: class CustomUser(AbstractBaseUser, PermissionsMixin): email= models.EmailField(_('email'), unique=True) vat_number = models.CharField(_('vat_number'), max_length=9) company_name = models.CharField(_('company_name'), max_length=255) contact_person = models.CharField(_('contact_person'), max_length=255) host_id = models.CharField(_('host_id'), max_length=255, blank=True) last_login_at = models.DateTimeField(_('last_login_at'), auto_now_add=True) current_login_at = models.DateTimeField(_('current_login_at'), auto_now_add=True) last_login_ip = models.CharField(_('last_login_ip'), max_length=100, blank=True) current_login_ip = models.CharField(_('current_login_ip'), max_length=100, blank=True) login_count = models.BigIntegerField(_('login_count'), null=True) is_active … -
How to make Django use current application's templates folder?
Right now I have a Django project with three apps. In my last app, the index.html loaded by my views.py is the index.html in another app's templates folder. Note this is how it is actually loading it, but not how I intend it load. The index.html in templates where the corresponding views.py is defined is not used. What I am wondering is how I define my settings so that the templates folder for the current application directory is used. This is my settings.py with respect to templates: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] This is the call to index.html def indexView(request): form = FriendForm() friends = Friend.objects.all() return render(request, "index1.html", {"form": form, "friends": friends}) -
Django: display my own field through custom form property doesnt work
I have a SurveyForm where I create dynamically my fields. Here's the most basic code I could do and still have my problem: class SurveyForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields = [] self.fields_alone = [] new_field = forms.CharField(label=f'1 - 2: This is the question', widget=widgets.Input(attrs={})) self.fields.append(('id_1', new_field)) self.fields_alone.append(new_field) self.fields = OrderedDict(self.fields) In my template, when I do a "classical" loop I can display the fields and it works, but the second loop, which is supposed to access to the same fields, doesn't work: <form action="" method="post"> {% for field in form %} {{ field.label }}&nbsp;:{{ field }} <br> {% endfor %} {% for field in form.fields_alone %} {{ field.label }}&nbsp;:{{ field }} <br> {% endfor %} </form> The second loop display the field as a string like <django.forms.fields.CharField object at 0x0000012C00EF60D0> What am I missing to display is like the "classical" loop? -
Django Rest Framework - how to customize serializer field
I'm currently working on DRF. models.py class Post(models.Model): id = models.IntegerField() content = models.CharField() category = models.CharField() created = models.CharField() Below, the Response I want to get [ { "id": "1", "content": "a", "category": "post", "created": "2020-01-23" }, { "id": "3", "content": "b" }, ] How can I get the response like above just using ONE model. -
Python Return function before thread finishes [duplicate]
I have a python function def image_backup(request, pool, namespace): thread1 = threading.Thread(target=backup(pool, namespace), args=(12, 10)) thread1.start() return HttpResponse(content="Success") The function works as intended, minus one thing. It will wait for the function the thread executes before it returns the HttpResponse. Is there a way for it to immediately return the function before the thread finishes? -
ValueError at --View didn't return an HttpResponse object. It returned None instead
I got this error when submitting the form. * I double-checked the views.py * Sometimes after deleting the database file (db.sqlite3): it worked correctly with the same views.py and html template, but after restart computer, the same error comes back again. ValueError at /en/checkout/ The view core.views.EnCheckoutView didn't return an HttpResponse object. It returned None instead. and here is its views.py class EnCheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, 'DISPLAY_COUPON_FORM': True } shipping_address_qs = Address.objects.filter(user=self.request.user, address_type='S', default=True) if shipping_address_qs.exists(): context.update({ 'default_shipping_address': shipping_address_qs[0] }) billing_address_qs = Address.objects.filter(user=self.request.user, address_type='B', default=True) if billing_address_qs.exists(): context.update({ 'default_billing_address': billing_address_qs[0] }) return render(self.request, 'en-checkout-page.html', context) except ObjectDoesNotExist: messages.info(self.request, 'You do not have an active order.') return redirect('core:en-checkout') def post(self, *args, **kwargs): form = CheckoutForm(self.request.POST or None) try: order = Order.objects.get(user=self.request.user, ordered=False) if form.is_valid(): use_default_shipping = form.cleaned_data.get("use_default_shipping") if use_default_shipping: print('Using the default shipping address') address_qs = Address.objects.filter(user=self.request.user, address_type='S', customer_name=customer_name, phone=phone, email=email, default=True) if address_qs.exists(): shipping_address = address_qs[0] order.shipping_address = shipping_address order.save() else: messages.info(self.request, 'No default shipping address available') return redirect('core:en-checkout') else: print('User is entering a new shipping address') customer_name = form.cleaned_data.get('customer_name') phone = form.cleaned_data.get('phone') email = form.cleaned_data.get('email') shipping_address1 = form.cleaned_data.get('shipping_address') shipping_address2 = form.cleaned_data.get('shipping_address2') … -
Django form.is_valid() returns False
I am creating a blog in django and i'm stuck at adding writing post_update_view, where form.is_valid() returns False and i'm not able to update the post. I've also checked this Django form is_valid() fails but i could not navigate to the right spot. Also, it's weird as for post creation form.is_valid() works fine (i'm assigning "form = PostModelForm(request.POST or None)" there). I would appreciate any suggestions. Greg Below is: Views.py def post_update_view(request, slug): obj = get_object_or_404(Post, slug=slug) form = PostModelForm(request.POST or None, instance=obj) print(form.is_valid()) if form.is_valid(): form.save() template_name = 'blog/post_update.html' context = {'form': form, 'title': f'Update {obj.title}'} return render(request, template_name, context) models.py: from django.conf import settings from django.db import models User = settings.AUTH_USER_MODEL class Post(models.Model): CATEGORY_CHOICES = ( (None, '--------'), ('CB', 'City Break'), ('1W', 'Week holidays'), ('2W', 'Two weeks holidays'), ('MO', 'Month holidays'), ('SB', 'Sabbatical'), ) CONTINENT_CHOICES = ( (None, '--------'), ('AS', 'Asia'), ('AU', 'Australia and Oceania'), ('AF', 'Africa'), ('EU', 'Europe'), ('NA', 'North America'), ('SA', 'South America'), ) user = models.ForeignKey( User, default=1, null=True, on_delete=models.SET_NULL ) title = models.CharField(max_length=150) date = models.DateField() category = models.CharField( max_length=100, choices=CATEGORY_CHOICES, blank=True ) continent = models.CharField( max_length=100, choices=CONTINENT_CHOICES, blank=True ) body = models.TextField() slug = models.SlugField() def __str__(self): return self.slug forms.py: from django import … -
django-rest-auth google and facebook sign up returning access token and code
I am building a rest api with Django, and I an using Django rest auth for social authentication. I believe I am doing everything right. upon visiting the route I get a response that I am to provide both access token and code for both Google and Facebook. I am lost at this point what to do. Please anyone who has an idea, please share. I have gotten the secret key and client id from both providers and inputed them in my settings.py and django admin. settings.py INSTALLED_APPS = [ ... 'django.contrib.sites', ... 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', ... ] SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'METHOD': 'oauth2', 'SCOPE': ['email', 'public_profile', 'user_friends'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'INIT_PARAMS': {'cookie': True}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'verified', 'locale', 'timezone', 'link', 'gender', 'updated_time', ], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': 'path.to.callable', 'VERIFIED_EMAIL': True, 'VERSION': 'v2.12', 'APP': { # get the key from "https://developers.facebook.com/apps/615248019004301/settings/basic/" 'client_id': 'code', 'secret': 'code', 'key': '' } }, 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'offline', }, 'APP': { # get from "console.developers.google.com/" then apis then credentials then oauthclient # fill in http://127.0.0.1:8000/accounts/google/login/callback/ in the “Authorized redirect URI” field 'client_id': 'code.apps.googleusercontent.com', 'secret': 'code', 'key': '' } } } … -
Pandas DataFrame to tablib.Dataset (for django or python)
A problem i encountered will trying to import data into django-import-export resources solution: from tablib import Dataset import pandas as pd dataset=Dataset(headers=list(df)) #extend dataset with data from df dataset.extend(df.to_records(index=False)) #replicate for clarity or export as json,xml,pdf,html,xls,xlsx,csv d.export('df') -
Django partial view with data from database
It is possible to create a partial view with database query and render it in multiplle views. Something like a commonente that when included in a view, works autonomously (make your query to the database and render your own view). In addition, I have a ship form in the navbar that makes a query to the database and brings a list of services. It is included in base.html and in each of the view I make it to the database to obtain the data and pass it in context. What I would like is to link some form in the search form with class view class. and to be able to bring the data I have found several ways to do it with javasript .. but if I could do it with Django it would be easier -
django models - invalid data after deleting attribute
I have these model for example (now noses have names): class Person(models.Model): id = models.AutoField(primary_key=True) class Nose(models.Model): id = models.AutoField(primary_key=True) owner = models.OneToOneField('Person', on_delete=models.CASCADE, primary_key=False, related_name='nose') name = models.CharField(max_length=50, null=True, blank=True) And I have this code that deletes a person nose (horrible accident...): danny = Person() danny.save() # danny.nose would raise: {RelatedObjectDoesNotExist}Person has no nose. nose = Nose(owner=danny, name='Big one') nose.save() # Now data in 'danny' is: # "id" attribute: 1 # "nose" attribute: nose instance with name "Big one" and id 1 # danny.nose would return the nose instance if hasattr(danny, 'nose'): danny.nose.delete() # After delete: data in 'danny': # id = 1 # nose: nose instance with name "Big one" and id None # danny.nose would return the nose instance with None id danny_from_db = Person.filter(id=1).first() # data in danny_from_db: id = 1, no "nose" attribute - hasattr(danny, 'nose') would return False # danny_from_db.nose would raise: {RelatedObjectDoesNotExist}Person has no nose. Why does the Person instance keeps that Nose attribute with None id, after deleting it from DB?