Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Rectify Permission Issues in Centos while Serving Django applications via Apache + mod_wsgi?
I have a Django App Configured with via Apache and mod_wsgi The app has issues when current mode is enforcing while running: sestatus [root@localhost html]# sestatus SELinux status: enabled SELinuxfs mount: /sys/fs/selinux SELinux root directory: /etc/selinux Loaded policy name: targeted Current mode: enforcing Mode from config file: enforcing Policy MLS status: enabled Policy deny_unknown status: allowed Max kernel policy version: 31 The error being shown on the webpage is: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. The error in logfile is: [Tue Jul 19 06:45:33.033587 2022] [wsgi:error] [pid 22355] [remote 166.175.xx.x:10600] [Tue Jul 19 06:45:33.033591 2022] [wsgi:error] [pid 22355] [remote 166.175.xx.x:10600] [Tue Jul 19 06:45:33.033592 2022] [wsgi:error] [pid 22355] [remote 166.175.xx.x:10600] During handling of the above exception, another exception occurred: [Tue Jul 19 06:45:33.033594 2022] [wsgi:error] [pid 22355] [remote 166.175.xx.x:10600] [Tue Jul 19 06:45:33.033597 2022] [wsgi:error] [pid 22355] [remote 166.175.xx.x:10600] Traceback (most recent call last): [Tue Jul 19 06:45:33.033645 2022] [wsgi:error] … -
Same Dynamic Data coming in every column of webpage
I am doing CRUD using serializers, foreignkeys and I am trying to dynamically list the categories, sub_categories. For example category = 9-6 wear and its subcategories are kurta, skirtset, dress, kurtaset. I want these subcategories below only 9-6wear The issue is that other subcategories are also mentioning kurta,skirtset,dress and kurtaset which I dont want as shown below I have tried for hours but without much success below are my models class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=70) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=1000) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) class Categories(models.Model): #made changes to category_name for null and blank category_name = models.CharField(max_length=30) category_description = models.CharField(max_length=30) isactive = models.BooleanField(default=True) class SUBCategories(models.Model): category_name = models.ForeignKey(Categories, on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=30) sub_categories_description = models.CharField(max_length=30) isactive = models.BooleanField(default=True) below are the serializer class SUBCategories(models.Model): category_name = models.ForeignKey(Categories, on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=30) sub_categories_description = models.CharField(max_length=30) isactive = models.BooleanField(default=True) class CategoriesSerializer(serializers.ModelSerializer): class Meta: model = Categories fields = "__all__" extra_kwargs = {'category_name': {'required': False}} class POLLSerializer(serializers.ModelSerializer): class Meta: model = Products fields = "__all__" below is my shoppingpage function def shoppingpage(request): cat = Categories.objects.filter(isactive=True) category = CategoriesSerializer(cat,many=True) subcat = … -
django rest framework nested serializer crud operations . what required is to create a api which should be called only once to perform crud operations
models.py class User(models.Model): ROLE_CHOICES = ( ("admin","ADMIN"), ("staff","STAFF") ) username = models.CharField(max_length=256) password = models.CharField(max_length=256) firstname = models.CharField(max_length=256) lastname = models.CharField(max_length=256) email = models.CharField(max_length=256) role = models.CharField(max_length=256,choices=ROLE_CHOICES) class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True,) phone_number = models.IntegerField() company_name = models.CharField(max_length=256) I want to use nested serializer here to do crud operations. -
Using flask, how can I return a row of data as a list
I am trying to get my route to return a row in a list format but it appears to be returning a concatenation of the row items. How can I return the row of data in list format? Here is what I want it to return: ['field1', 'field2', 'field3', 'field4', 'field5'] What it appears to return is: ['field1' 'field2' 'field3' 'field4' 'field5'] Here is my app.py file: from flask import Flask, render_template, json, redirect, request import pandas as pd # Flask constructor app = Flask(__name__) # Data setup salary_table = pd.read_csv("salaries.csv") salary_table.fillna('', inplace=True) headings = list(salary_table.columns) print(headings) data = list(salary_table.values) print(data) # Homepage URL call @app.route("/") def home(): return render_template("home.html", headings=headings, data=data) @app.route('/GetPlayerInfo/<row>') def GetPlayerInfo(row): return row # Listener if __name__ == "__main__": app.run(port=2509, debug=True) Here is my home.html file: <html> <head> </head> <body> <div class="tableContainerDiv"> <table class="table"> <tr class="header"> {% for header in headings %} <th class="cell">{{header}}</th> {% endfor %} <th>Info</th> </tr> {% for row in data %} <tr class="row"> {% for cell in row %} <td class="cell">{{cell}}</td> {% endfor %} <td><a href="GetPlayerInfo/{{row}}">Info</a></td> </tr> {% endfor %} </table> </div> </body> </html> -
Unable to write in a file after django app deployment on aws ec2 using nginx and gunicorn
I have deployed my Django online judge project on AWS EC2 using Nginx and Gunicorn I am taking user code in a string variable and writing it to a file in my project directory and it's working fine in development server but after deployment the program unable to write code in the file. for eg:- lets say a user have submitted code in c++ language so I took that code in a string variable and I open the my .cpp file via open() function in my views.py and writing the code in it. filepath = os.path.join(settings.BASE_DIR, 'language', 'forcpp.cpp') cpp_code=open(filepath,"w") cpp_code.write(user_problem_code) cpp_code.close() I have tried to modify path in every possible way but got unlucky in every try I have my files in language folder in which I want to write user submitted code and my views.py are in problempg application my project directory structure: online_judge_project/ account/ homesrc/ language/ /* directory containing files in which I want to write */ forcpp.cpp media/ oj/ settings.py problempg/ /* application containing views.py */ views.py static/ staticfiles/ template/ manage.py may be the path I am using in development is different in EC2 server. I have develop this project on a windows machine and I am … -
(django) how to flatten an array inside of a dictionary to an array only
I am currently trying to handle the nested data in django. In my case, I want to remove the key "event_log" and flatten it to a simple array of dictionary only. { "event_log": [ { "date": 12-12-2000, "point": 500 }, { "date": 12-12-2001, "point": 700 } ] } The outcome should look like this: [ { "date": 12-12-2000, "point": 500 }, { "date": 12-12-2001, "point": 700 } ] I have tried adding a to_representation method to the serializer: class EventDateSerializer(serializers.ModelSerializer): event_log = EventLogSerializer(many=True, read_only=True) class Meta: model = EventDate fields = ['event_log'] def to_representation(self, instance): data = super().to_representation(instance) flatten_data = data['event_log'] for item in flatten_data: for key, value in item.items(): data[key] = value return data However, it turns out this method can only flatten nested dictionary instead of array inside of dictionary. Has anyone got an idea on how to flatten the array inside of the dictionary? Much appreciated. -
How Check ManyRelatedManager is None
-models.py class Role: name = models.CharFiled(max_length=100) comp = models.ForeignKey(Company, models.CASCADE, related_name="comp_roles") users = models.ManyToManyField(User, related_name='user_roles', related_query_name='user_role', through='UserRole') class UserRole(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) role = models.ForeignKey(Role, on_delete=models.CASCADE) based on certain conditions I have two queries -in api_views.py: 1-Role.objects.filter(comp_id=self.comp_id).prefetch_related('users') 2-Role.objects.filter(comp_id=self.comp_id) -RoleSerializer.py class RoleSerializer(serializers.ModelSerializer): users = serializers.SerializerMethodField() def get_users(self, obj): #users: ManyRelatedManager = obj.users logger.info(f"this is obj.users: {obj.users}") logger.info(f"this is n obj.users: {obj.users == None}") # hit the db: # if not obj.users.all(): # if obj.users.exists() == None: # no hit the db: # if obj.users.all() == None: # if obj.users == None: if obj.users.all() == None: logger.info(f"obj.users is None!") return None logger.info(f"obj.users is not None!") serializer = UserReadSerializer(obj.users.all(), many=True) return serializer.data Either obj.users == None log or obj.users.all() == None codition are always false! My question is how can I find out obj.users or obj.users.all() (in RoleSerializer/get_users) is None? so I can decide to return whether None or UserReadSerializer data. -
How create filter for queryset Python django
can someone explain to me how to create a query with 3 sums with different filters for the same column using django's queryset? I tried to create using: sum1 = Sum("price", filter=Q(coins__=1)) sum2 = Sum("price", filter=Q(coins__=2)) sum3 = Sum("price", filter=Q(coins__=3)) but regardless of the filter, it receives the same value for the three filters. My table: Coin-in-out a - 1 - 2 b - 0 - 2 c - 3 - 3 a - 2 - 3 I need a single dictionary that receives the summed value and grouped by coin. -
I don't know why javascript is not working in the below mentioned code for back to top button for the blog page
The javascript in the base footer file is not working and that's why the back-to-top button in the base file is not working as expected. the functionality and all is working in the back-to-top button but the button is not visible because through javascript, I am adding a class active but it is not adding in this page but the base file is also linked to another page and there everything is working fine. I am not able to figure it out why it is not working. Below is the main blog file where base-home-footer file is linked to. {% extends 'media/assets/base-media.html' %} {% load main %} {% load static %} <!-- title start --> {% block title %}Prishni- Our Blog{% endblock title%} <!-- title end --> <!-- header start--> {% block header %} {% include 'assets/base-home-header.html' %} {% endblock header %} <!-- header end --> <!-- Content Start --> {% block mediaContent %} {% load markdownExtras %} <div class="wrapper _bg4586 _new89" id="main-content" role="main"> <div class="_215cd2"> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="course_tabs"> <nav> <div class="nav nav-tabs tab_crse justify-content-center"> <a class="nav-item nav-link active" href=" {% url 'media:ourBlog' %} ">Blog</a> </div> </nav> </div> <div class="title129 mt-35 mb-35"> <h1 align="center">Insights, ideas, … -
How to fetchData when react component is in viewport
I am working on a social media type of project, using ReactJS & django, I don't know how do pagination in react (load more post when end of the page is reached) I have implemented pagination on backend using drf api endpoint is something like: /post/api/?page=2 response is like: { "prev": true, "next": true, "data": [...] } -
Django FileField - I/O operation on closed file
I have a simple model Jour and the following model (JourAttachment): class JourAttachment(models.Model): jourreport = models.ForeignKey(JourReport,related_name="jourattachments", on_delete=models.CASCADE) file = models.FileField(null=False) When trying to create a Jour-instance, I add all the attachments the following way: View class JourReportListView(APIView): serializer_class = JourReportListSerializer permission_classes = (IsAuthenticated, ) def post(self,request,*args, **kwargs): user_making_request = request.user if not user_is_admin(user_making_request): return UserNotAdminResponse() attachments = request.FILES.getlist('attachment', None) serializer = JourReportCreateUpdateSerializer(data=request.data,partial=True,context={'attachments': attachments}) valid = serializer.is_valid(raise_exception=True) if valid: serializer.save() status_code = status.HTTP_201_CREATED return SuccessfulResponse(data=request.data, message="Jour report successfully registered!" ,status_code=status_code) return ErrorResponse() Serializer def create(self, validated_data): users = [] attachments = self.context['attachments'] if "additional_workers" in validated_data: users = [w.id for w in validated_data["additional_workers"]] del validated_data["additional_workers"] report = JourReport.objects.create(**validated_data) for a in attachments: JourAttachment.objects.create(file=a,jourreport=report) rerturn report This results in a ValueError: I/O operation on closed file and I have no idea why. -
How to pass a JSONResponse back to Django Template
I have this custom view function that would be automatically executed when the user violates my login policy (this is done via django-axes). I am unable to display my JSONResponse data on Django template. May I know if there is any workaround on this? HTML <form role="agent-login" class="login" id="agentloginform" action="{% url 'agent-login' %}" method="post"> {% csrf_token %} <div class="form-group"> <input type="text" placeholder="Email address" name="email" class="form-control"> </div> <div class="form-group togglepassword-right"> <input type="password" placeholder="Password" name="password" class="form-control"> <i class="glyphicon glyphicon-eye-open form-control-feedback" id="togglePassword"></i> </div> <p class="text-danger text-center" id="lockout-error" style="display:none;"> {{ errors.password }} {{ login }}</p> <div class="form-group"> <button data-request="ajax-submit" data-target="[role='agent-login']" class="btn-1 " type="button" id="agent-submit"> Login now </button> </div> </form> custom view def user_lockout(request, credentials): """ Custom accout lockout message for django-axes. change custom_account_lockout_message accordingly to what you need. """ response_data = { "login": "Failed", "error": settings.CUSTOM_AXES_SOFT_LOCKOUT_MESSAGE, } return HttpResponse(JsonResponse(response_data)) I was thinking of using ajax to get my JSONResponse data. But because its a custom button that was done others, I might not be able to change it. This is what I have came up with $('#agent-submit').click(function(e) { console.log('pressed'); console.log($(this).serialize()) console.log(e) $.ajax({ type: 'POST', dataType: 'json', url: '{% url ' agent - login ' %}', data: $(this).serialize(), success: function(response) { var dd = jQuery.parseJSON(response) … -
Want to access a file which is in another docker container from anotherdocker container using python code
We have two docker containers. The first container is backend_device_service which we access using the command -> docker exec -it backend_device_service bash. On this backend_device_container we write our python code. Now I am writing an API which needs to access a file which is on another container rsyslog (server is same just the container is different). We access this container using the command -> docker exec -it rsyslog bash In this container at the path -> /var/log/CPE my file contains which I need to access. However I can access any path in the same container using the following piece of code:- class SysLogReader(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get(self, request): content = os.popen('cat /app/sdwan_device_service/devices/views').read().strip('\n').lower() logger.info(f"\ncontent of the file:\n {content}\n") dir_path = os.path.dirname(os.path.realpath(__file__)) resp = {"success":True, "message" : f"Directoty path is {dir_path}"} return Response(resp, status=status.HTTP_200_OK) While my problem is how to access the file which is in another container rsyslog. -
How to add search in the Root pages header in Wagtail admin?
In wagtail admin, there are list of pages and subpages, from the side menu: Pages > Home > How can I add a search field to search for the child pages, as follows? Thanks -
Cart functionality in django
I'm building an ecommerce platform and I want to create the add to cart functionality in the website. But for some reason the quantity is not updating. Here's the views.py: def cart_detail_view(request, product_obj=None): if request.method == 'POST' and request.POST.get('action') == 'create-cart_product': cart_product_form = CartProductForm( request.POST, ) if cart_product_form.is_valid(): try: cart_product_obj = CartProduct.objects.get( product=product_obj, cart__id=request.session.get('cart__id'), ) cart_product_obj.quantity += cart_product_form.cleaned_data.get('quantity') except CartProduct.DoesNotExist: cart_product_obj = cart_product_form.save(commit=False) cart_product_obj.product = product_obj cart_product_obj.cart_id = request.session.get('cart__id') cart_product_obj.save() messages.error(request, 'something is wrong') return redirect('webshop:cart_detail_view') context = { 'cart_product_form': cart_product_form, } return render(request, 'webshop/cart_detail_view.html', context) This is my forms.py file class CartProductForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CartProductForm, self).__init__(*args, **kwargs) self.fields['quantity'].choices = tuple([(i, i) for i in range(1, 7)]) class Meta: model = CartProduct fields = ( 'quantity', 'product', ) widgets = { 'quantity': forms.Select(), 'product': forms.HiddenInput(), } I need to update quantity in my views but I don't understand how I am gonna do that? -
How to filter django queryset based on the serializer field value?
serializer class MyModelSerializer(serailizers.ModelSerializer): hrs = serializers.SerializerMethodField() get_hrs(self, obj): datetime = SomeModel.objects.filter(id=obj.id).last().datetime now = datetime.now() return (now - datetime).total_seconds() // 3600 class Meta: model = MyModel fields = "__all__" Now in the api there will be a filter paramter hr what it need to do is filter the queryset matching this above calculated hr. For example: @api_view(["GET"]) def get_list(request): qs = MyModel.objects.all() hr = request.GET.get("hr") if hr: qs = qs.filter(hrs=hr) # hrs is not inside model return MyModelSerializer(qs, many=True).data Here hrs is not there inside the Model it's a serializer field above calculated. How can I filter like this from serialzier fields ? Any gudiance would be very helpful. -
Why does changing my render request in views.py break my ability to import images in my base.html?
In my views.py, I have a function for my homepage; @login_required(login_url="/login") def home(request): user_object = User.objects.get(username=request.user.username) user_profile = Profile.objects.get(user=user_object) posts = Post.objects.all() return render(request, "main/home.html", {'user_profile': user_profile}) #This is the problem line and my HTML runs perfectly; <body> <header> <div class="container"> <img src="{% static 'css/images/uReflect.png' %}" alt="logo" class="logo"> <nav> But when I change my home function in views.py to the code below, my page stops working. I have no idea how an error with 'post.image' would correlate to me accessing my images that are independent of posts, and exist in a separate folder. The weirdest part to me is how the error says "NoReverseMatch at /home" but the error doesn't even occur in home.html, it occurs in base.html. Although, home.html does extend base.html; @login_required(login_url="/login") def home(request): user_object = User.objects.get(username=request.user.username) user_profile = Profile.objects.get(user=user_object) posts = Post.objects.all() return render(request, "main/home.html", {'user_profile': user_profile, 'posts': posts}) # Change made here with posts -
Django: query filter
I have two models that are related: one is a list of participants. The other is a list of times they have checked in or out of an office. The table (Checkin) has one record for every checkin/checkout pair. So, there can be many records for any participant. How can I retrieve only the very last (most recent) record for a participants checkin and then pass the participant and only that most recent Checkin record to my template? From what I can tell there's no ability to do something like a last() in my template, so how would I go about filtering to get just that single record? Thank you. Models: class Participant(models.Model): first_name = models.CharField(max_length=50) middle_initial = models.CharField(max_length=50, blank=True) class CheckIn(models.Model): adult = models.ForeignKey( Participant, on_delete=models.CASCADE, blank=True, null=True, related_name='adult_checkin') checkin = models.DateTimeField(blank=True, null=True) checkout = models.DateTimeField(blank=True, null=True) View snipit: p_checkins = Participant.objects.all().order_by('created') queryset = p_checkins context_object_name = "the_list" template_name = 'list_of_checkins.html' -
Is it better to use JsonField or multiple model fields for a Django Model?
For example, class TestModel(models.Model): title = models.CharField(max_length = 200) descriptions = models.JsonField() Or class TestModel(models.Model): title = models.CharField(max_length = 200) description_1 = models.TextField() description_2 = models.TextField() description_3 = models.TextField() description_4 = models.TextField() description_5 = models.TextField() Assume that I have a limited (max 5) number of descriptions. Which approach is better and would be considered as good practice? -
Django server: execute a function once a day
I have a django server which uses a another api to use its resources. In order to use the api, i need to pass access token. And I have refresh token which expires after two weeks. What I want to do is to define a function that checks if refresh token expires that day and if so, update tokens. Most importantly, I want to call that function once a day. I can do that with setInterval in javascript, but what is the most efficient and safest way to implement that feature with python ? -
keep getting bad request when I try to upload image to Django using react native camera
I am trying to make a camera app using react native and send the image to backend using Django. here is the code for taking picture and update it on Django. I tried PUT and POST method. const [image, setImage] = useState(null) const takePicture = async() => { // setimage(null); if(camera){ const options = { base64: true, quality: 0.5 } const data = await camera.takePictureAsync(options) setimage(data.uri); const upload = new FormData(); upload.append('name', '') upload.append('image', image); console.log(upload); fetch("http://192.168.0.154:8000/API/getObjectProperties/object/1/" , { method: 'PUT', // headers: { // 'Content-Type': 'application/json' // }, body: upload } ).then( (res) => res.json()).catch( (error) => console.error(error)); } } const takePicture = async() => { // setimage(null); if(camera){ const options = { base64: true, quality: 0.5 } const data = await camera.takePictureAsync(options) setimage(data.uri); const upload = new FormData(); upload.append('name', '') upload.append('image', image); console.log(upload); fetch("http://192.168.0.154:8000/API/getObjectProperties/object/1/" , { method: 'PUT', // headers: { // 'Content-Type': 'application/json' // }, body: upload } ).then( (res) => res.json()).catch( (error) => console.error(error)); } } but I keep getting bad request although it works when using postman. bad request the FormData is it because it cannot read the file from the camera.takePictureAsync() as it is like "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FThesisApp-1fe17b3a-01c2-46c4-953e-6368f5dc1eeb/Camera/d909cdfe-9d40-4788-a212-63780d715321.jpg" instead of just d909cdfe-9d40-4788-a212-63780d715321.jpg? is there any solution … -
Unable to display string from backend to Django Template
Hi I am unable to display some string from my custom view backend to django template. The string from backend is able to send over to the client side browser but still unable to display. The error message that I am trying to display is a lockout message from django-axes. it is a custom view function that returns a HttpResponse(JsonResponse(response_data)) where the response_data is as shown in the image inserted. Below is what I have tried. HTML <div class="login-form clrbg-before"> <p class="text-success" id="login-success" style="display: none;"></p> <form role="agent-login" class="login" id="" action="{% url 'agent-login' %}" method="post"> {% csrf_token %} <div class="form-group"> <input type="text" placeholder="Email address" name="email" class="form-control"> </div> <div class="form-group togglepassword-right"> <input type="password" placeholder="Password" name="password" class="form-control"> <i class="glyphicon glyphicon-eye-open form-control-feedback" id="togglePassword"></i> </div> <p class="text-danger text-center" id="password-error" style="display:none;"> {{ errors }}</p> <div class="form-group"> <button data-request="ajax-submit" data-target="[role='agent-login']" class="btn-1 " type="button"> Login now </button> </div> </form> <div style="text-align: center;"> <a href="#" class="gray-clr" id="agent-forgot"> Forgot Password? </a> </div> </div> views.py def agent_login(request): start = time.time() sop(start) response_data = {'login': "Failed"} redirect_url = '' data = [] error = False errors = {} result = 'FAIL' message = '' response_status = HTTP_400_BAD_REQUEST if request.POST: redirect_url = '' data = [] error = False errors = {} result … -
Django deploy on App Engine raise error: connection to server at "127.0.0.1", port 5432 failed:
i am trying to deploy my django web app on Google Cloud App Engine, but are running to a connection error. This is after I have done all the configuration like main.py, entry point, app.yaml. After doing some digging, they all point to my postgresql database blocking my connections somehow, but i checked and my database is up and running on sql cloud. Here is the screenshot of the error: [the error image][1]: https://i.stack.imgur.com/bDIfY.png Here is my app.yaml file: # [START django_app] runtime: python38 handlers: # This configures Google App Engine to serve the files in the app's static # directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to your main app. It is # required when static routes are defined, but can be omitted (along with # the entire handlers section) when there are no static files defined. - url: /.* script: django_blog.wsgi.application env_variables: APPENGINE_URL: https://engineblog.wn.r.appspot.com #entrypoint: gunicorn -b :$PORT django_project.wsgi:main inbound_services: - warmup # Only pure Python libraries can be vendored # Python libraries that use C extensions can # only be included if they are part of the App Engine SDK # Using Third Party Libraries: https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27 # libraries: # … -
Django - User Password Change by coding
I am trying to give permission to change password for logged in user. coded as below.. result comes as password has been changed but password not set. def changepassword(request): if request.method == 'POST': user = authenticate(request, username=request.user,password=request.POST['old']) if user is None: return render(request, 'pmp/changepassword.html', {'error': 'Current Password Enter Mismatch! '}) else: try: if request.POST['password'] == request.POST['confirm']: u = request.user u.set_password('password') return render(request, 'pmp/changepassword.html', {'success':'Password has been changed!'}) else: return render(request, 'pmp/changepassword.html',{'form': AuthenticationForm(), 'error': 'New Password and confirm Password mismatch!'}) except ValueError: return render(request, 'pmp/changepassword.html',{'form': AuthenticationForm(), 'error': 'Password not changed!'}) return render(request, 'pmp/changepassword.html') -
How to fix `TypeError: 'AnonymousUser' object is not iterable ` in Django
I'm using LoginRequiredMixin in Django. However I got error. TypeError: 'AnonymousUser' object is not iterable It happen in this line if Speaker.objects.filter(user=self.request.user, is_deleted=False).count() == 0: of this code. class SpeakerListView(LoginRequiredMixin, ListView): template_name = 'speaker/list.html' context_object_name = 'speakers' model = Speaker def dispatch(self, request, *args, **kwargs): # if user does not have speaker, redirect to create view if Speaker.objects.filter(user=self.request.user, is_deleted=False).count() == 0: messages.error(request, _('xxx')) return redirect('speech:speaker_add') return super().dispatch(request, *args, **kwargs) If you know, how to solve this problem. Please help me!