Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make option in form disabled When already requested
I am building an web app that allows users to request items. The user will select the item, the location, the start date and end date of the borrowing in a form. I have the following model which I created the form from: class Request(models.Model): shootkit = models.ForeignKey(Shootkit, on_delete=models.CASCADE, null=True, blank=True) username = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) request_start_date = models.DateField('Start Date') request_end_date = models.DateField('End Date') location = models.ForeignKey(Location, on_delete=models.CASCADE) I have 5 Items in the database. And here's the model: class Shootkit(models.Model): shootkit = models.CharField('Shootkit', max_length=100, null=True, blank=True) And the def in views: def request_form(request): submitted = False if request.method == "POST": form = requestForm(request.POST) if form.is_valid(): stock = form.save(commit=False) stock.username = request.user stock.save() return HttpResponseRedirect('/request_form?submitted=True') else: form = requestForm(initial = {'username': request.user}) if 'submitted' in request.GET: submitted = True return render(request, 'request_form.html', {'form':form, 'submitted':submitted,}) The issue here is that I want to grey out (disable?) the items options which have been already requested. so I know that I can filter the date greater or equal than today in objects in the Request table so it means that the item still unavailable. But I am not sure how to block/disable the item. Can anyone help please? -
Which javascript library to choose if I want to use Django for backend?
Which js library should I use if I want server side rendering and both frontend and backend on the same host. Usually I use React+webpack alongside Django, and I serve the frontend as a static page but I want to try something different. I was thinking about exporting static pages with NextJs and then use Django to serve those pages individually (not sure if this would work though). Any thoughts or ideas? -
Hello!! i'm a beginer in django and python development. but when i want to use the commandd pipenv shell i have this error
pipenv shell Traceback (most recent call last): File "c:\users\qurrata\appdata\local\programs\python\python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\qurrata\appdata\local\programs\python\python39\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Users\Qurrata\AppData\Local\Programs\Python\Python39\Scripts\pipenv.exe_main.py", line 7, in File "C:\Users\Qurrata\AppData\Local\Programs\Python\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 829, in call return self.main(*args, **kwargs) File "C:\Users\Qurrata\AppData\Local\Programs\Python\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 781, in main with self.make_context(prog_name, args, **extra) as ctx: File "C:\Users\Qurrata\AppData\Local\Programs\Python\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 700, in make_context self.parse_args(ctx, args) File "C:\Users\Qurrata\AppData\Local\Programs\Python\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 1212, in parse_args rest = Command.parse_args(self, ctx, args) File "C:\Users\Qurrata\AppData\Local\Programs\Python\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 1044, in parse_args parser = self.make_parser(ctx) File "C:\Users\Qurrata\AppData\Local\Programs\Python\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 965, in make_parser for param in self.get_params(ctx): File "C:\Users\Qurrata\AppData\Local\Programs\Python\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 912, in get_params help_option = self.get_help_option(ctx) File "c:\users\qurrata\appdata\local\programs\python\python39\lib\site-packages\pipenv\cli\options.py", line 27, in get_help_option from ..core import format_help File "c:\users\qurrata\appdata\local\programs\python\python39\lib\site-packages\pipenv\core.py", line 33, in from .project import Project File "c:\users\qurrata\appdata\local\programs\python\python39\lib\site-packages\pipenv\project.py", line 24, in from .environment import Environment File "c:\users\qurrata\appdata\local\programs\python\python39\lib\site-packages\pipenv\environment.py", line 16, in import pkg_resources ModuleNotFoundError: No module named 'pkg_resources' -
Check if a User type exists in ManyToManyField in Django?
I have a Course Model which contains a user who creates the course and contains a enrolled ManyToManyField which lets users enroll in the course. class Course(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='course_owner') enrolled = models.ManyToManyField(User) ... The user model contains two types - Teacher (Created the course) and Student (enrolls) class User(AbstractUser): is_student = models.BooleanField(default=True) is_teacher = models.BooleanField(default=False) I want a MyCourses View where the teacher can view his created_courses and the student can view his enrolled courses. def MyCourses(request): user = request.user courses = Course.objects.filter(user=user) context = { 'courses': courses } return render(request, 'classroom/mycourses.html', context) This works for the teacher part but how I can check if a student is enrolled in the course? Thanks. -
Why Django CK Editor easy image plugine not working?
I want image drag and drop functionality in my text editor so I added CK Editor easy image plugin. After adding easy image plugin, my whole text editor disappeared. Others plugin working properly but when trying to add easy image plugine, I am facing this issue. models.py text = RichTextUploadingField( # CKEDITOR.config.extraPlugins: extra_plugins=['notification','exportpdf','easyimage'], #notification and exportpdf working but when adding 'easyimage', my whole text editor is disappearing. # CKEDITOR.plugins.addExternal(...) #using my own path as they mention like this external_plugin_resources=[( 'someplugin', '/static/.../path-to-someplugin/', 'plugin.js', )], ) -
How to save multiple objects in Django models at once
What I'm trying to do is saving multiple scraped data(actor names) in my Actor table inside Django models. So far I've written the for loop below to achieve this goal but it only saves the last object. class Actor(models.Model): name = models.CharField(max_length=50) url = models.URLField() def __str__(self): return self.name def save(self, *args, **kwargs): i = 0 for num in range(5): title, year, actor_list = scraper(self.url) self.name = actor_list[i] super().save(*args, **kwargs) i += 1 I get the URL from users within a form, then save the form and send it to my models and the scraping begins. I scrape 5 actor names inside the scraper() function and append them to actor_list. But when I try to save the actor_list under the save function, it only saves the 5th actor which I think overwrites the previously saved objects. Is there something wrong with my for loop? or should I completely change my approach for this purpose? I'd also prefer to save the objects using Actor.objects.get_or_create() to skip the already existing objects, but I don't know how and where. I would appreciate it if someone could help me with this. -
How to save data in UserProfile while doing registeration in Django?
I make the SignUpForm for registeration. The fields of the SignupForm are 'username', 'first_name', 'last_name', 'email', 'student_ID', 'CBNU_PW',. I want to get these data on the registration page and save 'student_ID', 'CBNU_PW', in UserProfile. How can I get all the data on the registration page and save 'student_ID', 'CBNU_PW', data in UserProfile? I don't know how to make this in my code. This is my code. This is view.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.generic import TemplateView, CreateView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import SignUpForm from django.urls import reverse_lazy from .models import * from django.contrib import messages class HomeView(TemplateView): template_name = 'common/home.html' class DashboardView(TemplateView): template_name = 'common/dashboard.html' login_url = reverse_lazy('login') # class SignUpView(CreateView): # form_class = SignUpForm # success_url = reverse_lazy('home') # template_name = 'common/register.html' def register(request): form = SignUpForm() if request.method=='POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') return redirect('login') context = {'form': form} return render(request, 'common/register.html', context) from django.contrib.auth import authenticate, login def user_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('dashboard') else: return render(request, 'common/login.html', {'error' : 'username or password is incorrect.'}) else: … -
WebSocket connection failed (Django channels)
I'm trying to establish a websocket connection, however, I'm getting this error: WebSocket connection to 'wss://oasis.yiaap.com/ws/question/aaass-bc6f6f2e-4a96-4174-a8dd-a3b8f03645a7/' failed: I think everything is set up correctly. #routes.py websocket_urlpatterns = [ #re_path(r"ws/questions/", consumers.QuestionsConsumer.as_asgi()), path("ws/question/<question_slug>/", consumers.QuestionConsumer.as_asgi()) ] #consumers.py class QuestionConsumer(AsyncJsonWebsocketConsumer): async def connect(self): #print("DEBUG") self.question_slug = self.scope['url_route']['kwargs']['question_slug'] self.room_name = self.question_slug self.room_group_name = 'question_%s' % self.room_name # In order to detect who is the owner of the room # We'll setup the user # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() # Check if the question exists in the database otherwise close the connection # and send a message says 'question not found' so client can act on it is_questions_exists = await questions_exists(question_slug=self.question_slug) if is_questions_exists == False: await self.send_json({"message": "question_not_found"}) await self.close() await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def disconnect(self, close_code): user_id = self.scope["client"][1] owner_user_id = cache.get(f"{self.room_name}_owner") if user_id == owner_user_id: # Check if the user is the question owner then delete the question from database await delete_question(self.question_slug) cache.delete_pattern(f"{self.room_name}_owner") # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive answer from WebSocket async def receive_json(self, content): answer = content.get('answer', None) is_owner = content.get("is_owner", None) if answer: # Send answer to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'question_answer', 'answer': answer } … -
Tagulous - Displaying Posts based on filtering of self assigned tags
I have created a posts list where users can simply create a post, upload a photo and similar to StackOverflow, they can assign "Tags" to their post to categorise their post (I am using Tagulous library to power the tags feature of my application) At the moment users can assign tags to their Post. However, what I am wanting to achieve is the following: When a user creates a Post in a specific tag, I want to filter the overall Posts view, based on the past tags they have assigned to their previous posts. E.g. If User A assigns a tag called "Winter" to their Post, after submitting their post, they will see any other Posts on their Post Feed which are relevant to the "Winter" tag. If in the future, they decide to assign one or more other tags to any future posts they create, those posts sharing the same tag name will also appear on their Post Feed. In a nutshell, for every one tag which the user self assigns to any future post, they will begin to see Posts of other users who are using the same tag within their posts. Where I am at, at the … -
unsupported operand type(s) for *: 'NoneType' and 'decimal.Decimal'
I am trying to calculate the subtotal, VAT and Total for creating an invoice. I`ve got an error unsupported operand type(s) for *: 'NoneType' and 'decimal.Decimal' models.py class InvoiceLine(models.Model): TAX_RATE = ( (0, '20% (VAT on Expenses)'), (1, '5% (VAT on Expenses)'), (2, 'EC Aquisitions (20%)'), (3, 'EC Aquisitions (Zero Rated)'), (4, 'Exempt Expenses'), (5, 'No VAT'), (6, 'Reverse Charge Expenses (20%)'), (7, 'Zero Rated Expenses'), ) invoice = models.ForeignKey(Invoice,related_name="has_lines",on_delete=models.CASCADE, blank=True, null=True, unique=False) invoice_item = models.CharField(max_length=100, verbose_name="Line") tax_rate = models.IntegerField(choices=TAX_RATE,default=0, blank=True, null=True) total = models.CharField(max_length=250, null=True, blank=True) description = models.CharField(max_length=100, blank=True, null=True) unit_price_excl_tax = models.DecimalField(max_digits=8,decimal_places=2, null=True, blank=True) quantity = models.DecimalField(max_digits=8,decimal_places=2,default=1, null=True, blank=True) unit_price = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) vat = models.CharField(max_length=250, null=True, blank=True) def subtotal(self): subtotal = Decimal(str(self.unit_price * self.quantity)) return subtotal.quantize(Decimal('0.01')) def __unicode__(self): return self.description subtotal will calculate the unit price X quantity but give me an unsupported operand type error. Then, I`ll have the total_lines and VAT by adding 20%. Can I just calculate them using? def total(self): total = Decimal(str(self.subtotal * (self.tax_rate/100)+ (self.tax_rate/100))) return total.quantize(Decimal('0.01')) -
OSError at / SavedModel file does not exist at: model.h5/{saved_model.pbtxt|saved_model.pb}
model=load_model("cat_dog_model.h5") Anybody help to overcome this error while adding a saved neural network model in Django. -
django clean field model form
it is necessary to clean the fields in views or just in forms.py? how does the clean method work in modelform? class Book(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyField(Author) class BookForm(ModelForm): class Meta: model = Book fields = ['name', 'authors'] def clean_name(self): pass def create(request): if request.method == 'post': form = Bookform(request.POST) if form.is_valid(): #clean field -
__init__() takes 1 positional argument but 2 were given type error
I am currently using Django and python to create a web app to take meter readings for my company. I am receiving this error (Title) and I don't know what is causing it. I have Urls.py: urlpatterns = [ #Operational URLS path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path("",include("accounts.urls")), path('home/' , views.home, name='home'), #Complexes #AVONLEA path('avn', views.AvonleaView, name='Avonlea'), path('cavn', views.currentavonleas, name='currentAvonleas'), path('Avonleacsv', views.Avonleacsv, name='Avonleacsv'), path('meter_readings/avonlea/<int:avonleas_pk>', views.viewavonlea, name='viewavonlea' ), path('meter_readings/avonlea/<int:avonleas_pk>/delete', views.deleteavonlea, name='deleteavonlea' ), Views.py from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from .forms import AvonleaForm from .models import AvonleaClass from django.contrib import messages from django.views import View #Operational def home(request): return render(request, 'meter_readings/home.html' ) # Complexes #AVONLEA # # # class AvonleaView( View): def get(self,request): created_nums= AvonleaClass.objects.all().values('unitNumber') Aprev = AvonleaClass.objects.all().order_by('-unitDateEntered') previousReading = Aprev[1].newReading # created_nums= AvonleaClass.objects.all() print(created_nums , previousReading) created_nums =[int(i['unitNumber']) for i in created_nums] print(created_nums , previousReading) form = AvonleaForm() return render(request,"meter_readings/avonlea.html",{'form':form , 'created_nums':created_nums , 'name':name, 'previousReading' : previousReading }) def post(self,request): created_nums= AvonleaClass.objects.all().values_list('unitNumber') print(created_nums) form = AvonleaForm(request.POST) if form.is_valid(): form.save() return redirect('unt-url' , name ) messages.success(request , 'creates successfully ') else: return render(request, 'meter_readings/avonlea.html', {'form': form , created_nums:created_nums }) def currentavonleas(request): avonleas = AvonleaClass.objects.all() return render(request, 'meter_readings/currentavonleas.html', {'avonleas':avonleas}) def viewavonlea(request, avonleas_pk): avonlea = get_object_or_404(AvonleaClass, pk=avonleas_pk) if request.method == 'GET': … -
Wrong STATIC_URL when trying to deploy Django React app to Heroku with AWS S3
I have set up an S3 bucket for static files. Everything is working locally, but when I try to deploy the app the STATIC_URL is always overwritten and using the static path on the same page. production.py import os from dotenv import load_dotenv from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent.parent # Load dotenv load_dotenv() DEBUG = os.getenv('DEBUG_VALUE') SECRET_KEY = os.getenv("SECRET_KEY") USE_S3 = os.getenv('USE_S3') BUCKET_URL = os.getenv('REACT_APP_BUCKET_URL') # Server is running in production if DEBUG == 'FALSE': # HTTPS settings CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True # HSTS settings SECURE_HSTS_SECONDS = 31536000 # 1 year SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True # S3 bucket config if USE_S3 == 'TRUE': MEDIA_URL = '/media/' STATIC_URL = BUCKET_URL + '/static/' MEDIA_ROOT = BUCKET_URL + '/static/images/' AWS_ACCESS_KEY_ID = os.getenv('ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = os.getenv('CUSTOM_DOMAIN') AWS_LOCATION = 'static' #AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' else: MEDIA_URL = '/media/' STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR / 'public' / 'static' / 'images') -
django formtools initial data via GET parameter
I'm using django-formtools to create a form wizard. I want to pre-fill the first part of the form using get-parameter. First I validate the GET data with a regular django form. form.py class MiniConfiguratorForm(forms.Form): width = forms.IntegerField(min_value=MIN_WIDTH, max_value=MAX_WIDTH, initial=25, label=_('width')) height = forms.IntegerField(min_value=MIN_HEIGHT, max_value=MAX_HEIGHT, initial=25, label=_('height')) amount = forms.IntegerField(min_value=MIN_QUANTITY, max_value=MAX_QUANTITY, initial=1, label=_('amount')) class ConfiguratorStep1(forms.Form): # ... width = forms.IntegerField(widget=forms.NumberInput(), min_value=MIN_WIDTH, max_value=MAX_WIDTH, initial=25, label=_('width')) height = forms.IntegerField(widget=forms.NumberInput(), min_value=MIN_HEIGHT, max_value=MAX_HEIGHT, initial=25, label=_('height')) amount = forms.IntegerField(widget=forms.NumberInput(), min_value=MIN_QUANTITY, max_value=MAX_QUANTITY, initial=1, label=_('amount')) class ConfiguratorStep2(forms.Form): name = forms.CharField(max_length=100, required=True) phone = forms.CharField(max_length=100) email = forms.EmailField(required=True) views.py class ConfiguratorWizardView(SessionWizardView): template_name = "www/configurator/configurator.html" form_list = [ConfiguratorStep1, ConfiguratorStep2] def done(self, form_list, **kwargs): return render(self.request, 'www/configurator/done.html', { 'form_data': [form.cleaned_data for form in form_list] }) def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be reset before rendering the first step """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first mini_configurator = MiniConfiguratorForm(data=request.GET) init_data = None if mini_configurator.is_valid(): init_data = { 'width': '35', 'height': '33', 'amount': '17', } print("valid") else: print("invalid haxx0r") return … -
OSError: cannot load library 'C:\Program Files\R\R-4.1.ind\R.dll': error 0x7e
I am getting an error when using openrlib.py from rpy2. The specific thing I am trying to use it to import R, but it always throws an error when trying to open R.dll. rlib = ffi.dlopen('C:\Program Files\R\R-4.1.0\bin\x64\R.dll') OSError: cannot load library 'C:\Program Files\R\R-4.1.ind\R.dll': error 0x7e Above is my VSC terminal output. I do not understand why its changing "4.1.0" to "4.1.ind" but that is definitely part of the problem. Ill link a screenshot of the code. Things I have tried: Reinstalling R Reinstalling rpy2 setting the variable that used in ffi.dlopen() to the exact path my computer stores R.dll in following some other stack overflow solutions Any help would be appreciated! Image of code segment Image of terminal output -
I want a detailed explanation of each line in Django
from django.http import HttpResponse from django.shortcuts import redirect def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') else: return view_func(request, *args, **kwargs) return wrapper_func -
User account delete in django's rest
I want create view which can deactivation user's account. when i create view and send delete request i have error - > "detail": "You do not have permission to perform this action.". i have authenticated permissionn but i am login in my account. this is code -> class DeleteAccount(generics.RetrieveUpdateDestroyAPIView): serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] def delete(self, request, *args, **kwargs): user=self.request.user user.delete() return Response({"result":"user delete"}) -
switching to postgresql causes "django.contrib.auth.models.User.DoesNotExist: User matching query does not exist."
I checked similar questions but I could not find a solution. I am using django-rest-framework in my project and when it was connected to sqlitedb I had no issue. But when I switched to postgresql db I am getting that error. I successfully connected to databse and I created a super user. "is_superuser" and "is_staff" are true. I am sending a delete request, which was working before. Here is its view: @api_view(['DELETE']) @permission_classes([IsAdminUser]) def deleteProduct(request,pk): user = request.user print("userrrrrr",user) product=Product.objects.get(id=pk) print("product",product) product.delete() return Response("Product deleted") print(user) and print(product) are not printing anything, I think @permission_classes([IsAdminUser]) validation is not passing. I cannot figure out why it was working before. Here is the error message: File "/home/my_desk/anaconda3/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/my_desk/anaconda3/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/my_desk/anaconda3/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/my_desk/anaconda3/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/my_desk/anaconda3/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/my_desk/anaconda3/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/my_desk/anaconda3/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/my_desk/anaconda3/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/my_desk/anaconda3/lib/python3.8/site-packages/rest_framework/decorators.py", line 50, in handler return func(*args, **kwargs) File "/home/my_desk/Documents/projects/next.js/django-server-bingology/bingologyserver/base/views/user_views.py", line 98, … -
Why widget EmailInput style doesn't apply
I'm trying to style the django forms, I could apply the class to the TextInputs with widget but for the email and password it doesn't apply. Any idea why? Also, how can I delete the text above password? The password requisites, it isn't help_text forms.py class SignupForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['email', 'first_name', 'last_name', 'password1', 'password2'] widgets = { 'email': forms.EmailInput(attrs={'class': 'forms-group__input'}), 'first_name': forms.TextInput(attrs={'class': 'forms-group__input'}), 'last_name': forms.TextInput(attrs={'class': 'forms-group__input'}), 'password1': forms.PasswordInput(attrs={'class': 'forms-group__input'}), 'password2': forms.PasswordInput(attrs={'class': 'forms-group__input'}), } forms.html <form class="forms-group__form" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} {{ field.errors }} <br> <div class="forms-group__input-field"> <label class="forms-group__label">{{ field.label_tag }}</label><br> {{ field }}<br> {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} <div class="forms-group__button-div"><input class="button submit-button forms-group__button" type="submit" value="Update Profile"></div> </form> -
Overwrite and style Django default message
I created a form in order to change the user's password. There are messages displayed when there are errors on the form. But I would like to overwrite this. For what I found online is that I can overwrite message in 5 categories (debug, info, success, warning, error). But I think that we lose informations for example : First error example when I make a mistake on the current password. Second error example when I choose a common password. So if I change the message in the case of an error I would loose a lot of information (what is the error the current password or the new password). My question is how can I a change specific error message in django ? PS : How can I a change the language now the text is in english despite the fact that in settings there is USE_I18N = TRUE -
Why form.is_valid() is always false in UserCreationForm, Django
I'm making registration in Django. When I access to register/ page, everything shows fine and there isn't any error message. But, the user that I register doesn't save in database in Django (can't find the user on the admin page). Also, the redirect doesn't work. So, I think 'form.is_valid() is always false' is the problem. What is the problem? How can I solve this? This is view.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.generic import TemplateView, CreateView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import SignUpForm from django.urls import reverse_lazy from .models import * from django.contrib import messages class HomeView(TemplateView): template_name = 'common/home.html' class DashboardView(TemplateView): template_name = 'common/dashboard.html' login_url = reverse_lazy('login') # class SignUpView(CreateView): # form_class = SignUpForm # success_url = reverse_lazy('home') # template_name = 'common/register.html' def register(request): form = SignUpForm() if request.method=='POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') return redirect('login') context = {'form': form} return render(request, 'common/register.html', context) from django.contrib.auth import authenticate, login def user_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('dashboard') else: return render(request, 'common/login.html', {'error' : 'username or password is incorrect.'}) else: return render(request, … -
Django admin/ return 404
Starting development server at http://127.0.0.1:8000/ Not Found: /admin/ [30/May/2021 20:33:56] "GET /admin/ HTTP/1.1" 404 2097 project/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('marketability.mkbl_urls')), path('admin/', admin.site.urls), path(r'^ckeditor/', include('ckeditor_uploader.urls')), ] variants path(r'admin/', admin.site.urls), and path(r'^admin/', admin.site.urls), don't works too. project/marketability/mkbl_urls.py from django.urls import path from django.views.generic.base import RedirectView, TemplateView from . import views app_name = 'marketability' handler404 = 'marketability.views.handler404' urlpatterns = [ path('', views.home, name="home"), path('<slug:cat_>/', views.page_Category_Main, name='cat'), path('<slug:cat_>/<slug:product_>', views.page_Product, name='product'), path('al_about.html', views.about, name="about"), path('al_home.html', views.home, name="home"), path('search_all.html', views.search_all, name="doorway"), path('robots.txt', TemplateView.as_view(template_name="robots.txt", content_type="text/plain")), path('sitemap.xml', TemplateView.as_view(template_name="sitemap.xml", content_type="text/xml")), path('favicon.ico', RedirectView.as_view(url='/static/marketability/favicon.ico', permanent=True)), ] project/marketability/admin.py from django.contrib import admin from .models import TxtHow, TxtRatings # Register your models here. admin.site.register(TxtHow) admin.site.register(TxtRatings) project/settings.py .... NSTALLED_APPS = [ 'ckeditor', 'ckeditor_uploader', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'marketability', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR + '/marketability/patterns'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] .... superuser has created So, i don't see any deviations from Django Documentation. How to solve it? thks -
Django middleware to time page load speed computations
I'm trying to define a middleware to time page load speed and inject it into the context to display on my homepage. I've written this middleware and it gives me the page load time in milliseconds but I don't think it's accurate. Is there a better way of doing this? Heres the code: import time class StatsMiddleware: def __init__(self, get_response): self.get_response = get_response self.start_time = time.time() def __call__(self, request): response = self.get_response(request) return response def process_template_response(self, request, response): duration = time.time() - self.start_time response.context_data['pageload'] = round(duration * 1000, 2) return response -
haarcascade_frontalface_deflult.xml not working properly on live Django website on cPanel
I get the haarcascade_frontalface_deflult.xml file from cPanel the file are present there but it cannot detect the face its working locally fine but when I upload it on cPanel it did not detect faces properly face_detector = cv2.CascadeClassifier('/home/khblpkn3ru9o/public_html/media/haarcascade_frontalface_default.xml') i also try this cv2.CascadeClassifier('http://theangrynerds.com/media/haarcascade_frontalface_default.xml') you can check file http://www.theangrynerds.com/media/haarcascade_frontalface_default.xml my complete module code here def hello(request): if request.method == "POST": F_name = request.POST['name'] user_video = request.FILES['vide'] videoSave = videoStore.objects.create(User=User.objects.get(id=request.user.pk) , videoFile = user_video) get_path_video = videoStore.objects.get(pk = videoSave.pk) accurate_path = "http://theangrynerds.com/media/" + str(get_path_video.videoFile) faceCount = FaceName.objects.all().count() face_id = faceCount + 1 count =0 video = cv2.VideoCapture(accurate_path) # Detect object in video stream using Haarcascade Frontal Face face_detector = cv2.CascadeClassifier('/home/khblpkn3ru9o/public_html/media/haarcascade_frontalface_default.xml') while True: # Capture video frame cc, image_frame = video.read() if cc == False: break # Convert frame to grayscale gray = cv2.cvtColor(image_frame, cv2.COLOR_BGR2GRAY) # Detect frames of different sizes, list of faces rectangles faces = face_detector.detectMultiScale(gray, 1.3, 5) # Loops for each faces for (x,y,w,h) in faces: # Crop the image frame into rectangle FaceName.objects.create(User=User.objects.get(id=request.user.pk) , name = F_name , ids = face_id) # cv2.rectangle(image_frame, (x,y), (x+w,y+h), (255,0,0), 2) count += 1 has = cv2.imwrite("/home/khblpkn3ru9o/public_html/media/" + str(request.user.username) + "." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w]) c = str(request.user.username)+"." …