Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
wagtail links direct only to EN language
I am struggling with that issue already few days and can't find any solution or what is the problem. after adding the localization to the app all the links in the main "homepage" (i used bakerydemo https://github.com/wagtail/bakerydemo) all are directing only to the english pages. https://i.imgur.com/EkTvRg3.png my settings USE_TZ = True USE_I18N = True USE_L10N = True LANGUAGE_CODE = 'he' from django.utils.translation import gettext_lazy as _ WAGTAIL_I18N_ENABLED = True LANGUAGES = WAGTAIL_CONTENT_LANGUAGES = [ ("he", _("Hebrew")), ("en", _("English")), ("ru", _("Russian")), ] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale/'), ) on apps "wagtail_localize", #'wagtail.locales', "wagtail_localize.locales", # This replaces "wagtail.locales" didn't make any other changes on the files. I have tried to remove WAGTAIL_I18N_ENABLED = True to handle the logic by myself but then there is an error: Environment: Request Method: GET Request URL: http://localhost:8001/he/blog/blog/ Django Version: 3.2.11 Python Version: 3.9.7 Installed Applications: ['main.apps.MainConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'cms', 'cms.base',` 'cms.blog', 'cms.breads', 'cms.locations', 'cms.search', 'wagtail.contrib.search_promotions', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.api.v2', 'wagtail.contrib.modeladmin', 'wagtail.contrib.routable_page', 'wagtail.core', 'wagtail_localize', 'wagtail_localize.locales', 'wagtail.admin', 'rest_framework', 'modelcluster', 'taggit', 'wagtailfontawesome'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware'] Template error: In template C:\Users\beit\Desktop\NEWSITE\cms\templates\base.html, error at line 0 'NoneType' object has no attribute … -
Django NoReverseMatch / Reverse for 'your-url' with arguments '('',) , When Used DeleteView
Im Confused, Why The object cannot callable?. But when im used {% for listUsulan in listUsulanPenelitian %}. it should works but render 3 views like this. i just want render one modal pop up not three, by id. But when i dont used {% for ..}. its not working. Any Idea ? views.py class UserUsulanPenelitianDeleteView(LoginRequiredMixin, DeleteView): login_url = '/authentication' redirect_field_name = 'redirect_to' model = UserUsulan context_object_name = 'listUsulanPenelitian' template = 'dashboard/usulan-penelitian.html' def get_success_url(self): return reverse('dashboard:usulan-penelitian') urls app_name = 'dashboard' urlpatterns = [ path('', views.UserDashboardTemplateView.as_view(), name='index'), path('profil/', views.UserProfilUpdateView.as_view(), name='profil'), path('usulan-penelitian/', views.UserUsulanPenelitianCreateAndListView.as_view(), name='usulan- penelitian'), path('usulan-penelitian/view/<int:pk>', views.UserUsulanPenelitianDetailView.as_view(), name='usulan-penelitian- detail'), path('usulan-penelitian/edit/<int:pk>', views.UserUsulanPenelitianUpdateView.as_view(), name='usulan-penelitian- edit'), path('usulan-penelitian/delete/<int:pk>', views.UserUsulanPenelitianDeleteView.as_view(), name='usulan-penelitian- delete') ] .html <form action="{% url 'dashboard:usulan-penelitian-delete' listUsulanPenelitian.id %}" method="post"> {%csrf_token%} <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Hapus Usulan Penelitian ?</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body">Judul : {{listUsulanPenelitian.judul_penelitian}}</div> <div class="modal-footer"> <button class="btn btn-secondary" type="button" data-dismiss="modal">Batal</button> <button class="form-submit btn btn-danger" id="submitButton" type="submit">Hapus</button> </div> </div> </form> Traceback <QuerySet [<UserUsulan: Predictions for COVID-19 with deep learning models of LSTM, GRU and Bi-LSTM>, <UserUsulan: Deep Learning for solar power forecasting—An approach using AutoEncoder and LSTM Neural Networks>, <UserUsulan: Deep Learning for solar power forecasting—An approach using AutoEncoder and LSTM Neural Networks>]> C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site- packages\django\views\generic\list.py:86: UnorderedObjectListWarning: Pagination … -
django app runs locally but csrf forbidden on heroku
My app runs fine at heroku local but after deployed to heroku, every time i try to login/register/login as admin, it returns this: i have tried to put @csrf_exempt on profile views what could I do? -
Django not exporting querysets comma separated properly (csv)
I am trying to create CSV output from one object and I followed the official documentation, however, the output is not as expected. What I've tried: views.py: def export_csv(request): if request.method == 'POST': project_id = request.POST['project_id'] project = Project.objects.filter(pk=project_id).values() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="export.csv"' writer = csv.writer(response) writer.writerow(project) return response return redirect(index) Current output: "{'id': 4, 'project_code': '123456789', 'country': 'Norway', 'note': 'Lorem Ipsum'}" Desired output: "id","project_code","country","note" "4","123456789","Norway","Lorem Ipsum" How could I format the output to look like the desired one? -
Updated Django User model with profile now cant log in new users
I have updated the user model fields with user profile fields and now I can not seem to log in new users. I am using Djoser to handle these actions. A new user can sign up which updates the user object but I keep getting non_field_errors: Unable to log in with provided credentials. I have tried the following in settings.py to no avail: DJOSER = { 'LOGIN_FIELD': 'username', 'SERIALIZERS': { 'user_create': 'profiles.serializers.UserSerializer', 'user': 'profiles.serializers.UserSerializer' } } AUTH_USER_MODEL = 'profiles.Profile' Models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, blank=True) occupation = models.CharField(max_length=100, blank=True) residence = models.CharField(max_length=100, blank=True, null=True) email = models.CharField(max_length=100, blank=True, null=True) active_id = models.IntegerField(default=0) avatar = models.ImageField(null=True, blank=True, upload_to ='uploads/profile_pics',default='uploads/default.jpg') def __str__(self): return self.user.username def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.avatar.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.avatar.path) Serializers.py: class ProfileSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(read_only=True) avatar = serializers.ImageField(read_only=True) class Meta: model = Profile fields = "__all__" class ProfileAvatarSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ("avatar", ) class ProfileStatusSerializer(serializers.ModelSerializer): user_profile = serializers.StringRelatedField(read_only=True) class Meta: model = ProfileStatus fields = "__all__" class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ('profile', 'username', 'password') def update(self, instance, … -
Django queryset breaks send
from django.db.models.query_utils import Q class MessageForm(forms.ModelForm): subject = forms.CharField(max_length=100, required=False, help_text='Optional.') text = forms.CharField(max_length=4096, required=True, help_text='Required.') class Meta: model = Messages fields = ('receiver','subject','text',) def __init__(self, user=None, *args, **kwargs): user = kwargs.pop('sender', None) print(user) super().__init__(*args, **kwargs) if user: profile = Profile.objects.get(username=user) print(profile) if profile.is_staff: self.fields['receiver'].queryset = Profile.objects.filter(Q(is_active=True)) elif profile.verified !='': self.fields['receiver'].queryset = Profile.objects.filter(Q(is_active=True)) else: self.fields['receiver'].queryset = Profile.objects.filter(Q(is_active=True)) print(profile.is_staff) print((profile.verified !='')) print(profile.is_active) Will Display: user user True False True When I tried to switch my messageForm to display only certain querysets for the form my send function broke and started to receive None as the sender of that message. @require_http_methods(["POST"]) def send(request): sendMessageForm = MessageForm(request.POST or None,) print(sendMessageForm) if sendMessageForm.is_valid(): sendMessageFormUser = sendMessageForm.save(commit=False) sendMessageFormUser.sender = request.user sendMessageFormUser.save() return redirect('home') Will display: None <tr><th><label for="id_receiver">Receiver:</label></th><td><select name="receiver" required id="id_receiver"> <option value="" selected>---------</option> <option value="39">1</option> <option value="40">2</option> <option value="41">3</option> <option value="42">4</option> </select></td></tr> <tr><th><label for="id_subject">Subject:</label></th><td><input type="text" name="subject" maxlength="100" id="id_subject"><br><span class="helptext">Optional.</span></td></tr> <tr><th><label for="id_text">Text:</label></th><td><input type="text" name="text" maxlength="4096" required id="id_text"><br><span class="helptext">Required.</span></td></tr> -
type object 'Skills' has no attribute 'objects'
I am getting the following error "type object 'Skills' has no attribute 'objects'" while trying to run my Django project enter image description here enter image description here enter image description here enter image description here -
Falla en actualización de datos por campo m2m
Estoy intentando hacer una actualización en Django Rest Framework con la vista genérica RetrieveUpdateAPIView, envió la información al serializador, cuando voy a guardar la información de un campo relacionado m2m siento como si tomará el campo de una forma que estuviera creando y no actualizando, por lo que no he podido guardar la información. Me devuelve esto: { "category": [ { "gender": [ "Category with this Movie Genre already exists." ] }, { "gender": [ "Category with this Movie Genre already exists." ] } ] } con status 400 Bad Request Este es el código del las vistas (view) class MovieUpdateAPIView(RetrieveUpdateAPIView): permission_classes = authentication() serializer_class = MoviesSerializer def put(self, request, pk=None, *args, **kwargs): """ Update data of movie, Only super users can make updates """ instance = Movies.objects.filter(id=pk).first() data = request.data instance.score = data['score'] instance.public = data['public'] instance.logo = data['logo'] instance.movie_name = data['movie_name'] instance.description = data['description'] instance.release_year = data['release_year'] instance.film_director = data['film_director'] for category in data['category']: category_obj = Category.objects.get(gender=category['gender']) instance.category.add(category_obj) serializer = self.serializer_class(instance, data=data) if serializer.is_valid(): data = serializer.data instance.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Paso los datos al serializador porque el 'logo' es una imagen que se envía en Base64, entonces en el serializador esta la forma que … -
Django: How to hide Sites framework from Django Admin while using django-allauth?
Background I have a django server that uses django-allauth for handling authentication logic. I want to unregister Sites framework from django-admin, in other words, I do not want to see the Sites section inside django-admin: What I tried Normally, I would do one of the two things: Unplug django.contrib.sites from INSTALLED_APPS in settings.py Unregister Sites model from within one of my admin.py files like so: admin.site.unregister(Sites) The problem I tried doing both options above. Here is the error when I unplug Sites app from INSTALLED_APPS: ... File "C:\path-to-my-project\venv\lib\site-packages\allauth\utils.py", line 13, in <module> from django.contrib.sites.models import Site File "C:\path-to-my-project\venv\lib\site-packages\django\contrib\sites\models.py", line 78, in <module> class Site(models.Model): File "C:\path-to-my-project\venv\lib\site-packages\django\db\models\base.py", line 113, in __new__ raise RuntimeError( RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. django-allauth is clearly using it in line 13. Here is the error when I do admin.sites.unregister(Site): Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Program Files\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\path-to-my-project\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\path-to-my-project\venv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\path-to-my-project\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\path-to-my-project\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() … -
wagtail translation parent_url() 'NoneType' object has no attribute 'strip'
I am struggling with that issue already few days and can't find any solution or what is the problem. after adding the localization to the app all the links in the main "homepage" (i used bakerydemo https://github.com/wagtail/bakerydemo) all are directing only to the english pages. https://i.imgur.com/EkTvRg3.png my settings USE_TZ = True USE_I18N = True USE_L10N = True LANGUAGE_CODE = 'he' from django.utils.translation import gettext_lazy as _ WAGTAIL_I18N_ENABLED = True LANGUAGES = WAGTAIL_CONTENT_LANGUAGES = [ ("he", _("Hebrew")), ("en", _("English")), ("ru", _("Russian")), ] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale/'), ) on apps "wagtail_localize", #'wagtail.locales', "wagtail_localize.locales", # This replaces "wagtail.locales" didn't make any other changes on the files. I have tried to remove WAGTAIL_I18N_ENABLED = True to handle the logic by myself but then there is an error: Environment: Request Method: GET Request URL: http://localhost:8001/he/blog/blog/ Django Version: 3.2.11 Python Version: 3.9.7 Installed Applications: ['main.apps.MainConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'cms', 'cms.base',` 'cms.blog', 'cms.breads', 'cms.locations', 'cms.search', 'wagtail.contrib.search_promotions', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.api.v2', 'wagtail.contrib.modeladmin', 'wagtail.contrib.routable_page', 'wagtail.core', 'wagtail_localize', 'wagtail_localize.locales', 'wagtail.admin', 'rest_framework', 'modelcluster', 'taggit', 'wagtailfontawesome'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware'] Template error: In template C:\Users\beit\Desktop\NEWSITE\cms\templates\base.html, error at line 0 'NoneType' object has no attribute … -
How do I test that my Celery worker actually works in Django
(code at bottom) Context: I'm working on a Django project where I need to provide the user feedback on a task that takes 15-45 seconds. In comes Celery to the rescue! I can see that Celery is performing as expected when I celery -A tcommerce worker -l info & python manage.py runserver. Problem: I can't figure out how to run a celery worker in my tests. When I run python manage.py test, I get the following error: Traceback (most recent call last): File "/Users/pbrockman/coding/t1v/lib/python3.8/site-packages/django/test/utils.py", line 387, in inner return func(*args, **kwargs) File "/Users/pbrockman/coding/tcommerce/tcommerce/tests.py", line 58, in test_shared_celery_task self.assertEqual(result.get(), 6) File "/Users/pbrockman/coding/t1v/lib/python3.8/site-packages/celery/result.py", line 224, in get return self.backend.wait_for_pending( File "/Users/pbrockman/coding/t1v/lib/python3.8/site-packages/celery/backends/base.py", line 756, in wait_for_pending meta = self.wait_for( File "/Users/pbrockman/coding/t1v/lib/python3.8/site-packages/celery/backends/base.py", line 1087, in _is_disabled raise NotImplementedError(E_NO_BACKEND.strip()) NotImplementedError: No result backend is configured. Please see the documentation for more information. Attempted solution: I tried various combinations of @override_settings with CELERY_TASK_ALWAYS_EAGER=True, CELERY_TASK_EAGER_PROPOGATES=True, and BROKER_BACKEND='memory'. I tried both @app.task decorator and the @shared_task decorator. How do I see if celery is having the expected behavior in my tests? Code Celery Settings: my_project/celery.py import os from dotenv import load_dotenv load_dotenv() from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings') app = Celery('my_project-{os.environ.get("ENVIRONMENT")}', broker=os.environ.get('REDISCLOUD_URL'), include=['my_project.tasks']) from django.conf import settings app.autodiscover_tasks(lambda: … -
Heroku/Django - No default language could be detected for this app
I am trying to deploy a Django app via Heroku for the first time. When I run git push heroku master it returns this error: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: e6acd22b123b939729546f4f06f368a8855a4744 remote: ! remote: ! We have detected that you have triggered a build from source code with version e6acd22b123b939729546f4f06f368a8855a4744 remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku <branchname>:main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version remote: remote: Verifying deploy... remote: remote: ! Push rejected to vygrapp. remote: To https://git.heroku.com/vygrapp.git ! [remote rejected] master -> main (pre-receive hook declined) error: failed … -
how to pass extra parameter to django rest custom action inside the viewset?
@action(detail=True, methods=['get'], url_path='password-reset/<uid64>/<token>', url_name='password-reset-confirm') def password_reset(self, request, uid64, token): pass this is the url ( http://localhost:8000/user/2/password-reset/Mg/az44bk-48c221372ceaca98b4090a421131d5f3 ) I am trying to reach, but it keeps returning 404 page not found -
How to lazy paginate a bootstrap table with slow data
We have a scientific database with a number of fields that are Django "cached properties". These cached property fields are slow to retrieve. Rendering a table (decorated with bootstrap-table) with around a thousand results is annoying, but doable. However now that we're loading a lot more data into the database, rendering these tables ends up hitting the 90 second timeout. We have explored various options to speed things up, but most methods do not support cached properties, which is a non-starter. We're looking for a temporary solution short of taking the cached property speed issue (which is the root of the problem) head on. Our current idea was to paginate. However, it looks like it's impossible to do it without a major refactor in order to retain all of our current complex functionality. We would like to retain this bootstrap functionality: Column switching (show/hide columns) between page loads Column sorting such that it takes all data (on or off the current page) into account And we want to retain this complex Django functionality/implementation: Complex django templates that renders data on each row that spans multiple many-to-many table relationships using nested loops and custom tags that: Filtering of rows from related … -
How to detect faces with imutils?
I am currently creating a django face detection/recognition app to mark employee attendance, however I am facing some issues when capturing the camera feed and detecting the faces on the feed. The functions below within the view.py are to detect the employee face and capture 300 images of the logged in employee - Essentially the aim of this question is to resolve the face detection issue and the issue is specifically lying within face_aligned = fa.align(frame, gray_frame, face). views.py: def create_dataset(username): id = username if (os.path.exists('Recog_Data/Train_Data/{}/'.format(id)) == False): os.makedirs('Recog_Data/Train_Data/{}/'.format(id)) directory = 'Recog_Data/Train_Data/{}/'.format(id) # Detect face # Loading the HOG face detector and the shape predictpr for allignment print("[INFO] Loading the facial detector") detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor('Recog_Data/shape_predictor_68_face_landmarks.dat') # Add path to the shape predictor ######CHANGE TO RELATIVE PATH LATER fa = FaceAligner(predictor, desiredFaceWidth=256) # capture images from the webcam and process and detect the face # Initialize the video stream print("[INFO] Initializing Video stream") vs = VideoStream(src=0).start() # time.sleep(2.0) ####CHECK###### # Our identifier # We will put the id here and we will store the id with a face, so that later we can identify whose face it is # Our dataset naming counter sampleNum = 0 # Capturing … -
useEffect returns the whole HTML page
This React component is returning the HTML page in the blog object. if i add {blog} to the return it will return raw HTML, but won't take, {blog.title} for ie. import React, { useState, useEffect } from "react"; import axios from 'axios' import {Link} from 'react-router-dom' const BlogDetail = (props) => { const [blog, setBlog] = useState({}) useEffect( () => { const slug = props.match.params.id; const fetchData = async () => { try { const res = await axios.get(`http://localhost:8000/api/blog/${slug}`); setBlog(res.data); } catch (err) { } }; fetchData(); }, [props.match.params.id]); const createBlog = () => { return {__html: blog.body} } return ( <div className='container mt-3'> <h1 className='display-2'>{blog.title}</h1> <h2 className='text-muted mt-3'>{blog.category}</h2> <div className='mt-5 mb-5' dangerouslySetInnerHTML={createBlog()} /> <hr /> <p className='lead mb-5'> <Link to='/blog' className='font-weight-bold'>Back to Blog</Link> </p> </div> ) } -
How to I specify a generic form(ModelForm) for many Plugins in Django CMS?
I'm using Django 2.2 and Django CMS 3.7.1 I have a plugin defined like so: cms_plugins.py @plugin_pool.register_plugin class BackgroundImagePlugin(CMSPluginBase): """ Background Image """ name = "Background Image" model = models.GenericBackgroundImage form = admin.GenericPluginFormWithSettings render_template = "plugins/ofc/BackgroundImageFormBoxCta.html" I also have a generic ModelForm("GenericPluginFormWithSettings") that I'm creating. I'm passing this form to the plugin above. Here's that ModelForm Class: admin.py class GenericPluginFormWithSettings(ModelForm): class Meta: fields = '__all__' def __init__(self, *args, **kwargs): super(GenericPluginFormWithSettings, self).__init__(*args, **kwargs) raw_keys = list(self.fields.keys()) raw_keys.remove('top_margin') raw_keys.remove('bottom_margin') raw_keys.append('top_margin') raw_keys.append('bottom_margin') # raw_keys is in the right order here self.Meta.fields = raw_keys self.order_fields(raw_keys) The goal with this generic model form class is to always push two fields(top margin, and bottom margin) to the bottom of the order for whatever plugin they're used upon. This fails to order the fields in the order I need them to be in. The only thing that works is when I hard code the fields order like so: class GenericPluginFormWithSettings(ModelForm): class Meta: fields = ['image', 'header', 'top_margin', 'bottom_margin'] But obviously I can't hardcode them because I then I couldn't use this ModelForm Class with many different plugins with different other than those with image and header`. How can I implement a generic ModelForm that re-orders fields which … -
Django Token authentication problem accessing another account
I have made Account model, which is now custom user model in Django my app. Also, I have Token authentication, but I do not know how to refresh Token, and how frequently I have to change Token for user.. Also I have a problem, because a user after logging with token can access another account, by just changing id in url. How can I solve this problem. I thought about solution that I put id of user in Token, so when he access to some url I check if it is his id in url from Token. But I am not sure is this is good solution for Django, because I do not know how to add id in Token. Maybe Django has some cleverer solution. I am pretty new in Django, so... -
error on Django drf ModelSerializer update method
I have a very strange error, this is my serializer class class user_ser(ModelSerializer): class Meta: model = User fields = '__all__' depth = 1 whenever I send an API request to update user data, i got default values for is_staff and is_superuser in the image below I send only email and password example : look what I got :( this is the validated_data for the update method is : I did not add is_staff or anything else to the request body, so why is that happening. -
Adding flag based on date in django listview
I am looking to add an extra column based on two date columns. The column should indicate if the item overlaps a certain date. I have no idea how or where to get started. I am loading a simple model in a listview with 3 columns, name, startdatetime and enddatetime. The selected date is currently datetime.now() So basically i want to know what item is active right now. thanks in advance -
include text and variable in ValidationError
I am using this code on the model to check if users are uploading images that are too large code: def validate_image(image): file_size = image.file.size test = 'whoop' if file_size > settings.MAX_UPLOAD_SIZE: raise ValidationError("image too large") image = models.ImageField(default='default.jpg', upload_to=path_and_rename, validators=[validate_image]) however i want to include the name of the offending file if i use raise ValidationError(image) it displays the file name but if I try to include some text raise ValidationError(image, "is too large") it will only display whatever comes first either the variable or the string. How can i include both -
Accessing session variable based on variable in for loop django template
I have some products listed which can be in a cart, this cart is stored in a session variable dictionary for which the key is the product id and the value is some information about the quantity and stuff. I want to add the option to view (on the products page) how many of that product are in your cart. I know I can access session variables in a django template like this: {{ request.session.cart.2323.quantity }} Problem is, the key (2323 in this case) is a variable which depends on a for loop: {% for prod in products %} <p>{{ request.session.cart[prod.name].quantity }}</p> {% endfor %} But implementing it like that unfortunately is not possible. Is there any way in which this would be possible or would I have to change the way my cart works? -
Django queryset for user
models.py(shrunk to things that matter) class Messages(models.Model): sender = models.ForeignKey(Profile,related_name='sender',on_delete=models.CASCADE) receiver = models.ForeignKey(Profile,related_name='receiver',on_delete=models.CASCADE) forms.py class MessageForm(forms.ModelForm): subject = forms.CharField(max_length=100, required=False, help_text='Optional.') text = forms.CharField(max_length=4096, required=True, help_text='Required.') class Meta: model = Messages fields = ('receiver','subject','text',) I have a dropdown that shows all users that were made I would like to filter it based off some fields like is_active to showcase only users that are authenticated and more like this so I would like to override I think it's receiver queryset. def index(request): sendMessageForm = MessageForm() if is_staff: if is_active: else: What my current form displays. <select name="receiver" required="" id="id_receiver"> <option value="" selected="">---------</option> <option value="39">1</option> <option value="40">2</option> <option value="41">3</option> <option value="42">4</option> </select> -
Django migrate error: formisoformat argument must be string
I would really need help to understand this error I get in Django that suddenly appeared after I added a bunch of objects to a models.Model class. This error persists even when I comment out all the new objects that might have provoked the error. This error is a bunch of Tracebacks and at last it tells that there is a "TypeError: fromisoformat: argument must be str " in this line: return datetime.date.fromisoformat(value) in dateparse.py file. I've been looking for a solution for a few days now but can't seem to find any, I don't fully understand the functioning of django yet so it would be really great if anyone could tell me how to get through this. Thanks for your time. -
Django Ajax Reorder Not Updating the Field in Database
I'm building a list of students by each class in the grade. I have a folder full of profile pictures for students downloaded into my img folder and a column within my model that maps the details (name, class, age, etc.) to the image name. How do I tell my table to bring in the appropriate img for each student? Below I have my code working to use a single image as a constant (e.g. student1's picture shows up for everyone). list.html: <table class="table table-hover" id="table-ajax"> <thead class="thead-light"> <tr> {% comment %} <th></th> {% endcomment %} <th style="width: 50px; text-align: center;"></th> <th>{{ object_list|verbose_name:'field:name' }}</th> <th>{{ object_list|verbose_name:'field:hometown' }}</th> <th>{{ object_list|verbose_name:'field:birthday' }}</th> <th>{{ object_list|verbose_name:'field:race' }}</th> <th>{{ object_list|verbose_name:'field:rank' }}</th> <th style="width: 50px; text-align: center;">Pictures</th> <th style="width: 160px; text-align: center;">Actions</th> </tr> </thead> <tbody class="order" data-url="{% url 'cms:reorder' model_name %}"> {% include 'app/partials/pick_list_partial.html' %} </tbody> partial-list.html: {% for pick in object_list %} <tr id="{{ pick.pk }}"> <td><img src="{% static 'img/student1.jpg' %}" width="50" height="50"></td> <td><a href="{% url 'app:lead-list' pick.pk %}" title="Leads">{{ pick.name }}</a></td> <td>{{ pick.hometown }}</td> <td>{{ pick.birthday }}</td> <td>{{ pick.race }}</td> <td>{{ pick.rank }}</td> <td style="text-align: center;"> <a href="{% url 'app:file-list' pick.pk %}" class="btn btn-outline-success btn-sm border-0" title="Files"> <i class="fa fa-copy"></i></a></td> <td style="text-align: center;"> <a …