Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImageField upload_to attribute not calling a function that it's supposed to call
I'm having a very strange error. I have the following model in my models.py: def get_upload_path_profile_picture(instance, filename): extension = filename.split('.')[-1] folder_name = instance.name folder_name = folder_name.replace(" ", "-") return "employers/{0}/profile_picture.{1}".format(folder_name, extension) class Employer(models.Model): # user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) name = models.CharField(max_length=100, unique=True) # location = models.CharField(max_length=MAXIMUM_LOCATION_LENGTH, choices=COUNTRY_CITY_CHOICES, blank=True) short_bio = models.TextField(blank=True, null=True) website = models.URLField(blank=True) profile_picture = models.ImageField(upload_to=get_upload_path_profile_picture, blank=True, null=True) admin_approved = models.BooleanField(default=False) def __str__(self): return self.name The code above works. However, when I change the get_upload_path_profile_picture function to: def get_upload_path_profile_picture(instance, filename): print("Here in the get_upload_path_profile_picture function") extension = filename.split('.')[-1] employer_name = instance.name employer_name = folder_name.replace(" ", "-") to_return = "employers/" + str(employer_name) + "_profile_picture." + str(extension) print("to_return") print(to_return) return to_return The line Here in the get_upload_path_profile_picture function never gets printed. I changed nothing in the view that handles this model. Why does this happen? What am I doing wrong? -
When pausing a video, how to get the current frame as a number?
I am struggling with a problem. I am rendering a video with video.js and this is awesome. But I want to get the current frame number when I pause the video or if I click on a button, doesn't really matter. It is about getting the frame number of the exact moment from the video when it is paused or clicked. I tried the normal method (time already played * fps) but this gives a number with a lot of decimals. So this is no option because it gives different numbers with the exact same frame. Does anyone have a clue? I am using Django frame work to te get the video from the database to html. -
django AUTH_USER_MODEL error while deploying to heroku
I am deploying my project on heroku. When i got this error: $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 178, in get_model return self.models[model_name.lower()] KeyError: 'customuser' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/init.py", line 157, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 211, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 181, in get_model "App '%s' doesn't have a '%s' model." % (self.label, model_name)) LookupError: App 'stock' doesn't have a 'CustomUser' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/init.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/init.py", line 377, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/init.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/app/.heroku/python/lib/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, … -
I get an Api error from django back because of wrong date format?
//i have a django backend with sql database, with a date field //date format in the sql database 2020-12-10 13:10:20" //my kotlin code for parsing the date var formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd H:mm") val date = LocalDateTime.parse("2020-10-10 10:30", formatter) //the date field will be passed in the post request. //I get a 400 respons back, without the date field the post call is working fine ! //So i need to know how to parse the date to the right format which sql will accept. //Strange thing is that if i change the datefield with a put request it works just fine with the datefield. So i can change the field with a put request and the same code as posted above. But making a new date field with a post request is not working. -
Password Resetting view displays the django framework template
Password Resetting view displays the Django framework template instead of my HTML template. Even after adding template name in my urls.py, I still don't get any improvement urls.py from django.urls import path from .views import UserRegisterView, AddProductView, CategoryView, UserEditView, PasswordsChangeView from django.contrib.auth import views as auth_views from . import views from .views import * app_name = 'members' urlpatterns = [ # path('signup/', UserRegisterView.as_view(), name='signup'), # path('account/', UserEditView.as_view(), name='edit_account'), path('account/', views.edit, name='edit_account'), path('signup/', views.signup, name='signup'), path('activate/<slug:uidb64>/<slug:token>/', views.activate, name='activate'), # path('password/', auth_views.PasswordChangeView.as_view(template_name='registration/change_password.html')), path('password/', PasswordsChangeView.as_view(template_name='registration/change_password.html'), name='password'), path('add_product/', AddProductView.as_view(), name='add_product'), path('add_category/', CategoryView.as_view(), name='add_category'), path('password_reset/', auth_views.PasswordResetView.as_view(template_name='registration/password_reset.html'), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='registration/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='registration/password_reset_confirm.html'), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html'), name='password_reset_complete'), ] Tho, It only works for this path('password_reset/', auth_views.PasswordResetView.as_view(template_name='registration/password_reset.html'), name='password_reset'), Thanks for your help,:) -
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" %} …