Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django models.py
I created an App called order whose models.py (model name create_order) contain fields like "order_created_by, cloth_type, clothe colour, size, delivery_date, order_created_date". Now in models.py of wherehouse app I want to see all the field of created_order model. How can I do that. And can do this all using first importing models in views.py of wherehouse and the creating function then retuning the Http Response using models.objects.all(). But I want to see these all fields of create_order in admin.py of wherehouse app. -
Django: Save html entries in mysql db
I'm trying to follow this open source project to learn more about Django and crispy. For that I try to extend this open source project I downloaded the project from GitHub and got it running :). However, the models.py is missing and I thought I'll try to add it, and push the html form data into my local mysql db. So basically I'm trying to extend that existing code. I was able to add the models.py and create the table in mysql. Issue: If I press the submit button, no data appears in mysql. What I think I figured out is, I need some "save()" command. But where? I found postings on google about codlins in forms.py and view.py. But either it did not resolve it or cause error. Any ideas how to overcome this? models.py from django.db import models from mysite.core.choice import STATES class Address(models.Model): email = models.CharField(max_length=100, blank=True) password = models.CharField(max_length=100, blank=True) address_1 = models.CharField(max_length=100, blank=True) address_2 = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=100, blank=True) zip_code = models.CharField(max_length=100, blank=True) state = models.IntegerField(default=1, choices=STATES, blank=True) check_me_out = models.BooleanField(default=False) forms.py --> Also with comments about what I changed vs. the original from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout … -
how to store count value in python(django)?
I am trying to implement an upload limit functionality. I found that Everything is working as expected except the count value. Please find the below views.py code. def CTA_upload(request): i = 1 count = [0,] print('Counter value at starting::::::::: :', len(count)) allcts = CTS.objects.all() try: if len(count) <= 14: if request.method == 'POST': movie_resource = CTAResource() print('movie_resource', movie_resource) dataset = Dataset() new_movie = request.FILES['file'] if not new_movie.name.endswith('xls'): messages.info(request, 'Sorry Wrong File Format.Please Upload valid format') return render(request, 'apple/uploadcts.html') messages.info(request, 'stage1 fired:Processing file type is Okay :)...') imported_data = dataset.load(new_movie.read(), format='xls') print('abcdefghijk:', type(imported_data)) messages.info(request, 'Stage2 fired:*** Now checking data inside imported data :)') for data in imported_data: value = CTA( data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], ) print('Value 1 ::::', value) print('Final Count After entering < = 15:', len(count)) messages.info(request, 'Stage3 fired:*** Now entering to check count <= :)') i = i + 1 count.append(i) print('Count After Appending Value:',count) value.save() else: print('Final ***else Count when > = is equal to 15:', len(count)) messages.info(request, 'Sorry you are uploading more than 15 records so records') print('Final count jo hai variable me store:', count) messages.info(request, 'Sleeping For 10 sec and then it will clear count value. so you can upload extra … -
How to include Duo Authentication to Django UI after Windows Authentication
i have a code which performs uploading of file to certain destination , and i have already include windows authentication as first phase of authentication and wanted to include Duo Security as second authentication . So i referred few of the git and other platforms regarding duo security and edited my settings.py and Urls.py as below Settings.py INSTALLED_APPS = [ 'duo_auth', ] MIDDLEWARE = [ # ... 'duo_auth.middleware.DuoAuthMiddleware', ] DUO_CONFIG = { 'DEFAULT': { 'HOST': '<api-host-url>', 'IKEY': '<integration_key>', 'AKEY': '<app_secret_key>', 'SKEY': '<secret_key>', 'FIRST_STAGE_BACKENDS': [ 'django.contrib.auth.backends.ModelBackend', ] } } and URLS.py as urlpatterns = [ path('admin/', admin.site.urls), path('duo/', include('duo_auth.urls')), path('', views.home,name='home'), path('create', views.create,name='create'), path('files', views.files,name='files'), ]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and installed django-duo-auth and is successfully installed , i migrated the change and ran server , restarted app . But this is throwing me error 500 . So i really don know whether any change other than this is required or anything is to be added or removed . i didn't find any relative paper or article which i can read and solve this issue . Kindly help me solve this issue . -
How to upload a django project to heroku?
I have been trying to upload my Django app to the Heroku for 3 hours but it is showing me an error. I am doing everything as shown in the documentation but I am getting this error. error: src refspec master does not match any error: failed to push some refs to 'https://git.heroku.com/share-good.git' could anyone help me with that please?? -
Nginx reverse proxy to django application, images styles are not showing
Hello i have a complete django app which I'll be hosting on aws ec2 with gunicorn and nginx. But when I run the app with gunicorn or python3 my app runs and shows all images with the css and styles. But whenever I try to serve my django app with nginx by proxy_pass the image or style or anything on static folder could not be accessed. my error log shows permission issue. But I have set the app with user and group both nginx. but nothing is showing. nginx conf on nginx.conf http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 4096; include /etc/nginx/mime.types; default_type application/octet-stream; include /etc/nginx/conf.d/*.conf; server { listen 80; server_name dev.softopark.com; root /home/ec2-user/sites/softopark-django-cms; access_log /var/log/nginx/dev.softopark.com.access.log; error_log /var/log/nginx/dev.softopark.com.error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /usr/share/nginx/html/softopark-django-cms/static/; } location /media/ { root /usr/share/nginx/html/softopark-django-cms/media/; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://0.0.0.0:8000/; } } my gunicorn service file [Unit] Description=Softopark gunicorn service by: Softopark.com After=network.target [Service] User=nginx Group=nginx WorkingDirectory=/usr/share/nginx/html/softopark-django-cms Environment="/home/ec2-user/Env/cms5-XkwMz5k7/bin" ExecStart=/home/ec2-user/Env/cms5-XkwMz5k7/bin/gunicorn --workers 3 --bind 0.0.0.0:8000 … -
Annotate the union queryset not support in djagno
how calculate summery from union queryset: after union queryset sometime needed to calculate or summery data but annotate not work in django how calculate this a simple scenario for my case from django.db import models from django.db.models import Sum, F class Person(models.Model): name = models.CharField() class InvoiceRemain(models.Model): person = models.ForeignKey(Person, models.PROTECT) currency = models.CharField() currency_rate = models.DecimalField(max_digits=20, decimal_places=5) amount = models.DecimalField(max_digits=20, decimal_places=5) class PersonPayReceive(models.Model): person = models.ForeignKey(Person, models.PROTECT) currency = models.CharField() currency_rate = models.DecimalField(max_digits=20, decimal_places=5) amount = models.DecimalField(max_digits=20, decimal_places=5) class OpenBalance(models.Model): person = models.ForeignKey(Person, models.PROTECT) currency = models.CharField() currency_rate = models.DecimalField(max_digits=20, decimal_places=5) amount = models.DecimalField(max_digits=20, decimal_places=5) invoice = InvoiceRemain.objects.all().values('person', 'amount', 'currency_rate') pay_rec = PersonPayReceive.objects.all().values('person', 'amount', 'currency_rate') open_balance = OpenBalance.objects.all().values('person', 'amount', 'currency_rate') result = invoice.union(pay_rec, open_balance).values('person').annotate( result=Sum(F('amount') * F('currency_rate'))).values('person', 'amount') -
filter outpout of process with potentially unlimted output, detect exit code and timeout after X
This is question is related to select.select issues with subprocess.Popen (process doesn't stop, no data to read) and I still don't have any idea how to nicely solve the problem. I have some existing django code running under uwsgi (under Linux) with threading disabled, that executes for some requests a subprocess, that I don't have any control over. The normal operation is following: the subprocess runs for a rather short time and returns either an exit code of 0 or something different. The code will write some messages to stdout / stderr. The return code (exit ode) will tell me whether the work was done correctly. if execution failed it would be good to gather stdout/stderr and log it to understand why things failed. On rare occasions however the subprocess can encounter a so far not understood race condition and will do following. it will write repeatedly a specific message to stdout and stderr and loop and hang forever. As I don't know whether there are any other race conditions, that could freeze the process with or without any output. Id' also like to add a timeout. (Though a solution, that adresses getting the return code and detecting the repeated … -
Django REST Framework API : How to save/upload images with the name given by user(e.g. username.jpg) at Django server
I want to upload image with the name (which is given by user) at Django server through rest API,but i am not be able to find out the solution for this.Please tell me how to upload image with given name. here is my code(mainly): IN API TASK ->URLS: from django.conf.urls import include, url from django.contrib import admin from rest_framework import routers from django.conf import settings from myapi import views from django.conf.urls.static import static #Define API Routes router = routers.DefaultRouter() router.register(r'myimage', views.myimageViewSet) #we have only on viewset urlpatterns = [ url(r'^',include(router.urls)), url(r'^admin/',admin.site.urls), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) IN My API 1. MODEL from django.db import models # Create your models here. class myimage(models.Model): my_name=models.CharField(max_length=50) my_image=models.ImageField(upload_to='Images/',default='Images/None/No-img.jpg') def __str__(self): return self.my_name 2.SERIALIZERS from rest_framework import serializers from .models import myimage class myimageserializer(serializers.ModelSerializer): class Meta: model =myimage fields=('id','my_name','my_image') 3. VIEWS from django.shortcuts import render from .models import myimage from rest_framework import viewsets from .serializers import myimageserializer from rest_framework import filters import django_filters.rest_framework class myimageViewSet(viewsets.ModelViewSet): queryset = myimage.objects.all() #We use Filters for Ordering so remove order_by part serializer_class = myimageserializer filter_backends = (django_filters.rest_framework.DjangoFilterBackend,filters.OrderingFilter,) ordering = ('id','my_name',) 4.ADMIN from django.contrib import admin from .models import myimage admin.site.register(myimage) -
Password not changing of user
So I'm trying to change the password of the user via a form but it never changes, It says password changed but it always stays the same. views.py @login_required def userchange(request): if request.method == 'POST': user = request.user old_password = request.POST['Old password'] new_password1 = request.POST['New password1'] new_password2 = request.POST['New password2'] print(new_password1) print(new_password2) if user.check_password(old_password): if new_password1 == new_password2: if new_password1 == "" or new_password2 == "": return render(request, 'main/change.html', {'error':'Your new passwords are empty!'}) else: User.objects.get(username=request.user.username).set_password(new_password1) logout(request) return render(request, 'main/change.html', {'error':'Your password has been changed succesfully!'}) else: return render(request, 'main/change.html', {'error':'Your new passwords do not match'}) else: return render(request, 'main/change.html', {'error':'Your old password is incorrect'}) elif request.method == "GET": return render(request, 'main/change.html') change.html <h1>Note: You will be logged out</h1> <h2>{{ error }}</h2> <form method="POST"> {% csrf_token %} <input type="password" placeholder="Old password" name="Old password"> <input type="password" placeholder="New password" name="New password1"> <input type="password" placeholder="Confirm password" name="New password2"> <button type="submit">Change password</button> </form> -
IntegrityError: null value in column "category_id" of relation "message" violates not-null constraint DETAIL: Failing row contains
I believe this error comes from this line that i might have written incorrectly. Anyone can share why this is written incorrectly in views.py? I understand that I have to specify the this field because it is a foreign key to the model Category: message.category_id = self.categories.id views.py class AddMessageView(DetailView, FormView): model = Room form_class = MessageForm template_name = 'add_message.html' def form_valid(self, form): message = form.save(commit=False) message.category_id = self.categories.id message.name = self.request.user message.room = self.get_object() message.save() models.py class Category(models.Model): categories = models.CharField(max_length=80, null=False, blank=False, unique=True) slug = models.SlugField(blank=True, unique=True) class Room(models.Model): categorical = models.ForeignKey(Category, related_name='categorical', on_delete=models.CASCADE) slug = models.SlugField(blank=True) class Message(models.Model): category = models.ForeignKey(Category, related_name='category', on_delete=models.CASCADE) room = models.ForeignKey(Room, related_name='messages', on_delete=models.CASCADE) name = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='naming', on_delete=models.CASCADE) -
Got AttributeError when attempting to get a value for field `members` on serializer `HealthQuotationSerializer`
Trying out serialising parent and child model.Here are my models: class HealthQuotation(models.Model): quotation_no = models.CharField(max_length=50) insuredpersons = models.IntegerField() mobile_no = models.CharField(max_length=10) def __str__(self): return self.quotation_no class HealthQuotationMember(models.Model): premium = models.FloatField(null=True) suminsured = models.FloatField() quotation = models.ForeignKey(HealthQuotation,on_delete=models.CASCADE) def __str__(self): return str(self.quotation) Here are my serializers: class HealthQuotationMemberSerializer(serializers.ModelSerializer): class Meta: model = HealthQuotationMember fields= "__all__" class HealthQuotationSerializer(serializers.ModelSerializer): members = HealthQuotationMemberSerializer(many=True) class Meta: model = HealthQuotation fields = ['id','members'] On Serialising parent model with parent serializer, Django throws error "Got AttributeError when attempting to get a value for field members on serializer HealthQuotationSerializer. The serializer field might be named incorrectly and not match any attribute or key on the HealthQuotation instance. Original exception text was: 'HealthQuotation' object has no attribute". -
NoReverseMatch at /blog Reverse for 'single_blog' with no arguments not found. 1 pattern(s) tried: ['single_blog/(?P<id>[0-9]+)/$']
I tried many times but the page not rendering , i am not understanding where i did wrong? could you please let me know , where i did wrong? models.py class Post(models.Model): head = models.CharField(blank=False, unique=True, max_length=250) date_time = models.DateTimeField(blank=True, null=True, default=None) description = models.TextField(blank=False, max_length=1000) by_name = models.CharField(blank=False, null=True, unique=True, max_length=250) by_img = models.ImageField(null=True, blank=True) def __str__(self): return self.head views.py def blog(request): blogs = Post.objects.all() return render(request, 'blog.html', {'blogs': blogs}) def blog(request): blogs = Post.objects.all() return render(request, 'blog.html', {'blogs': blogs}) def dynamicblog(request, id): obj = Post.objects.get(id=id) return render(request, 'single_blog.html', {'obj': obj}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('contact', views.contact, name='contact'), path('shop', views.shop, name='shop'), path('service', views.service, name='service'), path('blog', views.blog, name='blog'), path('single_blog/<int:id>/', views.dynamicblog, name='single_blog'), path('single_service', views.single_service, name='single_service'), blog.html {% for blog in blogs %} <div class="col-lg-4 col-md-6 col-sm-12 news-block"> <div class="news-block-two news-block-three wow fadeInLeft" data-wow-delay="300ms" data-wow-duration="1500ms"> <div class="inner-box"> <div class="image-holder"> <figure class="image-box"><img src="{{blog.by_img.url}}" alt=""></figure> </div> <div class="lower-content"> <h4><a href="{% url 'single_blog' %}">{{blog.head}}</a></h4> <div class="post-info">by {{blog.by_name}} on {{blog.date_time}}</div> <div class="text">{{blog.description}}</div> <div class="link-btn"><a href="{% url 'single_blog/{{blog.id}}' %}">Read More<i class="flaticon-slim-right"></i></a></div> </div> </div> </div> </div> {% endfor %} single_blog.html <div class="col-lg-4 col-md-12 col-sm-12 sidebar-side"> {% for blog in obj %} <div class="sidebar blog-sidebar"> <div class="contact-widget sidebar-widget … -
pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection:
I am trying to use MongoDB with Django Framework using the library Djongo. I am stuck in a particular problem right now where I can't store more than 1 document in MongoDB. After first data insert, Django Throws pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: Even though I only have one document. Also I am not setting '_id' field in my models. So its Djongo who does it for me. My Model.py from djongo import models # Create your models here. class Data(models.Model): company_name = models.CharField(max_length=200) company_url = models.CharField(max_length=200) company_logo = models.CharField(max_length=200) objects = models.DjongoManager() -
Django: Easy way how to handle if an objects exists already or not
I have on my website an inputfield only with an email, where customers can sign up for newsletters. At the moment I am handling by a function if this customer (email) exists already, if not then the object is created, if not, then the object is catched. There must be a simplier way to do that in Django? Any ideas? Thanks a lot This is the simplified function: def get_customer(email): # all only lowercase in order to avoid multiple entries email = email.lower() if Customer.objects.filter(email=email).exists(): # get customer object customer = Customer.objects.get(email=email) else: # save form input to database customer = Customer.create(email) customer.save() return customer This is the real function, where I also update optional parameters like name (which is an input in an other form): def get_customer(name, email): # all only lowercase in order to avoid multiple entries email = email.lower() if Customer.objects.filter(email=email).exists(): # get customer object customer = Customer.objects.get(email=email) # if no name available in customer object but name given here, then update customer object if len(customer.name) == 0 and len(name) > 0: Customer.objects.filter(id=customer.id).update(name=name) else: # save form input to database customer = Customer.create(name, email) customer.save() return customer P.S.: I know email = email.lower() is not 100% correct … -
i have create user model . how to change password using email password reset link without use built-in django user model
model.py from django.db import models class Customer(models.Model): firstname=models.CharField(max_length=50) lastname=models.CharField(max_length=50) phone=models.CharField(max_length=10) email=models.EmailField(max_length=100) password=models.CharField(max_length=30) address=models.CharField(max_length=200) is_activated = models.BooleanField(default=True) def str(self): return self.firstname @staticmethod def get_customer_by_email(email): try: return Customer.objects.get(email=email) except: return False -
The view message.views.message didn't return an HttpResponse object. It returned None instead
after submitting the form it shows this error that values error at /Contact/ and the error which i mentioned in title i want to load html file in httpresponse after submmiting the form views.py from django.shortcuts import render, redirect from .forms import Messageform from django.contrib import messages from django.http import HttpResponse, HttpResponseNotFound from django.template import Context, loader # Create your views here. def message(request): if request.method == 'POST': form = Messageform(request.POST) if form.is_valid(): form.save() messages.success(request, 'Message sent') template = loader.get_template("message/messagesent.html") return HttpResponse(template.render()) else: form = Messageform() return render(request, 'contact.html', {'form': form}) -
user_id does not exist in database in DJANGO
I'm trying to access the profile of the user using its id as the url. My problem is that it returns that the id does not exist. Here are some codes that is related to the problem. views.py: @login_required(login_url='login') def profile_view(request, *args, **kwargs): context = {} user_id = kwargs.get("user_id") try: profile = UserAccount.objects.get(pk=user_id) except UserAccount.DoesNotExist: return HttpResponse("User is not yet registered.") if profile: context['id'] = profile.id context['username'] = profile.username context['profile_image'] = profile.profile_image context['date_joined'] = profile.date_joined return render(request, 'chat/profile.html', context) models.py: class UserAccount(models.Model): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=60, unique=True) password = models.CharField(max_length=100) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_superuser = models.BooleanField(default=False) def __str__(self): return self.username urls.py: path('account/<user_id>/', views.profile_view, name='profile_view'), base.html: {% if user.is_authenticated %} <a class="nav-item" role="presentation" href="{% url 'profile_view' user_id=request.user.id %}">Profile</a> <span class="navbar-text actions"><a class="btn btn-light action-button" role="submit" href="{% url 'logout' %}">Logout</a></span> {% else %} <a class="btn btn-light action-button" role="button" href="{% url 'register' %}">Sign Up</a></span> {% endif %} Sample run CORRECT: Login (as the first created user) Clicked profile redirects to the localhost:8000/account/1/ Sample run Error: Login (as the 5th created user) Clicked profile redirects to localhost:8000/account/5/ --> gives HttpResponse() under the views.py changing the value to 1 localhost:8000/account/1/ --> gives correct information … -
Field 'id' expected a number but got 'test1'
So I'm trying to change user password. I have tried user.set_password but that just doesn't work, It does not change the password User.objects.get(user_permissions=request.user.username).set_password(new_password1) gives me an error. views.py @login_required def userchange(request): if request.method == 'POST': user = request.user old_password = request.POST['Old password'] new_password1 = request.POST['New password1'] new_password2 = request.POST['New password2'] if user.check_password(old_password): if new_password1 == new_password2: if new_password1 == "" or new_password2 == "": return render(request, 'main/change.html', {'error':'Your new passwords are empty!'}) else: User.objects.get(user_permissions=request.user.username).set_password(new_password1) logout(request) return render(request, 'main/change.html', {'error':'Your password has been changed succesfully!'}) else: return render(request, 'main/change.html', {'error':'Your new passwords do not match'}) else: return render(request, 'main/change.html', {'error':'Your old password is incorrect'}) elif request.method == "GET": return render(request, 'main/change.html') change.html <h1>Note: You will be logged out</h1> <h2>{{ error }}</h2> <form method="POST"> {% csrf_token %} <input type="password" placeholder="Old password" name="Old password"> <input type="password" placeholder="New password" name="New password1"> <input type="password" placeholder="Confirm password" name="New password2"> <button type="submit">Change password</button> </form> -
Deploying project to Heroku builds fine but is unable to release and generates the SECRET_KEY setting must not be empty error
I am new to Django and Heroku. I cloned t[his][1] project from Github and tried to push it to Heroku. The entire build process goes smoothly, but the project never gets released. Unfortunately as soon as I get to the release stage I keep running into this error and have no idea how to solve it. Any suggestions? remote: Traceback (most recent call last): remote: File "manage.py", line 15, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 224, in fetch_comman remote: klass = load_command_class(app_name, subcommand) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 36, in load_command_class remote: module = import_module('%s.management.commands.%s' % (app_name, name)) remote: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 994, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 971, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 665, in _load_unlocked remote: File "<frozen importlib._bootstrap_external>", line 678, in exec_module remote: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 14, in <module> remote: from django.db.migrations.autodetector import MigrationAutodetector remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/autodetector.py", line 11, in <module> remote: from django.db.migrations.questioner import … -
Stop Django from rendering JSON response
I'm using Django with rest_framework and in my views I'm using the rest_framework.viewsets, I stopped rest_framework to show it's fancy interface using: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer'), } But now Django is rendering the JSON response I want it always to return Raw Data How can I do that? -
How to access short_description of a property in Django
If I have a Django model with a property defined as def __task_state(self): if self.task_id is None: return None else: return # Calculate state somehow __task_state.short_description = _("Task State") # Task state task_state = property(__task_state) Now how do I access short_description for the property? I am trying to iterate over all properties and field for the model so I can get verbose_name equivalent to use in detailed view and for list view column header. I can't use __task_state.short_description directly and I can't figure out how to get this info using task_state doc() function says not defined, short_description is obviously not going to be an attribute of property. Can't seem to find anything on it anywhere. Everywhere all it says is use short_description for property text but no one mentions how to access it. This is how I am trying to find all properties for my model in case anyone feel its relevant # Get property (name, value) set for the object def get_properties(self): # Get all properties property_names = [ name for name in dir(Job) if isinstance(getattr(Job, name), property) ] # Return list result = [] # Let's prune out pk from the result as we don't want it for … -
Lightbox error when trying to find close.png next.png loading.png prev.png
Could someone point me in the direction where I am supposed to be saving the subjected files? The error I am getting is "Not Found: /images/close.png" when trying to add buttons to my lightbox images. It's obviously expecting an images folder but I cannot seem to place it in the correct location within my project. Anyone lend a hand on where exactly to place this images folder..? Using Pycharm enter image description here -
Serving Django Channel and Django Rest Framework from same Elastic Bean Server?
How to serve the Django Rest Framework and Django Channel from the same Elastic Bean Container? -
@user_passes_test not working as expected - Django Python
I have created a role based login in Django 3.1.2. And i have used @user_passes_test decorator to check the role of user according to his/her role he can access the views, or we can say views will execute but it is not working as expected. models.py class User(AbstractUser): GENDER = ( (True, 'Male'), (False, 'Female'), ) USER_TYPE = ( ('Admin', 'Admin'), ('Designer', 'Designer'), ('Customer', 'Customer'), ) user_id = models.AutoField("User ID", primary_key=True, auto_created=True) avatar = models.ImageField("User Avatar", null=True, blank=True) gender = models.BooleanField("Gender", choices=GENDER, default=True) role = models.CharField("User Type", max_length=10, choices=USER_TYPE, default='Customer') Here in user models I have a field, with help of that I can specify user role and default is Customer. views.py # view to check whether a user is Designer or Admin def check_role_admin_or_designer(user): if user.is_authenticated and (user.role == 'Admin' or user.role == 'Designer'): print(user.role) return True # view to check whether a user is Admin def check_role_admin(user): if user.is_authenticated and (user.role == 'Admin' or user.is_superuser): return True else: return HttpResponse("You are not Authorized to access this page") # my login view def loginPage(request): if request.user.is_authenticated and request.user.role == 'Customer': return redirect('user-home') if request.user.is_authenticated and ( request.user.role == 'Admin' or request.user.role == 'Designer' or request.user.is_superuser): return redirect('admin-home') else: if …