Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No such File or directory "optimize-images"
I am using optimize-images (PyPi) library for optimizing images in a folder. (which is generated dynamically for every users). (Django Project) I have installed optimize-images using pip. Since, its a long running task i am using celery to first import the images to a directory and then running a command (optimize-images) on that directory for compressing all images. os.chdir(r'/home/django/image-io/accounts/'+dynamic_user+'/optimized/') cwd = os.getcwd() print("CURENT WORKING DIRECTORY") print(cwd) p=subprocess.Popen([r"optimize-images", cwd]) p.wait() where , dynamic_user is a user_name (string) optimized/ is the directory where all images are stored. I am not able to understand , why it says this error "No such file or directory: 'optimize-images'" Since, optimize-images is a command line utility and not a folder/file. Any help would be highly appreaciated. Here's the stack trace for err:-[2021-07-03 06:26:40,107: ERROR/ForkPoolWorker-2] Task home.tasks.product_import[c1a31047-5a11-493e-8e1b-fbc282e74a81] raised unexpected: FileNotFoundError(2, 'No such file or directory') Traceback (most recent call last): File "/home/django/image-io/env/lib/python3.8/site-packages/celery/app/trace.py", line 450, in trace_task R = retval = fun(*args, **kwargs) File "/home/django/image-io/env/lib/python3.8/site-packages/celery/app/trace.py", line 731, in __protected_call__ return self.run(*args, **kwargs) File "/home/django/image-io/home/tasks.py", line 185, in product_import p=subprocess.Popen([r"optimize-images", cwd]) File "/usr/lib/python3.8/subprocess.py", line 858, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/usr/lib/python3.8/subprocess.py", line 1704, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: … -
Implement multi user login in Nuxt
I am using Nuxt 2.15 and Django 3.2.3. I would want to implement a multi user login with Nuxt. In the django project, I have an single model with an option of either a student or a teacher. On the frontend (NUXT), user can register as either a student or a teacher. When it gets to the login, if a user is a teacher, it should be directed to a teachers and if a student, to student's page. I would be grateful with any assistance on the latter case. -
Heroku application error (Django) deploy with github. at=error code=H10 desc="App crashed" dyno= connect= service= status=503 bytes= protocol=https
I am an absolute beginner to Django and python and created a website from Django. I am trying to host my website on Heroku and deploy it with GitHub but showing an application error. I am finding a way to fix this. Please help me. My github project :- Pyshop and heroku project: pysho. It is showing an application error. When I run the command: Heroku logs --tail --app pysho it shows: » Warning: Heroku update available from 7.53.0 to 7.54.1. 2021-07-03T05:04:53.682795+00:00 app[web.1]: self._wrapped = Settings(settings_module) 2021-07-03T05:04:53.682796+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ 2021-07-03T05:04:53.682796+00:00 app[web.1]: mod = importlib.import_module(self.SETTINGS_MODULE) 2021-07-03T05:04:53.682796+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2021-07-03T05:04:53.682797+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-07-03T05:04:53.682797+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-07-03T05:04:53.682797+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-07-03T05:04:53.682798+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked 2021-07-03T05:04:53.682798+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-07-03T05:04:53.682798+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-07-03T05:04:53.682799+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-07-03T05:04:53.682799+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked 2021-07-03T05:04:53.682799+00:00 app[web.1]: ModuleNotFoundError: No module named 'ebgymmie' 2021-07-03T05:04:53.683086+00:00 app[web.1]: [2021-07-03 05:04:53 +0000] [7] [INFO] Worker exiting (pid: 7) 2021-07-03T05:04:53.777109+00:00 app[web.1]: [2021-07-03 05:04:53 +0000] [8] … -
having error (1054, "Unknown column 'order_product.id' in 'field list'") in django
I create the models file with inspectdb, but it gives an error when I want to show it in Admin panel: (1054, "Unknown column 'order_product.id' in 'field list'") In my searches, I realized I had to add a primary key to each of the models, but nothing happened when I did that. Here is my code: models.py class OrderProduct(models.Model): order = models.ForeignKey('Orders', models.DO_NOTHING) product = models.ForeignKey('Products', models.DO_NOTHING) attribute = models.ForeignKey(Attributes, models.DO_NOTHING, blank=True, null=True) color = models.ForeignKey(Colors, models.DO_NOTHING, blank=True, null=True) price = models.IntegerField(blank=True, null=True) attribute_price_differ = models.IntegerField(blank=True, null=True) attribute_price = models.IntegerField(blank=True, null=True) number = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'order_product' class Orders(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey('Users', models.DO_NOTHING) price = models.IntegerField() weight = models.IntegerField() coupon = models.ForeignKey(Coupons, models.DO_NOTHING, blank=True, null=True) status = models.IntegerField() process_status = models.IntegerField() code = models.CharField(max_length=255) hash = models.CharField(max_length=255) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'orders' #admin.py @admin.register(OrderProduct) class PostAdmin(admin.ModelAdmin): pass -
Django database routers - how do you test them, especially for migrations?
I've read the documentation on database routers in Django 2.2. I more or less understand the concept - including keeping certain tables together - except that it seems somewhat tricky to do in practice. I have defined the routers in settings: DATABASES = { "default": { "ENGINE": constants.POSTGRES_ENGINE, "NAME": constants.SYSDBNAME, ... }, "userdb": { "ENGINE": constants.POSTGRES_ENGINE, "NAME": constants.USERDBNAME, } DATABASE_ROUTERS = [ #the user database - userdb - which gets the auths and user-related stuff "bme.websec.database_routers.UserdbRouter", #the default database - sysdb "bme.websec.database_routers.SysdbMigrateRouter", ] Ideally I would use unit tests to submit all my models one by one to the routers' allow_migrate, db_for_read, db_for_write methods, and for each call, verify that I got the expected test results. But is there a way to do that? I suppose I can use models = django.apps.apps.get_models( include_auto_created=True, include_swapped=True ) and then drive those methods calls from unittests. But to take just def allow_migrate(self, db, app_label, model_name=None, **hints): How do I know when to have **hints and whether model_name is always provided or not? And most importantly, how do I simulate what the master router ultimately decides as stated in the doc (my emphasis)? Among other things, it doesn't rely on just one router, it … -
Multiple QuerySet to another Model
I'm writing the following code to search about category in profile model using Django ninja framework, if i retrieve only the fields in profile all query return, but when i need to get the username from the user model only one record return from the loop. profile.py class Profile(models.Model): SERVICEPROVIDER = 'service_provider' CUSTOMER = 'customer' user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') conf_password = models.CharField(max_length= 124) category = models.CharField(max_length= 80, blank=True, null=True) click = models.IntegerField(blank=True, default=0) date_clicked = models.DateTimeField(auto_now_add=True, blank=True,null=True) image_path = models.ImageField(upload_to='user_uploads/', blank=True) role = models.CharField(max_length=100, choices=[ (SERVICEPROVIDER, SERVICEPROVIDER), (CUSTOMER, CUSTOMER),]) profile_info = models.JSONField(blank=True, null=True) def __str__(self): return f'{self.user.username}' auth.py @auth.get("/search/{category}", auth=None, response={200: searchSchemaout, 404: MessageOut}) def search(request, category:str): profile = Profile.objects.filter(category__icontains=category).values() for i in range(len(profile)): user = get_object_or_404(User,id=profile[i]['id']) return 200, { "user": user, "profile": profile[i] } auth.py Schema class UserSchemaOut(Schema): username: str class profileSchemaout(Schema): role: str category: str class searchSchemaout(Schema): user: UserSchemaOut profile: profileSchemaout The result: { "user": { "username": "ahmed" }, "profile": { "role": "service_provider", "category": "doors" } } -
"Invalid data. Expected a dictionary, but got property."
Before this issue, when I tried to use request.data, it showed me an error saying attribute doesn't exist on WSGI Serializer class EmployeeSerializer(serializers.Serializer): # students = serializers.RelatedField(many=True, read_only=True) user = serializers.CharField(max_length=30) id = serializers.CharField(max_length=30) students = StudentSerializer(many=True,read_only=True) first_name = serializers.CharField() last_name = serializers.CharField(max_length=30) designation = serializers.CharField(max_length=40) # Data will be generally in JSON format def create(self, validated_data): # Student_det = validated_data.pop('stud_det') """ Create and return a new `Employee` instance, given the validated data. """ emp = Employee.objects.create(**validated_data) return emp def update(self, instance, validated_data): """ Update and return an existing `Employee` instance, given the validated data. """ instance.title = validated_data.get('title', instance.title) instance.code = validated_data.get('code', instance.code) instance.linenos = validated_data.get('linenos', instance.linenos) instance.language = validated_data.get('language', instance.language) instance.style = validated_data.get('style', instance.style) instance.save() return instance Serializer view @csrf_exempt def employee_list(request): if request.method == 'GET': employees = Employee.objects.all() user = User.objects.all() serializer = EmployeeSerializer(employees, many=True) serializer2 = UserSerializer(user, many=True) return JsonResponse(serializer.data, safe=False) if request.method == "POST": data_ = Request.data print(data_) serializer = EmployeeSerializer(data=data_) # serializer.data['user'] = user if serializer.is_valid(): print(serializer.data['user']) serializer.save() return JsonResponse(serializer.data, status=status.HTTP_201_CREATED) else: return JsonResponse(serializer.errors) Response trying to do an API post-call and what I am receiving is this, showing data is an attribute { "non_field_errors": [ "Invalid data. Expected a dictionary, but got property." … -
TypeError : verificationview() got an unexpected keyword argument 'uidb64' in django while email verification
I am trying to add email verification in my django app but when I click on the link which I get on email it gives out an error saying it got and unexpected argument views.py def sendmail(request): emailaddress=request.POST['email'] username=request.POST['username'] password=request.POST['password'] user = User.objects.create_user(email=emailaddress,username=username,password=password) user.is_active=False user.save() uidb64= urlsafe_base64_encode(force_bytes(user.pk)) domain = get_current_site(request).domain link= reverse('activate',kwargs={'uidb64':uidb64,'token':token_generator.make_token(user)}) activate_url='http://'+domain+link subject = 'Activate your Account' message = 'Hi' + user.username + "Please use the link for verification\n" + activate_url email_from = settings.EMAIL_HOST_USER recipient_list = [emailaddress] send_mail( subject, message, email_from, recipient_list ) messages.add_message(request,messages.SUCCESS,"Email sent") return render(request,'index.html') def verificationview(View): def get(self, request, uidb64, token): messages.add_message(request,messages.SUCCESS,"Account Activated") return redirect('/') utils.py class AppTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (text_type(user.is_active)+text_type(user.pk)+text_type(timestamp)) token_generator = AppTokenGenerator() urls.py urlpatterns = [ path('',views.loadpage), path('submit/',views.sendmail), path('activate/<uidb64>/<token>',views.verificationview,name='activate'), ] -
WHY request.GET.get('key') have two results?
I am using django for website. I want to send data from veiws.py to search_test.html. In terminal, they operate correctly. but in search_test.html, the data is none. why they have two different result? I used ajax to send input data to views.py. in views.py, I used request.GET.get('keyinput') for inputText variable using. here is my source code. please help me... search_test.html ... <form method = "GET" action = "{% url 'video:search' %} " id ="goSubmit"> <input name = "post_search_keyword" id = "post_search_keyword"> <button type = "submit" >submit</button> </form> <script> var oldVal var goSubmit = document.goSubmit; $("#post_search_keyword").on("propertychange change keyup paste input", function() { var currentVal = $(this).val(); if(currentVal == oldVal) { return; } oldVal = currentVal; var allData = { "keyinput": currentVal }; $.ajax({ url:"{% url 'video:search' %}", type:'GET', dataType:'json', data:allData }) aaa = "{{data}}" console.log(aaa) }); </script> <script> $(function () { //화면 다 뜨면 시작 var a = "{{restaurant|safe}}"; var array = a.split(","); console.log(array); var searchSource = array; // 배열 형태로 $("#post_search_keyword").autocomplete({ //오토 컴플릿트 시작 source: searchSource, // source 는 자동 완성 대상 select: function (event, ui) { //아이템 선택시 console.log(ui.item); }, focus: function (event, ui) { //포커스 가면 return false;//한글 에러 잡기용도로 사용됨 }, minLength: 1,// 최소 글자수 autoFocus: true, … -
React js Trying to Fetch data from my Django backend with state but I have multiple state obj
So here's the problem. I have multiple states that are being changed in my form, but I also want to change the value of all the key's when I fetch the data. How do I do this? Here's my code. class UserInfo extends Component { state = { userInfo: { birthPlace: "", bio: "", school: "", firstName: "", lastName: "", occupation: "", what_are_you_seeking_on_site: "", age: "", } } handleSubmit = (userInfo) => { //Fix backEnd where UserFields are saved because you only want one of the users not all fetch('http://localhost:8000/allUsers',{ method: "POST", headers: { 'content-type': "application/json" }, body: JSON.stringify(userInfo) }) .then(res => res.json()) .then(data => { this.setState({ }) }) } handleChange = (event) => { this.setState({ what_are_you_seeking_on_site: event.target.value }) } render() { const {classes} = this.props return ( <div> <Container component="main" maxWidth="xs"> <CssBaseline /> <div className={classes.paper}> <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Sign up </Typography> <form className={classes.form} onSubmit={this.handleSubmit} noValidate> <Grid container spacing={2}> <Grid item xs={12} sm={12}> <TextField autoComplete="fname" name="firstName" variant="outlined" required fullWidth id="firstName" label="First Name" autoFocus value={this.state.firstName} onChange={e => { this.setState({ firstName: e.target.value }) }} /> </Grid> <Grid item xs={12}> <TextField variant="outlined" required fullWidth id="lastName" label="Last Name" name="lastName" value={this.state.lastName} onChange={e => { this.setState({ lastName: e.target.value }) }} /> … -
Django rest framework access related custom fields
I want to sum all the Bars progress value in the FooSerializer The code order is FooSerializer.get_progress -> BarSerializer , I can't access BarSerializer.progess in FooSerializer. from django.db import models from rest_framework import serializers from rest_framework.viewsets import ModelViewSet class Foo(models.Model): name = models.CharField(max_length=180) class Bar(models.Model): foo = models.ForeignKey(Foo, related_name='bars', on_delete=models.CASCADE) class BarSerializer(serializers.ModelSerializer): progress = serializers.SerializerMethodField() def get_progress(self, instance): return 100 # some computed value class FooSerializer(serializers.ModelSerializer): bars = BarSerializer(many=True) progress = serializers.SerializerMethodField() def get_progress(self, instance): # how to access barSerializer's progress ? total = sum(x.progress for x in instance.bars) return total -
Getting 403 Forbidden error on post requests when serving django app on Amazon cloud front through heroku
I have a django app deployed in heroku, which was working previously, however after adding the Edge add-on, which serves your static files from Amazon cloudfront for caching, all of my post requests are getting 403 errors. I do pass the csrf token correctly, as my post requests still work when not served from cloudfront, but on cloudfront I am getting the error that the CSRF Verification failed It also mentions that the referer header is missing, however I can see referer specified in the request headers in the network tab of the developer tools. Any idea what I am missing here? -
It is possible to use spotify API to everyone listen a song?
I'm plannig to do a chat app with djano and django-channels that will allow me to run te application asyncronous, I want to implement the spotify API for everyone in the room listen to some music, it is possible to do this in an async application? -
Django Q task result decrypt
Can somehow tell me how to decrypt the result in django_q_task table when the task failed I check the documentation and still cant get it https://django-q.readthedocs.io/en/latest/tasks.html -
Django REST Api Security Architecture
My sites architecture. Both components are hosted on AWS via elasticbeanstalk. Frontend: React gets data via API Endpoints served from backend Backend: Django REST Framework I want to restrict api access such that: only the frontend can grab data from the REST API, some data is public to anyone on the site, some only accessible to signed in users whitelisted developers can access data from the REST API such that they can develop the frontend display of that data No other machine, site, service, person, alien can access the REST API unless we know about it! Willing to research and learn required to implement a solution like this, just would like to have some guidance as I am a young Padawan. -
Django rest framework: Social Auth + JWT: Which third party packages are preferred to achieve this
I am developing a mobile application for which Django rest framework provides the api. I want a login system with username+password and google and facebook options I have gone through the https://www.django-rest-framework.org/api-guide/authentication/ I mentions many third party packages in the end. Can someone guide me, how to achieve my goal using which combination of third party packages. I have used django-allauth previously but it has no rest support. -
Django can't able to save multichoice field (checkbox) data in database
Am trying to save data from multi choice field to database but it doesn't get saved in database instead it shows all many to many relationship data. Models.py class masterList(models.Model): mastername=models.CharField(max_length=150) unit=models.ForeignKey(unit, on_delete=models.CASCADE) status =models.IntegerField() def __str__(self): return self.mastername class subCategory(models.Model): sub_category_name=models.CharField(max_length=200) category=models.ForeignKey(category,on_delete=models.CASCADE) masters= models.ManyToManyField(masterList) status=models.IntegerField() def __str__(self): return str(self.sub_category_name) Forms.py class subCategoryForm(forms.ModelForm): the_choices = forms.ModelMultipleChoiceField(queryset=masterList.objects.all(), required=False, widget=forms.CheckboxSelectMultiple) class Meta: model=subCategory fields=[ "category", "sub_category_name", "status", ] Views.py def add_sub_category(request): context={} form = subCategoryForm(request.POST) if form.is_valid(): form.save() context = {'form':form} return render(request,'add_sub_category.html',context) I think form.save_m2m() will do this job but i couldn't understand how it works. Thanks in advance :) -
Django 3.x - Custom Error Page is showing a 500 when it should be a 404
For a CS50 project I'm working on with a wiki page, I'm trying to send the right custom 404 error when a user types a page that doesn't exist in wiki/TITLE however when I type a missing page, Django throws a 500 instead of a 404. Is this a common error or did I make my error message wrong? Debug is set to False and Allowed Hosts is configured to ['*'] in settings: Here's my custom error handlers in views.py: def error_404(request, exception): context = {} response = render(request, 'encyclopedia/error_404.html', context=context) response.status_code = 404 return response def error_500(request): context = {} response = render(request, 'encyclopedia/error_500.html', context=context) response.status_code = 500 return response Here's how they are in wiki/urls.py: from django.contrib import admin from django.urls import include, path from django.conf.urls import handler404, handler500 urlpatterns = [ path('admin/', admin.site.urls), path('', include("encyclopedia.urls")), ] handler404 = "encyclopedia.views.error_404" handler500 = "encyclopedia.views.error_500" Here's what the terminal shows (my styles.css is throwing a 404 for some reason but I haven't changed anything there...that's a separate issue): -
How do I get Javascript Handler to recognize dynamically added forms via Formsets?
So after about 3 days of completely being demoralized over JQuery...come to figure out that there is an issue with Django formsets whereby if there are extra forms defined prior to the page load...all is right with the world. If the user clicks to add forms....or the add button essentially...the dynamically loaded forms are not captured by Javascript or Jquery. The data gets processed...but I am unable to manipulate the dynamically generated forms via Javascript or JQuery. I tried to add event listeners programmatically but that didn't seem to help. Essentially...I have a link that is generated by jquery.formset.js. It looks like... <a class="delete-row-budget" href="javascript:void(0)">Del</a> It gets generated fine...but the issue is that it's invisible to JQuery and Javascript. Has anyone else encountered this? I did come across this issue which sounds identical but have not been able to get this solution to work....https://stackoverflow.com/questions/61036000/how-to-handle-javascript-event-inside-a-inlineformset-factory-with-formset-media Thanks in advance for any thoughts or ideas. -
How to pass form data as instance in Django?
info: I am trying to make an app like monthly installment payment of items(property or etc). I want when I fill out the customer form and select the product, I have to submit the payment form along with it and that payment will be linked to that customer. So in order to do this work, I have created a CustomerPayment model. I don't know how the models should be designed to do this. Problem I am trying to submit the customer payment along with the customer form but my form is not submited it's redirect me to back on form. i don't know how can i pass the both form data as instances of CustomerPayment (customer=customer & payment=payment). Example: models.py class Customer(models.Model): name = models.CharField(max_length=255) phone = models.CharField(max_length=11, blank=True) class Payment(models.Model): collect_by = models.ForeignKey(User, on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now_add=True) amount = models.FloatField(default=0) class CustomerPayment(models.Model): customer = models.ForeignKey(Customer, related_name='Customer', on_delete=models.CASCADE) payment = models.ForeignKey(Payment, related_name='Payment', on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now_add=True) views.py def order_form(request): customer_form = CustomerForm(request.POST) payment_form = PaymentForm(request.POST) customer_payment_form = CustomerPaymentForm(request.POST) if request.method == 'POST': if customer_form.is_valid() and payment_form.is_valid() and customer_payment_form: customer = customer_form.instance.sales_men = request.user customer.save(commit=False) payment = payment_form.instance.collect_by = request.user payment.save(commit=False) customer_payment_form.instance.customer = customer customer_payment_form.instance.payment = payment customer_payment_form.save() return redirect('/') context … -
Any idea on why my django LoginView form isn't being displayed?
I'm trying to display the LoginView form but it won't display. I've been looking at the documentation for almost an hour and I cannot seem to figure out why the form is not being displayed. It accepts my template so it's rendering the template properly but not creating the form within the HTML form tags. urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('', include('blog.urls')), ] Login HTML {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <!-- fieldset used to group related elements into a form --> <fieldset class="form-group"> <legend class="border-bottom mb-4">Log In</legend> <!-- Loads in the form_key's value within our view with P tags instead--> <!-- {{ form_key }} --> {{ form_key|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Don't have an account yet? <a class="ml-s" href="{% url 'register' %}">Sign up now</a> </small> </div> </div> {% endblock content %} BASE HTML {% load static %} <!-- Loads in our static folder … -
Getting cloudinary default image to work with Django object
I'm trying to get Cloudinary default image to show up in my Django template, but it's not working. Each image URL works separately, but when combined, neither works. It goes to the one error. <img src="https://res.cloudinary.com/.../d_{{ id }}/{{ system|lower|cut:' '}}.png" width="250px" onerror='this.onerror = null; this.src=""'/> -
login - 'AnonymousUser' object has no attribute '_meta'
If password is not correct I am getting this kind of error, I don't know why. I can usually register, log in, log out, but when password is incorrect something wrong is happening. I am using AbstractBaseUser registration form. I will appreciate any help and thank you in advance. views.py from django.http.request import HttpRequest from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout, update_session_auth_hash from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from django.contrib import messages from .forms import RegistrationForm, LoginForm, UserChangeForm, ChangePasswordForm from .models import Account from django.conf import settings @csrf_exempt def sign_in(request): form = LoginForm() context = {'form':form} if request.method == "POST": form = LoginForm(request.POST or None) Account.objects.get(email=request.POST.get('email')) if form.is_valid(): data = form.cleaned_data user = authenticate(email=str(data['email']), password=str(data['password'])) login(request, user) return redirect('/') return render(request, 'login.html', context) -
How do I remove the "Installed x object(x) from y fixture(s)" report from django test?
I am using fixtures during my django tests as they are proving to be quite useful def some_test(self): ... call_command('loaddata', 'path/to/fixture.json') ... self.assertTrue(...) And when I run my tests, they all pass: $ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). ..Installed 2 object(s) from 1 fixture(s) ...................................... ---------------------------------------------------------------------- Ran 40 tests in 0.104s OK Destroying test database for alias 'default'... However, the "Installed 2 object(s) from 1 fixture(s)" is starting to annoy me. Is there a way to reduce the verbosity of the command? So then it could look like: $ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). ........................................ ---------------------------------------------------------------------- Ran 40 tests in 0.104s OK Destroying test database for alias 'default'... Which is what I want -
How does the Django template engine work?
In Django, I wonder when and when the code written in the django template language in the html file works. I looked for the official documentation, but couldn't find it.