Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3 'User' object has no attribute 'admin'
SITUATION I am modifying this GitHub project from this YouTube Series and this is a demo how the original application runs. My goal is to add settings option for Merchant(in the code Admin or AdminUser) accounts in the marketplace, because in the original project only buyers have the option to add image and their contact details. CODE model.py #database table create class Customer(models.Model): #empty fields accept - null=True user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(default="profile1.png", null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) #show customer name in admin panel def __str__(self): return self.name class Adminuser(models.Model): #empty fields accept - null=True user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(default="profile1.png", null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) #show customer name in admin panel def __str__(self): return self.name url.py from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ ... path('customer/<str:pk_test>/', views.customer, name="customer"), path('adminuser/<str:pk_test>/', views.adminuser, name="adminuser"), ... ] views.py #CUSTOMER_ONLY PROFILE SETTINGS @login_required(login_url='login') @allowed_users(allowed_roles=['customer']) def accountSettings(request): customer = request.user.customer form = CustomerForm(instance=customer) if request.method == 'POST': form = CustomerForm(request.POST, request.FILES,instance=customer) if form.is_valid(): … -
Multiple Images Upload using Django Claases
I am creating an e-commerce web app using Django and I am stuck at adding multiple Images to a product. This is my Forms.py class ProductForm(forms.ModelForm): images = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta(): model = Products labels = { "isbn": "ISBN" } fields = ('isbn', 'title', 'authors', 'publication_date', 'quantity', 'price', 'images') widgets = { 'publication_date': DateInput() } this is my Models.py class Products(models.Model): isbn = models.CharField(max_length=50) title = models.CharField(max_length=264) authors = models.CharField(max_length=264) publication_date = models.DateField(max_length=264) quantity = models.DecimalField(max_digits=3, decimal_places=0) price = models.DecimalField(max_digits=6, decimal_places=2) seller = models.ForeignKey(User, on_delete=models.CASCADE) creation_date = models.DateTimeField(auto_now_add=True) updation_date = models.DateTimeField(auto_now=True) images = models.ImageField(upload_to='images/',null=True,blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("book_item", kwargs={'pk': self.pk}) def get_add_to_cart_url(self): return reverse("add-to-cart", kwargs={ 'pk': self.pk }) def get_remove_from_cart_url(self): return reverse("remove-from-cart", kwargs={ 'pk': self.pk }) This is my Create View class ProductCreate(LoginRequiredMixin, SuccessMessageMixin, CreateView, ): form_class = ProductForm model = Products template_name = 'books/new_book.html' success_message = "Books Added" def form_valid(self, form): form.instance.seller = self.request.user Products = form.save() Products.save() return super().form_valid(form) I want to add multiple images to my product. -
Setting up deployment for Django+React project having each run on different ports with Nginx
I am developing a Django (for Web API serving) + React (frontend purpose) project where the codebase for both Django and React are consolidated in a main project folder, meaning both are on the same git repository, as below: . +-- _backend | +-- _config | | +-- settings.py | | +-- urls.py | | +-- wsgi.py | +-- _sample_app | +-- _static | +-- _media | +-- manage.py | +-- requirements.txt +-- _frontend | +-- _public | +-- _src | | +-- App.css | | +-- App.js | | +-- index.js | +-- babel.rc | +-- package-lock.json | +-- package.json | +-- webpack.config.js Now, I would like to implement the recommended way of integrating both technologies: Django as a standalone backend app that only serves API (no UI, assets, templates) React as a standalone SPA whose purpose is to serve the frontend (UI, web pages, assets, etc.) Which means that Django will be starting on its own port and React also on its own. Now, during development I could do: React on localhost:3000 Django on localhost:3001 However, I am not pretty sure how to deploy using the above setup on production server. I will be using Nginx for this … -
My user got log out when i'll try to send a form to a BDD (Django)
As the title said, i don't know why my user got disconnected when i create a new "Comment". AND The form should be save in the database but instead i got redirect to the root (with nothing in the database OFC :> ) halp aled ayuda Taskete My view : from django.shortcuts import render, redirect from .models import Comment from . import forms from django.contrib.auth.decorators import login_required def comments_create(request): if request.method == 'POST': form = forms.CreateComment(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/usercomments/') else: form = forms.CreateComment() return render(request,'usercomments/comments_create.html',{'form':form}) The templates : {% extends 'base.html' %} {% block content %} <div class="create_comment"> <h2>Write a comment</h2> <form action="site-form" action="{% url 'create' %}" method="post"> {% csrf_token %} {{form}} <input type="submit" value="Create"> </form> </div> {% endblock %} Urls.py : from django.conf.urls import url from . import views urlpatterns = [ url(r'^$',views.comments_list, name="list"), url(r'^create/$', views.comments_create, name="create"), url(r'^(?P<slug>[\w-]+)/$',views.comments_detail, name="detail"), ] Models.py : from django.db import models from django.contrib.auth.models import User from django.conf import settings class Comment(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add=True) -
Django: Correct way to clear FieldField and set it to blank
I have a file field in a django model, which has a file associated with it. I would like to clear file for a record and perhaps set the filefield to the prior state it was before file was uploaded. What is the correct way to do this? -
Setting up Django-Casper
I have installed Django-Casper on my raspberry-pi following this tutorial: http://blog.daviddemartini.com/installing-casperjs-on-raspberry-pi/ I need it to tests the AJAX of my Django app. Everything worked fine but when I tried to run $ casperjs I've an error TypeError: Attempting to change the setter of an unconfigurable property. I have searched a way to fix this issue but with no luck. Has anyone encountered the same issue? -
Django says 'The _imaging C module is not installed' when I try to add images to database entries
I am working on ubuntu server,and this is my first web development project based on django. After I have hosted the site with apache2, mod_wsgi , the site is running but I have encountered two problems: 1)All the users and other database entries have been lost. I have tried makemigrations and migrate , but it didnt solve it. 2) I tried to add all the entries again, but now there is a problem with adding images to the ImageField in the databases using Pillow module.It says The _imaging C module is not installed . The error takes place in sites-packages\PIL\Image.py (I am using a virtualenv) somewhere around line 93 which is from . import _imaging as core . Python version: 3.7, django version: 3.0 , ubuntu version: 18 Here are all fixes I've tried: 1) Changed line 93 in PIL/Image.py from from . import _imaging as core to from PIL import _imaging as core . No changes, the error still occurs. 2)Tried installing libjpeg with the following code- sudo apt-get install libjpeg-dev . Turned out that I already had it globally. 3)Changed the location of virtualenv directory from somewhere inside /var/www/ to /usr/local/ because somewhere I had read that there … -
Query set error when using get_or_create and objects.filter
I am trying to add a default value to a model when creating one my view def index(request, log_id): log = get_object_or_404(LogBook, pk=log_id) logmessages = LogMessage.objects.filter(logbook=log_id) logbook, _ = LogBook.objects.get_or_create(logmessages=logmessages) form = CreateLogMessage(request.POST) if request.method == "POST": if form.is_valid(): instance = form.save(commit=False) instance.reported_by = request.user instance.date = datetime.now() logbook.done_status = False logbook.save() instance.save() Expected result : Logbook should be created using the logmessage instance. I have an error The QuerySet value for an exact lookup must be limited to one result using slicing. I have look up on SO and althougt this error came up a lot nothing work for me, any idea ? -
I am trying to use static files like css and images in my django project but statics files are not displayed in my template page
I want a image to be displayed in my navbar at the top left corner but its not visible and my css styling is also not styling my pages....in short my static files are not displayed in my project. i think i have mentioned all the neccesary things if anything is missing please mention. my settings.py---- STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') STATIC_FILES = os.path.join(BASE_DIR,'static','static_files') STATIC_ROOT = os.path.join(BASE_DIR,'static','static_root') urls.py--- from Devishi import settings from django.conf.urls.static import static urlpatterns = [ path('',views.home,name='home'), path('product/',views.products,name ='product'), path('customer/',views.customer,name ='customer'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) main.html--- {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>{% block title %}DASHBORD||{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="{% static '/css/my.css' %}"> </head> <body> {% include 'app/navbar.html' %} {% block content %} {% endblock %} <hr/> <p>Our Footer</p> </body> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </html> navbar.html--- {% load static %} <style media="screen"> .hello-msg{ font-size:18px; color:#fff; margin-right:20px; } </style> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <img src="{% static "img/logo.png" %}" alt="image"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item … -
Getting TypeError at / expected string or bytes-like object in QuerySet
I tried to run runserver, I checked all the pages, everything was fine except my homepage which issued an error. TypeError at / expected string or bytes-like object. Traceback (most recent call last): File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\views\generic\list.py", line 142, in get self.object_list = self.get_queryset() File "C:\Users\ANTON\Desktop\Learn Django\cloneBlogProject\mySite\blog\views.py", line 19, in get_queryset return Post.objects.filter(published_date__lte = timezone.now).order_by('-published_date') File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\query.py", line 904, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\sql\query.py", line 1350, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q child_clause, needed_inner = self.build_filter( File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\sql\query.py", line 1311, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\sql\query.py", line 1165, in build_lookup lookup = lookup_class(lhs, rhs) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\lookups.py", line 22, in __init__ self.rhs = self.get_prep_lookup() File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\lookups.py", line 72, in get_prep_lookup return self.lhs.output_field.get_prep_value(self.rhs) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\fields\__init__.py", line 1355, in get_prep_value value = super().get_prep_value(value) File … -
How to use template tags inside safe filtered content in django
<strong>{{ var.name }} </strong> The above code is saved inside database with a field name data . While rendering template with {{ data | safe }} , it gives output as {{ var.name }} as strong , but doesn't load the content inside var.name. Is it possible to do so. -
how to edit or modify my booleanfield in django
i would be really glad if anyone could help me with my code,i have a model shows if a user is subscribed or not,so i decided to use a boolean field but i want to edit the field so that i can be able to display Subscribed once a client click on it and perform some payment in another url,and the user would be given a specific generated code to use till the subscription is over to access to actions here is what i have written in my model and my output thanks in advance models.py class Patient(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, related_name="patient") subscribe = models.BooleanField(default=False) def __str__(self): return f'{self.user.username}' views.py @login_required def patient(request): context = { 'patient': Patient.objects.all() } return render(request, 'pages/patient.html', context) template.html <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4 h4 text-center center">Your Email</legend> <legend class=" mb-4 h3 center text-center">{{ user.email }}</legend> </fieldset> <div class="form-group text-center center"> <button class="btn btn-outline-info" type="submit">{{ user.patient.subscribe }}</button> </div> </form> -
Is possible to send a personalized email in django (with context), without use a html template?
Basically, i would like to know if it's possible to do this: views.py ... current_site = get_current_site(request) subject = 'Activate your account!' message = render_to_string('portale/admin/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) account_activation_email.html {% autoescape off %} Hi {{ user.username }}, Please click on the link below to confirm your registration: http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} but without using the html template. Any ideas? -
How to configure Cookiecutter Django to use Gmail SMTP
Can anyone help me with to configure my django cookiecutter production setup to work with Gmail SMTP. I have deployed my application using docker. Cookiecutter gives you to configure your app to anymail providers. I've chosen Mailgun however I didn't have an email address that has been verified by my domain provider. So, I couldn't register any user to my app because ( https://cookiecutter-django.readthedocs.io/en/latest/deployment-with-docker.html#configuring-the-stack) here it says you can't :) I have tried to override the default email verification setting from "mandatory" to "none". However, it still threw 500. In below, I've added all-auth settings. I had to decide either to buy an email address or configure my app to work with Gmail Smtp or get rid of this email verification process. settings/base.py ACCOUNT_ALLOW_REGISTRATION = env.bool("DJANGO_ACCOUNT_ALLOW_REGISTRATION", True) # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_AUTHENTICATION_METHOD = "username" # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_EMAIL_REQUIRED = True # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_EMAIL_VERIFICATION = "none" # https://docs.djangoproject.com/en/dev/ref/settings/#email-backend EMAIL_BACKEND = env( "DJANGO_EMAIL_BACKEND", default="django.core.mail.backends.smtp.EmailBackend" ) Any way to get rid of this 500 would be awesome. -
How to authenticate fsspec for azure blob storage
From a django REST API view I am trying to access a file that is stored in an azure storage blob. I would like to open it without downloading it into a file, as shown here. Read access is sufficient. For this I scetched out my view like so: import os from fsspec.implementations.http import HTTPFileSystem @api_view() def my_view(request): url = "https://storageaccount.blob.core.windows.net/container/" filename = "file.f" fs = HTTPFileSystem( container_name=os.environ["AZURE_STORAGE_CONTAINER"], storage_options={ "account_name": os.environ["AZURE_STORAGE_ACCOUNT"], "account_key": os.environ["AZURE_STORAGE_KEY"], }, ) with fs.open(url + filename, "r") as fobj: ds = somehow.open_dataset(fobj) return Response({"message": "Data manipulated"}, status=200) This gives a FileNotFoundError. My questions are: Is this even possible with azure blob storage? If not, what would be the closest thing? How would I authenticate the HTTPFileSystem? I feel like I more or less made those keywords up but wasn't able to find any information about it... -
Looping through nested dicts in Django Template
I have a nested dict that I am passing as context to a template of the following structure: cWeeks{ 1: { 'receivables': { 'customer': 'x', 'amount': 'y', ...} 'payables': { 'customer': 'x', 'amount': 'y', ...} } 2: { etc } } In my template I have a for loop iterating over each number and then another nested for loop that should iterate over all items in 'receivables'. Unfortunately that second loop never begins. This is the relevant code in the template: {% for cw in cWeeks %} <div class="kw1"> <div class="card"> <h5 class="card-header text-center">KW {{ cw }}</h5> <ul class="list-group list-group-flush"> {% for receivable in cw.receivables %} <li class="list-group-item zahlung payment-receivable"> <div class="payment-content"> <div class="typ">Zahlung</div> <div class="kunde">{{ receivable.customer }}</div> <div class="kwSelektor"> <form action="#" method="POST"> <div class="form-group formKwSelektor"> <select class="form-control form-control-sm" id="kwxxSelektor"> <option value="10">KW 10</option> <option value="11">KW 11</option> </select> </div> <button type="submit" class="btn btn-primary">KW ändern</button> </form> </div> <div class="betrag">{{ receivable.amount }}</div> <div class="bank">{{ receivable.account }}</div> </div> </li> {% endfor %} </ul> </div> </div> {% endfor %} My views.py: from django.shortcuts import render from django.http import HttpResponse from .models import * def home(request): """ Calendar Weeks payments overview """ cWeeks = {1: dict(), 2: dict(), 3: dict(), 4: dict()} for week in range(1, … -
500 Error on a Django page that uses Ajax
I'm having a 500 error after trying to submit a csv file. The 500 error says having a problem in DeproAjaxView. Up until November this was working fine. Now the live site is giving the 500 error, but the local development server is giving a 403 forbidden error (csrf token missing or incorrect). I checked that, and it does have a token. class DeprovisionView(LoginRequiredMixin,UserPassesTestMixin,TemplateView): template_name = "technology/deprovision.html" login_url = reverse_lazy('login') def test_func(self): user = self.request.user.id groups = User.objects.filter(pk=user,groups__name__exact='HARDWARE_ADMIN').exists() return groups class DeproAjaxView(LoginRequiredMixin,UserPassesTestMixin,View): login_url = reverse_lazy('login') def test_func(self): user = self.request.user.id groups = User.objects.filter(pk=user,groups__name__exact='HARDWARE_ADMIN').exists() return groups def post(self, request, *args, **kwargs): device_list = defaultdict(list) error_list = [] success_list = [] devices = [] deprovision = [] csv_data = json.loads(request.body.decode("utf-8")) data = list(chain.from_iterable(csv_data.get('data'))) loop = asyncio.new_event_loop() response = sorted(loop.run_until_complete(async_get_chromebook(data, loop)), key=itemgetter('status')) for item in response: device_list[item['status']].append(item) for key, value in device_list.items(): if key == 'ACTIVE': devices.extend(value) else: error_list.extend(value) if not devices: data = {'status': 'error','error_list': error_list} else: for item in devices: deprovision.append(item.get('deviceId')) depro_resp = loop.run_until_complete(async_deprovision(deprovision, loop)) for item in depro_resp: if item['status'] == 'SUCCESS': success_list.append(item) else: error_list.append(item) data = {'status': 'success', 'success_list': success_list, 'error_list': error_list} return HttpResponse(json.dumps(data)) -
Django - How to join two querysets with different key values (but from same model)
I am trying to join two querysets in Django with different key values, but from the same model, is there any way to do so? Here is my code: models.py class CustomerInformation(models.Model): status = ( ('lead', 'Lead'), ('client', 'Client'), ) customer_id = models.AutoField(primary_key=True) customer_name = models.CharField(max_length=100) status = models.CharField(max_length=100, choices=status, default='lead') conversion_date = models.DateField(null=True, blank=True) created_date = models.DateField(default=timezone.localdate) def save(self, *args, **kwargs): if self.customer_id: if self.status != CustomerInformation.objects.get(customer_id=self.customer_id).status and self.status == 'client': self.conversion_date = timezone.now() elif self.status != CustomerInformation.objects.get(customer_id=self.customer_id).status and self.status == 'lead': self.conversion_date = None super(CustomerInformation, self).save(*args, **kwargs) here is my filtering start = date.today() + relativedelta(days=-30) client_qs = CustomerInformation.objects.filter(conversion_date__gte=start).values(date=F('conversion_date')).annotate(client_count=Count('date')) lead_qs = CustomerInformation.objects.filter(created_date__gte=start).values(date=F('created_date')).annotate(lead_count=Count('date')) Basically what I am trying to achieve is to get the count of CustomerInformation instances created in the past 30 days (by annotating the count of the field 'created_date'). Also, I want to get the count of CustomerInformation instances that have converted to 'client' status within the past 30 days (by annotating the count of the field 'conversion_date'). Is there any way for me to do so and receive them in a single queryset, preferably with a single date field? For example, my desired output would be [ {'date': '170620', 'lead_count': 2, 'client_count': 1}, {'date': '180620', … -
How to create view for both user and super user in a classbased view in Django? I am trying to use single link for both user and super user
class LoginCBV: def loginview(self, request): if request.user.is_authenticated: return redirect("collage_dashboard") else: if request.method == 'POST': email = request.POST.get('email') password =request.POST.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) return redirect("collage_dashboard") else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'auth/log-in.html', context) #@user_passes_test(lambda x: x.is_superuser) def loginview2(self, request): if request.user.is_authenticated: return redirect("collage_dashboard") else: if request.method == 'POST': email = request.POST.get('email') password =request.POST.get('password') user = authenticate(request, email=email, password=password) if user is not None and user.is_superuser: login(request, user) return redirect("dashboard") else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'auth/log-in.html', context) -
How do I extend my Django Default UserCreationForm?
here is my "forms.py" class CreateUser(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] and here is my "views.py" def register(request): form = CreateUser() if request.method == 'POST': form = CreateUser(request.POST) if form.is_valid(): form.save() # messages.sucess(request, 'Acccount created!') return redirect('login') context = {'form':form} return render(request, 'register.html', context) and here is my basic register.html so far. <h3>Register</h3> <form method="POST" action=""> {% csrf_token %} {{form.as_p}} <input type="submit" name="Create User"> <a href="/login">I already have a user!</a> {{form.errors}} </form> The thing is, I need to add a lot of stuff to the registration. The default user/password login is ideal, but the registration needs to have other fields for things like address and credit card number. How do I properly extend this registration, in a way that the login is still the same? -
Is there a way of triggering an action when a specific field is changed in Django models
I am looking for a way to trigger an action whenever a specific field on a model is changed, regardless of where it is changed. To add some context, I have been experiencing an elusive bug, where occasionally a date field is being set to the 13th of January 2020, I have absolutely no idea where in the codebase this is happening, it is also happening seldom enough that I have not been able to pick up any pattern as to what could be causing it. What I would like to do is trigger some kind of an alert whenever this field is changed to the 13th of Jan 2020, so I can attempt to isolate what is causing it. -
How do I find the name and its count for a FK object?
Having these models: class AccidentJob(models.Model): name = models.CharField(max_length=50) class Accident(TimeStampedModel, models.Model): job = models.ForeignKey(AccidentJob, on_delete=models.CASCADE) I want something like this: [ {'job__name': 'Auxiliar de surtido', 'count': 2}, {'job__name': 'Técnico de mantenimiento', 'count': 1} ] but I am getting this: [ {'job__name': 'Auxiliar de surtido', 'count': 1}, {'job__name': 'Auxiliar de surtido', 'count': 1}, {'job__name': 'Técnico de mantenimiento', 'count': 1} ] This is my query: from django.db.models import Count Accident.objects.values( "job__name" ).annotate( count=Count('job__name') ).values("job__name", "count") I can do it with Python, but I would prefer having PostgreSQL do the work. -
Django form field values filter by multiple queries
I am working with form logic now and my task sounds pretty easy - I need to implement form with dependent fields: 1) Country 2) Region 3) District (area) So I have my simple models: class CountryModel(models.Model): name = models.CharField('Country name', unique=False, max_length=128, blank=False, null=False) class RegionModel(models.Model): name = models.CharField('Region name', unique=False, max_length=128, blank=False, null=False) country = models.ForeignKey(CountryModel, on_delete=models.CASCADE, blank=True, null=True) class DistrictModel(models.Model): name = models.CharField('District name', unique=False, max_length=128, blank=False, null=False) region = models.ForeignKey(RegionModel, on_delete=models.CASCADE, blank=True, null=True) class FormModel(MetaModel): country = models.ForeignKey(CountryModel, on_delete=models.CASCADE, blank=True, null=True) region = models.ForeignKey(RegionModel, on_delete=models.CASCADE, blank=True, null=True) area = models.ForeignKey(AreaModel, on_delete=models.CASCADE, blank=True, null=True) It means that District queryset is depends on chosen Region and Region queryset is depends on chosen Country. I put my logic in the init form method and it looks like this: class SignCreateForm(ModelForm): data_url = '/sign-form-data/' class Meta: model = FormModel fields = ['country', 'region', 'district'] dependencies = {'district': ('region', 'country'), 'region': ('country',)} class Media: # ajax form refreshing script js = ('js/formset.js',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.is_bound: if self.data['country']: self.fields['district'].limit_choices_to = {'country': self.data['country']} apply_limit_choices_to_to_formfield(self.fields['district']) Dut it doesn’t works and raises an error: "Cannot resolve keyword 'country' into field. Choices are: id, name, region.." The question is: Is there … -
Wagtail admin_order_field attribute not sorting correctly
I have admin_order_field attribute set on method in ModelAdmin class but it's giving wrong sort results. Upon clicking sort button, it displays some duplicates and some of the values("All Clients", No Client Selected") are not grouped together. `class PermissionsModelAdmin(ModelAdmin): def clients_list(self, obj): all_clients = "All Clients" c_name = [c.name for c in obj.clients.all()] if c_name: selected_clients = ", ".join([c.name for c in obj.clients.all()]) else: selected_clients = "No Client Selected" return all_clients if obj.is_accessible_to_all_clients else selected_clients clients_list.short_description = "Clients" clients_list.admin_order_field = "clients"` -
how can i open bash_profile? i tried subl ~/.bash_profile . But i got
C:\Users\PC\PycharmProjects\django\mysite>subl ~/.bash_profile 'subl' is not recognized as an internal or external command, operable program or batch file.