Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-tenant: write dataframe to postgresql schema (automatically find the schema)
Here is my issue in my django app: A tenant log in and then import csv file into his schema. I am processing the with pandas and so I use sqlalchemy to write in the schema. I found help on this topic there SQLAlchemy support of Postgres Schemas but it does not do the trick Here is my django form where the writing operation is happening. the code does not show any error, however, everytime I register a new user, the data gets imported to "t1", the first schema of the list. Strangely enough, if I create a new database and the first user I create is t2, then t2 gets the data imported well, then if i create t1, it gets created well too. But then I create "t3" and the data goes to "t1. my lack of expertise in the topic prevents me from understand what is going and where to look at to find the solution. dbschema = 't1,t2,t3,t4,public' engine = create_engine('postgresql://user:mypassowrd@127.0.0.1:5432/dbexostock12', connect_args={'options': '-csearch_path={}'.format(dbschema)}) DB = tableau.to_sql('dashboard_tableau', engine, if_exists='replace') -
Filtering by nested foreignkey field with django-filters
I've a Customer model which has User as a foreignkey field. In Customer ListView I want to search by name of Customer (Customer --> User --> Name). The ModelChoiceFilter is giving s list of all user objects as a dropdown. I'm unable to figure out how can I put it as a search box of names. Based on another stackoverflow answer, I tried to put it as a ChoiceFilter with a callable as choices argument, but then pagination object started giving error. Could anyone please help. Models.py class User(AbstractUser): name = models.CharField(max_length=100) phone = PhoneNumberField(unique=True) email = models.EmailField(unique=True) class Customer(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) Filters.py class CustomerFilter(django_filters.FilterSet): User = get_user_model() user = django_filters.ModelChoiceFilter(queryset=User.objects.all()) class Meta: model = Customer fields = { 'user':[], } -
Appropriate database for the Django project
We have a new requirement for the Django project. I want to identify the appropriate database for this. Overview: Data will be read from the flat files(Excel, PDF, etc..) and stored into the database. For any future requirement, the stored data from the database will be read again. I go through the Django documentation for the databases and there I see various options (Postgresql, Oracle, MySql, etc..) including 3rd party databases like SQL Server for Django. So, I would like to identify the appropriate database for this application. Which database is better to be used with Django project. Thanks in advance. -
<class 'main.admin.HomepageAdmin'>: (admin.E012) There are duplicate field(s) in 'fieldsets[0][1]'
i am currently working on cartridge ecommerce website:i have usermodel from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext, ugettext_lazy as _ from django.db import models from mezzanine.pages.models import Page from mezzanine.core.models import Orderable from mezzanine.core.fields import FileField, RichTextField from mezzanine.core.models import SiteRelated from cartridge.shop.models import Product from datetime import datetime from mezzanine.utils.timezone import get_best_local_timezone from mezzanine.conf import settings from pytz import timezone @python_2_unicode_compatible class SiteConfiguration(SiteRelated): """Singleton model for storing site-wide variables.""" logo = FileField("Logo", upload_to="site", format="Image", blank=True) logo_small = FileField( _("Small Logo"), upload_to="site", format="Image", blank=True ) favicon = FileField( _("Favicon"), upload_to="site", blank=True, help_text=_("An image that appears in the browser tab") ) footer_address = RichTextField( default=_("Our address"), help_text=_("Company address displayed in footer.")) footer_subscribe_info = models.CharField( max_length=200, default=_("Pellentesque habitant morbi tristique senectus et netus \ et malesuada fames ac turpis egestas."), help_text=_("Text displayed above the subscription email field.") ) def __str__(self): return str(self.site) class Meta: verbose_name = verbose_name_plural = _("Site Configuration") class Homepage(Page): """Main class for homepage.""" product_heading = models.CharField( max_length=100, default=_("Hot This Week"), help_text=_("A header displayed above the products.") ) second_slider_heading = models.CharField( max_length=100, default=_("GET INSPIRED"), help_text=_("A header displayed above the 2nd slider.") ) second_slider_subheading = models.CharField( max_length=100, default=_("Get the inspiration from our world class designers"), help_text=_("A … -
How to get models.CASCADE in ManytoMany relationships in Django?
I have 2 tables: class Subject(models.Model): level = models.CharField(max_length=50) subject_name = models.CharField(max_length=50) teacher_name = models.ForeignKey(Teacher, on_delete=models.CASCADE) total_seats = models.IntegerField() subject_details = models.CharField(max_length=50) class Season(models.Model): season = models.CharField(max_length=2, primary_key=True) subject = models.ManyToManyField(Subject) When I delete a Subject instance, I want the Season instance that is related to delete as well. How do I do that in the models? -
How to get moodle's reports and other related data in python django rest
I want to work on a project in which i want to be able to access the reports and to create update and delete courses, assignments and quizzes in moodle via django api. But i don't know where to start from. -
DRF password rest workflow throwing django.template.exceptions.TemplateDoesNotExist
I'm using Django Rest Password Reset for the reset password workflow as it's, at my sight, the best supported for this particular case. In urls.py # Password reset path('reset-password/verify-token/', views.CustomPasswordTokenVerificationView.as_view(), name='password_reset_verify_token'), path('reset-password/', include('django_rest_passwordreset.urls', namespace='password_reset')), If i go to reset-password/ after running the server, this is what i get If i POST an email that's not stored in the DB, then it gives a HTTP 400 Bad Request with { "email": [ "There is no active user associated with this e-mail address or the password can not be changed" ] } If i POST an email that's stored in the DB, then I get TemplateDoesNotExist at /test_app/reset-password/ user_reset_password.html I placed the signal receiver inside of a view named CustomPasswordResetView class CustomPasswordResetView: @receiver(reset_password_token_created) def password_reset_token_created(sender, reset_password_token, *args, **kwargs): """ Handles password reset tokens When a token is created, an e-mail needs to be sent to the user """ # send an e-mail to the user context = { 'current_user': reset_password_token.user, 'username': reset_password_token.user.username, 'email': reset_password_token.user.email, 'reset_password_url': "{}?token={}".format(reverse('password_reset:reset-password-request'), reset_password_token.key) } # render email text email_html_message = render_to_string('user_reset_password.html', context) email_plaintext_message = render_to_string('user_reset_password.txt', context) msg = EmailMultiAlternatives( # title: "Password Reset for {title}".format(title="Some website title"), # message: email_plaintext_message, # from: "test@test.com", # to: [reset_password_token.user.email] ) msg.attach_alternative(email_html_message, … -
Ordering one-to-many by "reverse related" model
I have two models with a one-to-many relationship, say: class EmailSeries(Model): class Meta: ordering = [] name = CharField(...) class Email(Model): title = CharField(...) content = TextField(...) date = DateTimeField(...) series = ForeignKey(EmailSeries) Would it be possible to order EmailSeries by the date field of the Emails that have it as series? For example when viewing EmailSeries objects in django's admin I would like to see them ordered by the earliest date of all the emails belonging to each series. Is this possible? If so, what would I have to put into Meta.ordering for that to work? -
Django Formset MultiValueDictKey Error When Editing an Object
I am working with formsets for the first time and am receiving this error. It is interesting, because I have a 'Create' version of this view, and an 'Edit' version. The formset works just fine while Creating a new object, but when I try to Edit one I get this issue. I've seen online this having to do with the form.id but I don't think that's the case or I feel I wouldn't be able to use the create view successfully. Any thoughts on how I could try to resolve this? The error message highlights the line manifests = form2.save(commit=False) views.py def EditProformaView(request, pk): ManifestForm= modelformset_factory(ProformaManifest, fields =('ProductCode', 'DescriptionOfGoods', 'UnitQty', 'Type','Amount', 'Price')) item = get_object_or_404(Proforma, pk=pk) if request.method == "POST": form = ProformaForm(request.POST, instance=item) form2 = ManifestForm(request.POST) if form.is_valid(): new_proforma = form.save() manifests = form2.save(commit=False) #this is the line that creates the error for manifest in manifests: manifest.proforma = new_proforma manifest.save() data = form.cleaned_data #get the data from the form manifestData = form2.cleaned_data context = { 'data': data, 'manifestData': manifestData, } pdf = render_to_pdf('proforma_preview.html', context) ... messages.success(request, "Success: Proforma Has Been Created!") return redirect('HomeView') else: ... else: form = ProformaForm(instance=item) qs = ProformaManifest.objects.filter(proforma=pk) form2 = ManifestForm(queryset = qs) context = … -
How to make create() method of model's manager return a model object
I have a model User() for which I have created a custom manager class UserManager(). In UserManager() I have created a method create_user() which stores the information in database for model User(). Model User() class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=False, null=False) last_name = models.CharField(max_length=255, blank=False, null=False) profile_picture = models.ImageField(upload_to='profile_pictures/', max_length=None, null=True, blank=True) is_active = models.BooleanField(default=True) objects = UserManager() USERNAME_FIELD = 'email' Manager UserManager() class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, password,profile_picture=None): if not email: raise ValueError('Users must have an email address.') user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, profile_picture = profile_picture, ) user.set_password(password) user.save(using=self._db) # return model instance. It returns email address of the newly created user. return user I want create_user() to return id as a User Object. In the current scenario it returns email of the user. I am expecting create_user() method to return something like this - <User: User object (2)>. -
How to use pdf.js with django? or other way to embed pdf files in django? I want a non-javascript solution
I want to embed the pdf files in the html page, I could not find a reliable way around. How can I use pdf.js with Django or is there a library for django to do that? Particularly how to use it via CDN? Do I have to use node.js to run this?(i hope not) -
how to get selected choice from charfield and use it to make able another charfield in Django?
models.py: class Ligne(models.Model): Num_ligne = models.DecimalField(max_digits=8, decimal_places=0, null=True) CIN_ab = models.DecimalField(max_digits=8, decimal_places=0, null=True) FIXE='fx' MOBILE='mob' ligne_types = [ (FIXE, 'Fixe'), (MOBILE, 'Mobile'), ] Type = models.CharField(max_length=100,choices=ligne_types, null=True) forms.py: class Ligne_form(forms.ModelForm): Reseau=forms.CharField(required=False,disabled=True) Localisation=forms.CharField(required=False,disabled=True) class Meta: model = Ligne fields= [ 'Num_ligne', 'CIN_ab', 'Type' ] -
Django orm raw query with joins
i get this error when trying to execute my query: 'int' object is not iterable jobs = Job.objects.select_related("company").raw(""" select * from jobs_job left join jobs_job_position on jobs_job.id = jobs_job_position.job_id left join categories_position on categories_position.id = jobs_job_position.position_id left join categories_position_parent_cat on categories_position_parent_cat.position_id = categories_position.id left join categories_industry on categories_industry.id = categories_position_parent_cat.industry_id where categories_industry.id=12 limit 5 """) for job in jobs: print(job) In the for job in jobs line. I tried a simpler query: jobs = Job.objects.select_related("company").raw("select * from jobs_job limit 5") And that works fine. Is something wrong with joins and django orm or did I maybe write it in a bad way? The raw SQL query is working fine as well -
Django RecursionError: maximum recursion depth exceeded in comparison
I have seen many such errors but none of them matched what i am searching so kindly help me to understand where am i making mistake in saving signals in django. I know that save method is running infinity time but how do i stop in my code as I am beginner not able to understand what or where exactly i should be making changes. from django.db import models import random import os from .utils import unique_slug_generator from django.db.models.signals import pre_save, post_save class ProductQuerySet(models.query.QuerySet): def active(self): return self.filter(active=True) def featured(self): return self.filter(featured=True, active=True) class ProductManager(models.Manager): def get_queryset(self): return ProductQuerySet(self.model, using=self._db) def all(self): return self.get_queryset().active() def features(self): return self.get_queryset().featured() def get_by_id(self, id): qs=self.get_queryset().filter(id=id) if qs.count() ==1: return qs.first() return None # Create your models here. class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) image = models.ImageField(upload_to='products/', null=True, blank=True) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) objects=ProductManager() def __str__(self): return self.title def __unicode__(self): return self.title def product_pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(product_pre_save_receiver, sender=Product) This is may model.py -
Django Signal dispatch after related fields is updated
I have 2 models class Mapping(Model): title = models.CharField(max_length=22) class Query(Model): field = models.CharField(max_length=22) type = models.CharField(max_length=10, choices=(('=', 'Equals', ('in', 'Contains'))) value = models.CharField(max_length=256) mapping = models.ForeignKey(Mapping, null=True, blank=True, related_name='queries') So a mapping can have Multiple Queries. I need to do some operation to match Employees (a seperate model) who map to a Mapping after it is created, So i tried to use Signals @receiver(post_save, sender=Mapping) def do_something(instance, created, **kwargs): print("SIGNAL Received !!") print(instance.queries) # Gives None The problem here is that the signal is dispatched before Query objects are creted and i get None when trying to access instance.queries I cannot use the m2m_changed as this is not a ManyToManyField. I also thought of changing the signal sender to Query Model instead of Mapping Model but it wont work as I need to map employees to mapping only if they satisfiy all the queries of a Mapping for which i need to run the task on Mapping Object rather than Query. Please suggest any possible solutions. -
Orders Template not displaying data
For some reason while trying to display my order details in the user.html nothing appears on the website. All the base.html data appears, all thats missing is the order information. I'm not sure what is causing this problem as all my files seem to be linked correctly. Is there anything that I need to add? All help greatly appreciated! models.py - users from django.db import models from django.contrib.auth.models import User from fuisce.models import Product from django.db.models.signals import post_save class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' models.py - orders from django.db import models # Create your models here. from carts.models import Cart from users.models import Profile STATUS_CHOICES =( ("Started", "Started"), ("Abandoned", "Abandoned"), ("Finished", "Finished"), ) class Order(models.Model): user = models.ForeignKey('users.Profile', null=True, blank=True, on_delete=models.CASCADE) order_id = models.CharField(max_length=120, default='ABC', unique=True) cart = models.ForeignKey('carts.Cart', on_delete=models.CASCADE) status = models.CharField(max_length=120, choices=STATUS_CHOICES, default="Started") sub_total = models.DecimalField(default=10.99, max_digits=1000, decimal_places=2) tax_total = models.DecimalField(default=10.99, max_digits=1000, decimal_places=2) final_total = models.DecimalField(default=10.99, max_digits=1000, decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __string__(self): return self.order_id urls.py from django.urls import path from . import views from carts import views as cart_views from orders import views as order_views urlpatterns = [ path('', views.home, name='fuisce-home'), path('subscription/', views.subscription, … -
Pass password in a hash table Django
I am pretty new in Django. I built a website where you can create a user and share posts. My question is how can I pass the password in a hash table when the user registers to the website instead of plain text? I have tried to use make_password but when I was monitoring the protocol on Wireshark I saw the password (I am using the Django built-in User module): Wireshark -
Adding placeholder in django forms
I have a extended form from usercreation form in django , I want to add placeholder to email and password . forms.py class ExtendedUserCreationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ['email','password1','password2'] def save(self, commit=True): user = super().save(commit=False) user.username = user.email user.email = self.cleaned_data['email'] if commit: user.save() return user These is the forms.py where extended form with help of UserCreationform in django , How do i add placeholder to email and password fields. -
Pandas dataframe not acting as expected once deployed to heroku (Django project)
I have created a program which does data entry and returns a pandas table (the info is saved in a list, called JOB_INFO, at the top of the views.py file - I will attach this below) with some results which can be downloaded. I also have the table rendering on the html page that has the data entry form - the table renders below the form and updates(appends) with each user input(form submit). This is works perfectly in development on my local machine, but when it's been successfully deployed to heroku, it starts acting up and not behaving as expected. Examples include: Not updating the table - the form seems to submit but the table doesn't update. If I keep trying, it suddenly works. But then I'll try another and the previous one disappears and only the latest one will show in the table. It just seems so random. Not emptying the list - I have a button to clear the table but that doesn't work either. If I click the button a bunch of time it might work suddenly. But then randomly some information will show up in the table again that I thought was cleared! Info in downloaded … -
User Prefetch queryset annotated value outside prefetch related annotate
I have 3 models like below: class Customer(models.Model): customer_name = models.CharField(max_length=100) customer_phone = models.CharField(unique=True, max_length=11) customer_address = models.TextField(max_length=200, null=True) objects = CustomerManger() class Order(models.Model): customer = models.ForeignKey(Customer, related_name='order_customer', on_delete=models.CASCADE) ordered_date = models.DateTimeField(auto_now_add=True) is_paid = models.BooleanField(default=False) paid_total = models.FloatField(default=0) objects = OrderManager() class OrderedItem(models.Model): product = models.ForeignKey(ProductVariant, on_delete=models.CASCADE) price_per_product = models.FloatField(default=0.0) discount_percent = models.IntegerField(default=0) quantity = models.IntegerField(default=0) order = models.ForeignKey(Order, related_name='ordered_items', on_delete=models.CASCADE) I need all customers with extra calculations like total purchase items and the total dues. So, My query looks like this: data = self.model.objects.prefetch_related( Prefetch( 'order_customer', queryset=Order.objects.prefetch_related('ordered_items').annotate( due=Case( When(is_paid=False, then=Sum(F('ordered_items__quantity') * F( 'ordered_items__price_per_product') * (Value(1) - (F('ordered_items__discount_percent') / 100.00))) - F( 'paid_total')), default=Value(0), output_field=FloatField() ) ), to_attr='order' ) ).annotate(total_due=Sum(F('order_customer__due'))) I need the data like this: [ customer: { customer_name, customer_id, total_due, total_purchased_item } ] Here I count the due for per order inside Prefetch queryset and put the value in due. But outside the prefetch annotation, I can't access the value due. But normal annotated values can be accessed in chain annotate. It gives me an error "Unsupported lookup 'due' for AutoField or join on the field not permitted." I can't find out the problem solution. Is there any solution or any idea please share. Thanks in advance. -
Why can't I use ".update()" with a Django object?
I've been trying to update a Django object with: object_name.update(name="alfred") The thing is that when I get the object name this way: object_name = myobject.objects.get(id=object_id) the method update won't work. But when I get the object this way: object_name = myobject.objects.filter(id=object_id) it will work Why does this happen? Is it because the last object is a queryset? Is there anyway to use .update with a django object? thank you! -
Can not import multiplie statements in Django URL Page
In my Django Project, I have a Main URL Page(in Project File) to this, When I try to import views from two different Django apps then only one Import statement is activated and another one shows an error "Unused import statement". But actually I need both import statements. Because I have two views these have come from two different apps. So how can I import multiple views from different apps -
Django forms.ModelChoiceField queryset problem with models.manager
I am having trouble making a ModelChoiceField queryset in a ModelForm. The related model.objects manager has been overridden to filter the results in order to get only instances created by the actual user. Here are my models : class Bloc(ModelPrive): TYPE_BLOC = ( ('pleinchamps', 'plein champs'), ('tunnel', 'tunnel'), ('pepiniere', 'pépinière'), ('autre', 'autre'), ) nb_planche = models.IntegerField(null=True) caracteristique = models.CharField(max_length=200, null= True, blank=True) geom = models.PolygonField(srid=4326) type_bloc = models.CharField(max_length=200, blank=True, choices=TYPE_BLOC) nom = models.CharField(max_length=200, null=True, unique= True) class ModelPrive(models.Model): created_by = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, editable=False) class Meta: abstract = True objects = ModelPriveManager() class ModelPriveManager(models.Manager): def get_queryset(self): user = get_current_user() return super().get_queryset().filter(created_by=user) In my manager the get_current_user() returns the actual user that has been intercepted by a custom middleware. Here is my form : class BlocFormList(ModelForm): choix_bloc = forms.ModelChoiceField(queryset = Bloc.objects.all().order_by('nom'), required=True) class Meta: model = Bloc fields = ['choix_bloc'] Here is my view : def planification(request): form_bloc = BlocFormList() if request.method == 'POST': # some other code return render(request, 'planification.html', locals()) The problem is, when I do a Bloc.objects.all() in views I get the expected answer (Bloc.objects.filter(created_by=user)) but when it is done inside the queryset of the modelform, it returns nothing (as if there were no active user). After … -
Error during template rendering django (maximum recursion depth exceeded)
I have a base.html under templates/project1 directory which is extended from home/about/blog.html pages. In base.html, i separated header section on separate file named header.html with the following code. {% include "project1/header.html" %} The code in header.html is as follow: {% extends "project1/base.html" %} <header> <nav> <ul id="navigation"> <li><a href="{% url 'nata-about' %}">About Us</a></li> <li><a href="{% url 'nata-blog' %}">Blog</a></li> {% if user.is_authenticated %} <li><a href="{% url 'profile' %}">&nbsp; Profile</a></li> <li><a href="{% url 'logout' %}">&nbsp; Logout</a></li> {% else %} <li><a href="{% url 'login' %}"> &nbsp; Login</a></li> <li><a href="{% url 'register' %}"> &nbsp; Register</a></li> {% endif %} </span> </ul> </nav> </header> When i run the program, it displays an error as follow; Error during template rendering In template D:\pypro\nata\nata_App\templates\nata\header.html, error at line 7 maximum recursion depth exceeded which means it is showing error on below line: {% if user.is_authenticated %} -
Django Server does not start When using keep.alive()
I am using realtime stock price to get real time data using SDK. i successfully got data from this SDK but other django services not working like web page and API. below image show process. But when i remove client.keep_alive() working fine but after some time channel closed.