Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Auto creating profile for two types of users in django
I have a user model and two models Employee and Manager which inherits from the user model. I want to create an employee and manager whenever i register a new user. Should i use a boolean field to ask if it is a employee or a manager when creating a user? or is there another way? btw i am using django signals models.py class User(AbstractUser): email = models.EmailField(_('email address'), blank=True, unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username", ] class Employee(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) year_joined = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) department = models.IntegerField(null=True, blank=True) def __str__(self): return f'{self.user.username}' def enrolledYear(self): return self.year_joined.strftime("%Y") class Manager(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) designation = models.CharField(null=True, blank=True, max_length=100) departments = models.IntegerField(null=True, blank=True) def __str__(self): return f'{self.user.username}' -
How to install Google Recaptcha v3 with Django CMS and Aldrym Forms
I am trying to get ReCaptcha v3 working for an aldryn form in django / djangocms. Instead of the ReCaptcha riddle all I get is a "Recaptchafieldplugin 1*" on the site: What am I missing? Am I misunderstanding how this "invisible ReCAPTCHA" should work? Should there not be a captcha riddle to solve? There is a working sample project running. To get recaptcha up and runnning here is what I did so far. I followed the readme. pip install aldryn-forms-recaptcha-plugin adjusted settings.py accordingly set RECAPTCHA_SCORE_THRESHOLD = 1 for testing (1 = always activate recaptcha) set the recaptcha keys in the .env file python manage.py migrate added to the bottom of the base.html template Here is the settings.py: import os # isort:skip import environ env = environ.Env() env.read_env(env.str('ENV_PATH', 'recaptchatest/.env')) gettext = lambda s: s DATA_DIR = os.path.dirname(os.path.dirname(__file__)) """ Django settings for recaptchatest project. Generated by 'django-admin startproject' using Django 3.1.14. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY … -
Update function data is not saving in django
views.py class ProductsDetailView(DetailView): template_name = "productsdetail.html" queryset = Products.objects.all() context_object_name = 'products' model = Products serializer_class = Productserialize def productupdate(request,id): prod = Products.objects.get(id=id) if request.method == "POST": if len(request.FILES) != 0: if len(prod.image) > 0: os.remove(prod.image.path) prod.image = request.FILES['image'] prod.title = request.POST.get('title') prod.description = request.POST.get('description') prod.save() return redirect('productsdetail') return render(request,'productsupdate.html',{'prod':prod}) detail.html <form> Title:- {{products.title }} <br><br> Description:- {{ products.description}}<br><br> {% if products.image %} Image :- <img src="{{products.image.url}}" alt="image"><br><br> {% endif %} <button><a href="/update/{{ products.id}}">Edit</a></button> </form> update.html <form method="post" action="/update/{{prod.id}}" enctype="multipart/form-data"> {% csrf_token %} <table> <tr> <td>Title:<br> <input type="text" name="title" id="title" value="{{ prod.title }}"></td> <br> </tr> <tr> <td>Description:<br> <textarea name="description" id="description" value="{{ prod.description }}">Description</textarea></td> <br> </tr> <tr> {% if prod.image %} <td>Image:<br> <input type="file" name="image" id="image" value="{{prod.image.url}}"></td> {% endif %} <br> </tr> <tr> <td><button type="submit" id="update">Update</button></td> </tr> </table> </form> When i click edit button in detail page it shows update form but when Iam trying to update data is not saving I don't know what is the issue I have given views,detail html and update html code Please help me to solve this Thanks in advance -
Serve Django static files in kubernetes
I am trying to host a Django project inside Kubernetes. But now am facing an issue to serve static files of Django. So I researched about it. In my researches found that storage objects are a better option like S3. Can I serve static files without using S3? I trying to serve using the Nginx server. I tried in different ways but I didn't get a solution. Here is my deployment YAML. And I attached a volume for static files and media files. Can I possible serve static files and media files from that volume using Nginx deployment.yml apiVersion: apps/v1 kind: Deployment metadata: name: m3-mobiles-deployment labels: app: m3-mobiles spec: replicas: 1 selector: matchLabels: app: m3-mobiles template: metadata: labels: app: m3-mobiles spec: volumes: - name: m3-mobiles-assets-vol hostPath: path: /home/docker/m3mobiles/assets - name: m3-mobiles-media-vol hostPath: path: /home/docker/m3mobiles/media containers: - name: m3-mobiles image: amjedsaleel/m3mobiles volumeMounts: - name: m3-mobiles-assets-vol mountPath: /app/assets - name: m3-mobiles-media-vol mountPath: /app/media ports: - containerPort: 8000 env: - name: SECRET_KEY valueFrom: secretKeyRef: name: m3-mobiles-secret key: secret-key - name: DEBUG valueFrom: secretKeyRef: name: m3-mobiles-secret key: debug - name: DB_NAME valueFrom: secretKeyRef: name: m3-mobiles-secret key: db-name - name: DB_USER valueFrom: secretKeyRef: name: m3-mobiles-secret key: db-user - name: DB_PASSWORD valueFrom: secretKeyRef: name: m3-mobiles-secret key: … -
How to solve [Deprecation] Synchronous XMLHttpRequest error in django console
I am currently using Django, but I don't think this is a django-specific error. By the way, I looked at JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated...", but I don't think it solves my issue. As you can see below, I got the error in the chrome console: Here is the code from my templates that I think is causing the problem: {% block script %} <script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script> ... <script src="{% static 'js/checkout.js' %}" type="text/javascript"></script> {% endblock %} The interesting thing is that the website worked fine in development mode on my desktop, but I had this issue once I depolyed it online. Thank you, and please leave any comments or questions you have. -
Space Between Nav Bar & Body
I have a random gap between the body of my base.html and the navbar above it. When I add a random div after the include navbar line, it fills that space with the new information.. But when removed, it's just blank and nothing shifts up. Additionally, when I remove the class='row' for the div tags in the body, nothing happens. What would be causing this space? base.html: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> {% comment %} <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" /> {% endcomment %} <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" integrity="sha512-vKMx8UnXk60zUwyUnUPM3HbQo8QfmNx7+ltw8Pm5zLusl1XIfwcxo8DbWCqMGKaWeNxWA8yrx5v3SaVpMvR3CA==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link href="{% static 'css/base.css' %}" rel="stylesheet"> {% block extracss %}{% endblock %} <title>{% block title %}title{% endblock title %}</title> </head> <body style='background-color:#e7e7e7;'> {% include 'include/navbar.html' %} <div class='row' style='background-color: orange;'> <div class='column' style='padding-left:35px ;float: left; width:17%;background-color: #f1f1f1;'> test </div> <div class='column' style='float: right; width:83%;background-color: #e7e7e7; padding:25px'> {% block content %}{% endblock content %} </div> </div> {% include 'cms/modal/modal.html' %} <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js" integrity="sha512-VEd+nq25CkR676O+pLBnDW09R7VQX9Mdiij052gVCp5yVH3jGtH70Ho/UUv4mJDsEdTvqRCFZg0NKGiojGnUCw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="{% static 'cms/js/ajax.js' %}"></script> {% block extrajs %}{% endblock extrajs … -
How to solve Synchronous XMLHttpRequest error in django console [duplicate]
I am currently using Django, but I don't think this is a django-specific error. By the way, I looked at JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated...", but I don't think it solves my issue. As you can see below, I got the error in the chrome console: Here is the code from my templates that I think is causing the problem: {% block script %} <script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script> ... <script src="{% static 'js/checkout.js' %}" type="text/javascript"></script> {% endblock %} The interesting thing is that the website worked fine in development mode on my desktop, but I had this issue once I depolyed it online. Thank you, and please leave any comments or questions you have. -
Improperly Configured DATABASE_NAME env var
I made a .env file in the same directory as my settings.py file and have some environmental variables in there such as: secret_key, database_name, etc. However, it doesn't seem to be reading the database name correctly in the .env file. I feel like I followed the docs, but still get the improperly configured error when pushing to Heroku. It does work when running the server locally though. settings.py from pathlib import Path import os from datetime import timedelta import environ env = environ.Env() environ.Env.read_env() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Take environment variables from .env file environ.Env.read_env(os.path.join(BASE_DIR, '.env')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env('DEBUG') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': env('DATABASE_NAME'), 'USER': env('DATABASE_USER'), 'PASSWORD': env('DATABASE_PASSWORD'), 'HOST': env('DATABASE_HOST'), 'PORT': env('DATABASE_PORT'), } } .env (example) SECRET_KEY=django-insecure-vdihiodnsdkcndocndcndocdcoidcosjvodjv DEBUG=True DATABASE_NAME=vjiojjoj3oj3ioj3 DATABASE_USER=vdijvodivjdivfv ... error File "/app/project_name/settings.py", line 94, in <module> 'NAME': env('DATABASE_NAME'), File "/app/.heroku/python/lib/python3.10/site-packages/environ/environ.py", line 175, in __call__ return self.get_value( File "/app/.heroku/python/lib/python3.10/site-packages/environ/environ.py", line 371, in get_value raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the … -
Attribute Error: 'Project' object has no attribute 'getVoteCount'
I am getting the error "'Project' object has no attribute 'getVoteCount'" when I am trying to submit an 'upvote' to a project (and hence have the positive vote ratio updated). The error Exception Location is located 28 in the views code which states 'projectObj.getVoteCount'. I have tried playing around with this but cannot work it out. First proper project so explain in simple terms please! Thanks! Models.py: class Project (models.Model): owner = models.ForeignKey( Profile, null=True, blank=True, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = RichTextField(null=True,blank=True) featured_image = models.ImageField(null=True, blank=True, default="default.jpg") subjective = RichTextField(null=True,blank=True) differential_diagnosis = RichTextField(null=True,blank=True) objective = RichTextField(null=True,blank=True) diagnosis = RichTextField(null=True,blank=True) treatment = RichTextField(null=True,blank=True) plan = RichTextField(null=True,blank=True) references = RichTextField(null=True,blank=True) tags = models.ManyToManyField('Tag', blank=True) vote_total =models.IntegerField(default=0, null=True, blank=True) vote_ratio =models.IntegerField(default=0, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.title class Meta: ordering = ['-vote_ratio', '-vote_total','title'] class Review(models.Model): VOTE_TYPE = ( ('up', 'Up Vote'), ('down', 'Down Vote'), ) owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) body = models.TextField(null=True,blank=True) value = models.CharField(max_length=200, choices=VOTE_TYPE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) class Meta: unique_together = [['owner', 'project']] def __str__(self): return self.value @property def getVoteCount(self): reviews = self.review_set.all() upVotes = reviews.filter(value='up').count() totalVotes = reviews.count() ratio … -
How can I have my template display a list on two different div tags without having redundancies
I have a list from my Model but I want my template to display the list element in groups of 4 or half the total length of the list Example: let say i have 10 elements in my list i want 5 on the right size and 5 on the left side. Please see screenshot below. [![But this is what i get ][2]][2] [2]: https://i.stack.imgur.com/zMQdj.png This is my HTML file. <div class="section-title"> <h2>Skills</h2> <p>hsjkhvdkdjhvjkdfnv kjdf, dfhvkhdnfvkjldf,xhvnkldsv.mckldfnv ,dfhxncjcshfxdjvhcnjsdnckndjvbc d,sxbc kjdjsxcbjdksbvc kjs,bhzscs,zhcnlksjhlnzcklsnzjcjsdzcjb ds cxdbjvcsdbzcjks,gdcbkjds,zbcn jkcdxbv,m dfxvchj bdxnvbjhdujxdnkck jdfvknc dfkjhvxjdknfxzjxvkc. </p> </div> {% for skill in skills_list%} <div class="row skills-content"> <div class="col-lg-6" data-aos="fade-up"> <div class="progress"> <span class="skill">{{skill.skill_name}} <i class="val">{{skill.skill_value}}</i></span> <div class="progress-bar-wrap"> <div class="progress-bar" role="progressbar" aria-valuenow={{skill.skill_value}} aria-valuemin="0" aria-valuemax="100"></div> </div> </div> </div> </div> {% endfor %} </div> ##################################### views.py this is the views.py file #### TEST class TestView(generic.ListView): model = Skills template_name = 'portfolio_app/test.html' ########################URL.py from django.urls import path from portfolio_app.models import * from . import views urlpatterns = [ path('',views.fact,name='index'), #path('index/',views.SkillView.as_view,name='index'), path('about/',views.about_me,name='about'), path('service/',views.ServiceView.as_view(),name='service'), path('resume/',views.ResumeView.as_view(),name='resume'), path('contact/',views.ContactView.as_view(),name='contact'), path('test/',views.TestView.as_view(),name='test'), ] -
How to track a user time from the moment he/she logins and logout using django middleware
I am working on a task. To build a middleware using Django rest framework that can track the user time from the moment he/she logins to the logout time means how much time he/she spent during login and logout. Also to count a specific API hit. -
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 …