Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Looping through nested dictionary in Django template
My context dictionary for my Django template is something like the following: {'key1':'1', 'key2':'2', 'key3':'3', 'key4':{'key5':{'key6':'6', 'key7':'7', 'key8':'8'}}} I would like to iterate through the dictionary and print something like: some label = 6 some label = 7 some label = 8 How can I achieve this in my Django template? -
Index of row looping over django queryset
I used to convert a django query set to a pandas DataFrame before looping over its rows, but it's not efficient as I loose many properties of a query set. sample_qs = MyModel.objects.all() sample_df = pd.DataFrame(sample_qs) for index, row in sample_df.iterrows(): print(f"Processing row {index} of {sample_df.shape[0]}...") Is there a similar way to iterate over sample_qs without converting it to a pandas DataFrame and still have something similar to index? I know about iterator, but couldn't find anything similar to index: for q in sample_qs.iterator(): print(f"Processing {str(q)}...") -
Add field to the object in the view
I have step form for creating Course object, and inside this object i have tutor field and i want to add something like that Course.tutor.add(request.user) but i can't do that because i haven't any instance to do that class FormWizardView(SessionWizardView): template_name = 'courses/create_course.html' file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT,'courses')) form_list = (CourseForm1,CourseForm2,CourseForm3,CourseForm4) def done(self,form_list,form_dict,**kwargs): instance = Course() for form in form_list: for field, value in form.cleaned_data.items(): setattr(instance, field, value) instance.save() return redirect('courses:my_courses',username=self.request.user.username) -
dkjango ForeignKey that allows Null value
I have class Comment with ForeignKey to self - parent: parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True) I allowed null and blank enteries, but when i try to create a new comment without a parent, i have this log:ERREUR: une valeur NULL viole la contrainte NOT NULL de la colonne « parent_id » can someone help me to resolve this issue -
All mutations must define a mutate method in it - Django
in Django ghaphql in trying use create a new object. But mutation is giving this error - "All mutations must define a mutate method in it" -
How to give all users the ability to view a base data set. And allowing them to add their own data entries to view and share to users
Just a heads up, I am new to using web frameworks. My only experience so far comes from completing the VSCode, Django and Mozilla MDN tutorials. But I'm making my way through these along with my own project. I'm creating a web app that has an "official" database table that all website/app users can view. But, I want to be able to let them add their own data entries to the table, which only they can view and edit. And would be able to grant other users/friends access to their created data entries, to expand the total number of entries made available. Without making everyone using the site having to work out which data entries are the "official" and which are user created. Hopefully a better way of understanding what I'm planning So, what would be the best method for setting up user accounts to have access to the main database table and their own data set, which they can grant access for others to view? Would this mean creating a table for each user, and if so how can this be set up automatically upon account creation? I've read that creating a new table in the database can be … -
Django: Save session variable outside of view is not working
i'm creating my first django project and i'm trying to use session variables out of the view. Firstly i'm getting some data from a form. That works fine. """views.py""" request.session['points_to_victory'] = form.cleaned_data['points_to_victory'] request.session['player_amount'] = form.cleaned_data['player_amount'] request.session['double_out'] = form.cleaned_data['double_out'] request.session['players'] = players request.session['current_player'] = 0 request.session.save() form.process(request.session.session_key) print("Output after form.process: " + str(request.session.items())) But i'm calling a function in my form class and try to add there another entry to my session. The code in the form class is the following: """forms.py""" s = Session.objects.get(pk=session_key) session = s.get_decoded() session["game"] = 1 print("Output in form.prcocess: " + str(session.items())) s.save() The commando line output is: > Output in form.prcocess: dict_items([('points_to_victory', 301), ('player_amount', 1), ('double_out', True), ('players', ['Mustermann']), ('current_player', 0), ('game', 1)]) > Output after form.process: dict_items([('points_to_victory', 301), ('player_amount', 1), ('double_out', True), ('players', ['Mustermann']), ('current_player', 0)]) So the changes in the session dict are done but not saved. Is there any other way to save is? And can you explain why it is not working? -
AWS S3 Bucket Django Image Upload
DONE I am following this guide tho build AWS S3 Bucket in to my Django 3.0 project. I am doing everything as it is in the guide. When I add an image that successfully gets uploaded to the S3 bucket (based on AWS management view where I can see all the stored files) but it does not appear as an image only as a "typical image icon" on the website If I follow the just recently uploaded file's URL in the Google chrome inspector opening the images URL gives me the following message (IDs have been changed fro privacy purposes) ERROR This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>InvalidRequest</Code> <Message> The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256. </Message> <RequestId>862368GFHSD9776868676</RequestId> <HostId> KKjhghfg568fadfgdg768sdg69s8g0s8hsh70hs90h9f0/sdg898= </HostId> </Error> TRIED I have found the same question on aws forum but it has not been answered The solution probably has to to something with Access rights (I don't understand this answer https://stackoverflow.com/a/21614550/10270590 ) "use AWS4-HMAC-SHA256" -
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