Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use data from GET request in get_intial() and get_form_kwargs() of FormVIew
I am trying to refactor my code to inherit FormView instead of View. The view I'm working with receives values in the GET request. I retrieve the values in the get_context_data method and pass them through different functions to end up with a set of variables that I can pass in the context. For the sake of example, this includes variables FOO and BAR. I need to initialise my form by passing variable FOO in the kwargs and additionally set my form field's initial value to BAR. I understand I should use the get_initial() and get_form_kwargs() methods to do this. I am just struggling with how to get FOO and BAR from the get_context_data method. I tried adding FOO and BAR to the context dictionary: context = super().get_context_data(**kwargs) context["FOO"] = foo context["BAR"] = bar return context And then calling it from the other methods: def get_initial(self): """ Get initial value for the form field """ initial = super(NameOfView, self).get_initial() context = self.get_context_data() initial_value = context["BAR"] initial.update({'name': inital_value}) return initial and the same for get_form_kwargs. But I get a RecursionError: maximum recursion depth exceeded while calling a Python object Any help understanding how I can acheive this will be appreciated -
get_for_model in Django ContentType
what is the benefit of get_for_model function when i can get it via type ? example: Book is model ContentType.objects.get_for_model(Book)---->ContentType:book -
Wagtail: Inserting links to images in rich text field
I have a need to insert links to images held in the CMS in rich text editor, similar to how documents are inserted. However, by default images are inserted as embeds and requires an extra step to choose a format. How I could override the "insert image" button in rich text editor to work similar to documents and insert images only as a link? In other words, the current document chooser provides the following database entry: "value": "<p><a id=\"1\" linktype=\"document\">Download pdf</a></p>" I would like to have something similar to images as well, for example: "value": "<p><a id=\"1\" linktype=\"image\">Download image</a></p>" Technically I don't care about the database representation so I'm also okay with a solution which only changes the API output to similar format as documents have, for example: <p><a href=\"/documents/1/document.pdf\">Download pdf</a></p> However, I still would like to get rid of the unnecessary step in CMS to choose image format. Any suggestions? -
django adding a request body manually
I want to manually create a request object including variables in a body. My attempt would be: from django.http import HttpRequest request = HttpRequest() request.method = 'POST' request.content_type = 'application/json' request.POST = {"var1": "abc", "var2": var2} However it seems like the dictionary is not included in the way I expect it. Any idea what I'm doing wrong? -
jQuery is not rendering properly datatable
i am Django user i want to render out my api data using jQuery. Api data is rendered but the datatable is not working properly. but when i render data in datatable using django template datatable working fine. i thing some class's of datatable maybe not working. i try harder but i don't know how can i debug this thing. can anybody know how can i render datatable properly in html using jQuery? it's jQuery Output Django Output <table id="approvedData"> <thead> <tr> <th>ID</th> <th>Story</th> <th>Created By</th> <th>Timestamp</th> <th>Priority</th> <th>Action</th> </tr> </thead> <tbody id="approvedList"> </tbody> </table> index.js function fetchData() { $.ajax({ type: 'GET', url: endpoint, success: function (data) { console.log(data) var html = ''; data.map(object => { let storyStatus = ('Story not finish'); let colorClassName = ("badge-danger"); if (object.story_status === "sf") { colorClassName = "badge-success"; storyStatus = "Story finish" } if (object.story_status === "fr") { colorClassName = "badge-success"; storyStatus = "Approved" } html += `<tr> <td> ` + object.id + `</td> <td><a href="#"> ` + object.title + `</a></td> <td> ` + object.author + `</td> <td> ` + moment(object.created_on).fromNow() + `</td> <td><span class="badge ${colorClassName} id="story-status">${storyStatus}</span></td> <td> <div class="table-btns"> <a href="${updateURL}update/${object.id}" class="table-btn table-btn--edit"> <i class="icon ion-ios-create"></i> </a> <a href="#" class="table-btn table-btn--delete"> <i class="icon … -
How to customise django User model for a multiuser system
I am working on a Django project that requires me to extend the default User model for different types of users. Let me explain with Uber. Uber has two different mobile apps: the normal app for everyone and another for its drivers. Let's assume I am a normal user with the normal app and I decide to sign up as a driver on the driver's app. I could sign up with the same email I used to sign up on the normal app and it would still work and I am very sure Uber still uses the same User table. This is what I am trying to achieve but it's been challenging. Here's what I have so far: # models.py class UserTypes(models.TextChoices): TYPE_1 = "Type 1", "Type 1" TYPE_2 = "Type 2", "Type 2" class SexTypes(models.TextChoices): MALE = "Male", "Male" FEMALE = "Female", "Female" class UserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("Users must have an email address!") user = self.model(id=id) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None): user = self.create_user( email, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin, TimeStampedModel): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email … -
django and instapy integration
I want to build a tool like hootsuide for my own stuff. As you know, Instagram only allows instagram partners to publish a content via api. I use instapy as a single python file but I've never used with django before. I'm having some troubles with integration. views.py : from django.shortcuts import render, redirect from instapy import InstaPy # Create your views here. def instapy_login(request): session = InstaPy(username='test', password='test') session.login() return redirect("/") However, I want to use this login credentials for next requests. For example : def fetch_followers(request): session = InstaPy(username='test', password='test') # I don't want to login again. session.login() # I don't want to login again. followers = session.grab_followers(username="test", amount="full") print(followers) return redirect("/") I don't want to login in every request. Any idea about fixing it? Thanks alot! -
"TypeError at / argument 1 must be str, not PosixPath" in django ecommerce website
I was building an eCommerce website using Django and Vue.Js. There was no issue while I was hosting the website in localhost. But when I deployed my website on Heroku an error is showing up "TypeError at / argument 1 must be str, not PosixPath". Mainly an error in the jinja template. code: {% for category in menu_categories %} .. statements .. {% endfor %} buckler-ecom.herokuapp.com The link to the deployed site -
Call view from within another view with modified request
I have a view_A in Django where I want to get data from another view_B. I can't just use the functions from B or modify B because it's something external that I import. So within view_A I would create a request object and pass it to view_B like that: from django.http import HttpRequest class view_A(APIView): def post(self, request): new_request = HttpRequest() new_request.method = 'POST' new_request.content_type = 'application/json' new_request.POST = {"var1": var1, "var2": var2} response = view_B(new_request) return(response) However it seems that I am not setting the body of the request correctly as it returns: {"var1":["This field is required."],"var2":["This field is required."]} Any idea where I messed up? -
best free library to create gantt chart with Django [closed]
What is the best free gantt chart javascript library that can be integrated with Django. Currently I am trying plotly.js but the runtime is slower when it fetches data from database. Also, I couldn't find dynamic change or resizing of progress bars smooth in Gantt Chart using plotly.js. I could use GoogleCharts but this needs license when used for commercial purpose. I am more intersted in Opensource libraries -
best free library to create gantt chart with Django [closed]
What is the best free gantt chart javascript library that can be integrated with Django. Currently I am trying plotly.js but the runtime is slower when it fetches data from database. Also, I couldn't find dynamic change or resizing of progress bars smooth in Gantt Chart using plotly.js. I could use GoogleCharts but this needs license when used for commercial purpose. I am more intersted in Opensource libraries -
"TemplateSyntaxError at / 'humanize' is not a registered tag library" in django
when I tried to run the server I got this error. I have added 'django.contrib.humanize' in my installed apps. and {% load humanize %} in my files. The error it shows : TemplateSyntaxError at / 'humanize' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache i18n l10n log static staticfiles tz -
Get Absolute Url keeps directing to one particular id
Good day, I have a Django project where I want to display an order list and detail. All seems to work perfectly but the link only links to one particular id ( for instance id 66). I have tried deleting the particular order id from the admin panel, thinking maybe the URL would just reset, but I get the URL id incremented, now it's no longer id 66 but 67. Pls how can I fix this? here are my codes: models.py class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) phone_number = models.CharField(max_length=20) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) braintree_id = models.CharField(max_length=150, blank=True) coupon = models.ForeignKey(Coupon, related_name='orders', null=True, blank=True, on_delete=models.SET_NULL) discount = models.IntegerField(default=0, validators=[ MinValueValidator(0), MaxValueValidator(100) ]) class Meta: ordering = ('-created',) def __str__(self): return self.first_name def get_absolute_url(self): return reverse('orders:orderdetail', args=[self.id]) views.py def order_list(request): orders = Order.objects.all() current_user = request.user success = Order.objects.filter(user=current_user.id).filter(paid=True) fail = Order.objects.filter(user=current_user.id).filter(paid=False) return render(request, 'orders/order/order_list.html', { 'success': success, 'fail': fail, 'current_user': current_user, 'orders':orders, }) def order_detail(request, order_id): order = get_object_or_404(Order, id=order_id) return render(request, 'orders/order/order_detail.html', {'order': order}) urls.py from django.urls import path from . import views app_name = 'orders' urlpatterns = … -
tags_set returns blank after post request (Django Rest Framework)
I am trying to create article with some tags from another model.But i am facing a problem where the post request in serializer returns blank class ArticleTagViewSerializer(serializers.ModelSerializer): class Meta: model = ArticleTags fields = ('id','tag') def create(self, validated_data): return ArticleTags.objects.create(**validated_data) class ArticleCreateSerializer(serializers.ModelSerializer): tags_set = ArticleTagViewSerializer(source='posttags',required=False,many=True) class Meta: model = Article fields = ('id','author','caption','tags_set',) def create(self, validated_data): return Article.objects.create(**validated_data) How can i solve the problem in a way that multiple tags are saved ? Note:Tags_set inputs are as List String in json -
what if you have many users in your website in django?
what if i have like 1 million users, where would i store all these users;can sqlite handle all of these users; can i use firebase, postegresql? how much mb does a user have in django? that's a lot of question!! -
Multiple items filter in Django
I'm having a trouble on how can I filter multiple data in django-filters or any solution you can suggest just to filter it by tags. From now on I'm only manage filter only one using django-filter, yet I have no idea what should I use in using tags or multiple data. Can somebody help me about this? filters.py from django.contrib.auth.models import User from .models import Person import django_filters class UserFilter(django_filters.FilterSet): class Meta: model = Person fields = ['province', 'municipality','barangay','classification','classification','category','type_payout','payroll_batch','batch_it','paid','paid_by' ] views.py django-filter dte_from = request.POST.get('dte_from', None) dte_to = request.POST.get('dte_to', None) user_list = Person.objects.filter(date_receive__range=[dte_from, dte_to]) bene = UserFilter(request.POST, queryset=user_list) -
Django pass form data from one function to another
I have following View. How can I pass one or more variables into the other add_to_cart function? Through **kwargs? I want to have the form data from classed based Product Detail View assigned to the add_to_cart function. The form data is in the post function. The variables I want to pass into add_to_cart function is following: aussenbreite = form.cleaned_data['aussenbreite'] aussenhöhe = form.cleaned_data['aussenhöhe'] If you cannot give me detailed instructions this would be ok. I just need to know how to pass variables from one function into another. And if this is possible from class based view into function based. class ProductDetailView(DetailView): model = Item template_name = 'shop/descriptions.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['aussenmass_form'] = AussenmassForm() return context def aussenmass_post(self, **kwargs): if request.method == "POST": aussenmass_form = AussenmassForm(request.POST or None) if aussenmass_form.is_valid(): aussenbreite = form.cleaned_data['aussenbreite'] aussenhöhe = form.cleaned_data['aussenhöhe'] data = { 'aussenbreite' : aussenbreite, 'aussenhöhe' : aussenhöhe, } return data else: aussenmass_form = AussenmassForm() return render(request, self.template_name, {'aussenmass_form': aussenmass_form}) And I want to pass the two variables from this def post into this function: def add_to_cart(request, slug, **kwargs): item = get_object_or_404(Item, slug=slug) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False, ) #check … -
Django query annotate with applied distinct on another field
assume I have a db table with following rows: some_key - price 1 | 100 1 | 100 2 | 150 2 | 150 3 | 100 3 | 100 I want to list users with their total expending according to orders table. but for whatever (stupid) reason each row may have been duplicated. so I should add distinct on "some_key" column and obviously this code bellow won't work. how could I annotate Sum of prices with distinct on "some_key" column query = User.objects.filter(<...>).annotate(price_sum=Sum("orders_set__price", distinct=True)) any suggestion? -
Embed image from eli5.explain_weights() into html in Django platform
I am working with Django to develop my website. I use eli5 library link to evaluate the feature important of machine learning model. The function eli5.explain_weights() is run in python file and it provides an explanation in form of PIL image. How do I export and present this image in HTML. Thanks -
Django form post not saving
I am making a Django application (for the first time in my life). As part of the application, a timetable needs to be implemented. Loading data (from the databse) into the timetable works fine: Timetable view The thing is that the data should be editable. So users need to be able to change the time or the yes/no parameter. I've created a POST handler in views.py, but when I press save, the page quickly reloads and the old values are back. What am I doing wrong? models.py class timeTable(models.Model): key = models.CharField(max_length=200, unique=True, null=True) value = models.CharField(max_length=200, null=True) def __str__(self): return self.key views.py @login_required(login_url='login') def timetable(request): timeTableFormset = modelformset_factory(timeTable, fields='__all__' ,extra=0) timetableform = timeTableFormset(queryset=timeTable.objects.all()) if request.method == 'POST': form = timeTableFormset(request.POST) if form.is_valid(): form.save() return render(request, 'VulnManager/timetable.html', {'timetableform': timetableform}) timetable.html: <form method="POST"> {% csrf_token %} <table id="tablePreview" class="table table-borderless table-hover"> <!--Table head--> <thead> <tr> <th></th> <th>Monday</th> <th>Tuesday</th> <th>Wednesday</th> <th>Thursday</th> <th>Friday</th> <th>Saturday</th> <th>Sunday</th> </tr> </thead> <!--Table head--> <!--Table body--> <tbody> <tr> <th scope="row">Scan?</th> {{ timetableform.management_form }} {% for timeTableValue in timetableform.forms %} {% if forloop.counter <= 7 %} <td><select class="form-control" id="{{ timeTableValue.key.value }}" disabled="true"> <option>{{ timeTableValue.value.value }}</option> <option> {% if timeTableValue.value.value == "true" %} false {% elif timeTableValue.value.value == "false" %} … -
Django admin, ImageField: choose image from uploaded
I have a pretty simple model: class Article (models.Model): title = models.CharField(max_length=120) content = RichTextUploadingField(blank=True, default='') logo = models.ImageField(default='media/images/default.jpg', upload_to='media/images') I can upload images from local PC to the server, but how can I choose from already uploaded images? In Django Admin when I press "choose file" button, the local file system window is opening. -
Django Form: Calling foreign key field attributes in template
In a template I want to call a class attributes of a foreign-key form field item.pid like shown below {%for item in form.item %} {{item.pid}} {% endfor %} My question is simple and the solution should be as well but I am stuck here for way too long now. I have tried formsets, inlineformsets, clean and so many more things which are in the documentation and here on SO. It's even not possible to call a class method of a form field. calling {{form.instance.item.pid}} should be the solution but I can't get it running. model.py class Event(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE, blank=True, null=True, default=0) item = models.ForeignKey(Item, on_delete=models.CASCADE, blank=True, null=True, default=0) #many more class Person(models.Model): person_number = models.IntegerField(null=True) name = models.CharField(max_length=200, null=True) surname = models.CharField(max_length=200, null=True) #many more class Item(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE, blank=True, null=True, default=0) pid = models.IntegerField(null=True) #many more def save(self, *args, **kwargs): self.pid = Person.objects.filter(surname=self.person.surname, name=self.person.name).values("person_number") super(Item, self).save(*args, **kwargs) views.py def event(request, event_id=None): if event_id: instance = get_object_or_404(Event, pk=event_id) else: instance = Event() form = EventForm(request.POST or None, instance=instance) if request.POST and form.is_valid(): form.save() return HttpResponseRedirect(reverse('cal:calendar')) context = { 'form': form, } return render(request, 'cal/event.html', context) forms.py class EventForm(ModelForm): class Meta: model = Event fields = … -
How to save continually the countdown number of days in the database in django?
I am developing an insurance car web app where the customer can come and block his insurance at any time if the car has a problem. I would like to count daily and save in the database the number of days remaining, and also if the customer blocks his insurance, that I can stop counting until he comes to activate it. At the moment, I can only save when the customer blocks or unblocks their insurance via the insurance contract modification function. Here is the update contract function: def ContratUpdate(request, id=None): context = {} detail = get_object_or_404(Contrat, id=id) contract = request.POST.get('numero_de_contrat') form = ContratAddFrom(request.POST or None, instance=detail) if form.is_valid(): instance = form.save(commit=False) instance.save() id = form.instance.id contrats=Contrat.objects.filter(numero_de_contrat=contract) for contrat in contrats: if contrat.statut_assurance =='Reprise': nb_Days = contrat.nombre_de_mois+contrat.created.day-date.today().day contrat.remainingdays=nb_Days contrats.update(remainingdays=nb_Days) elif contrat.statut_assurance=='Suspendre': nb_Days = contrat.remainingdays+contrat.created.day-contrat.modified.day contrat.remainingdays=nb_Days contrats.update(remainingdays=nb_Days) return redirect('assurance_auto:Contrat_Liste') else: form = ContratAddFrom(instance=detail) context["form"] = form return render(request, 'auto/UpdateContrat.html', context) And this is what I am trying to do in the contract model in order to solve my issue but it does not working: class Contrat(models.Model): Statut_contrat = ( ('Encours', 'Encours'), ('Suspendre', 'Suspendre'), ) # numero_de_contrat = shortuuid.uuid() numero_de_contrat = models.CharField(max_length=10, unique=True, null=False, blank=False) statut_assurance =models.CharField(max_length=15, choices=Statut_contrat) vehicule = models.ForeignKey(Vehicule, on_delete=models.CASCADE) … -
how to display dynamically generated image in django template stored in variable with image path in local folder
im trying to display image in template but ive tried every method and it fails. I have a function that takes a user input image and search for the closest match in the database that also has a set of images and gives the result with the closest match. The database of these images are all stored in folder in a local folder (C:\Users\Sairar\Dev\image\src\makeup\db_images). Once the result is generated the image is then stored in a variable eg "mimg". Now mimg is a vaariable that contains my resultant image. when i write mimg.show, it works and the image is displayed on the screen but the only problem is dsplaying it on the template which im unable to figure. -
Is there any way in django to get a string representation of a url full path
So I'm trying to send a url to an external website as a callback url for some process and I was wondering if there's anyway or function where maybe if I pass in the url name from urlpatterns and required args it would return the full path of the url as a string instead of hard coding it in. The url in urls.py looks something like this: app_name = example_app urlpatterns = [ ... '<int:example_id>/, views.my_function, name='some_name' ] And I want something like this just as a string: https://my_site_domain.com/example/1/ # 1 is the example_id