Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get individual users data after login in django?
iam new to django.Can anyone send me the code of signup and login page to get particular details of the username (i.e if we login with some usename then it should only give details of that username not remaining). -
django ajax like button with css classes
hello I have a post model which has a like(m2m) and user(forgeinkey) model field and Im trying to check if the request.user has liked the post and if they have, I should show them a red heart button else a blue heart should be shown, now since there are multiple posts and likes, Im looping through each like object to check if the request.user has liked it or not. Unfortunately for some reason, I couldn't implement a good logic and I see like button for every user. Some help would be appreciated. Here's my model: class post(models.Model): user = models.ForeignKey(User,default='' , related_name='has_liked', on_delete=models.CASCADE) caption = models.CharField(max_length=100) image = models.FileField(upload_to='images/', null=True, blank=True) video = models.FileField(upload_to='videos/', null=True, blank=True) created = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField(User, null=True, blank=True, default='') The View: @login_required def usersfeed(request): users = User.objects.all() posts = post.objects.filter(Q(user__in=request.user.profile.friend.all()) | Q(user=request.user)).order_by('-created') comments = Comment.objects.all() status_form = StatusForm(request.POST) friend_requests = FriendRequest.objects.filter(to_user=request.user) friends = request.user.profile.friend.all() for i in posts: likes = i.like.all() print(likes) for like in likes: if like.username == request.user.username: if request.user: Hasliked = True print('liked') else: Hasnotliked = True print('not liked') context = { 'Post':posts, 'User':users, 'form':PostForm(), 'Profile':profile, 'Form':CommentForm(), 'Comment':comments, 'Status':status_form, 'fr':friend_requests, 'friend':friends, 'Hasliked':Hasliked, 'Hasnotliked':Hasnotliked, } return render(request, 'social_media/feed.html', context=context) The view for … -
NoReverseMatch at / Reverse for 'url' with arguments '('',)' not found
I am trying to pass URL as a parameter in dynamic URL. The URL contains ? which is making django search for the keys. How do I make Django ignore '?' that are present in my URL. Custom URL: https://www.amazon.in/Samsung-Galaxy-M12-Storage-Processor/dp/B08XGDN3TZ/ref=sr_1_1_sspa?dchild=1&keywords=redmi+9&qid=1622011804&sr=8-1-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFZSlE5U0lEUzBFUVQmZW prd.Url is passed as a parameter {% for prd in prds %} {{ prd.name }} <a href="{% url 'url' prd.Url %}">Click</a> {% endfor %} urlpatterns = [ path('admin/', admin.site.urls), path('', index, name='index'), path('create/', createProfile.as_view(), name='create_profile'), path('update/<pk>', UpdateProfile.as_view(), name='update_profile'), path('url/<my_url>', url, name='url') ] -
Django filter and paginate not working. (Using AJAX)
I have a table for tracking job applications and im trying to implement a filter feature. On choosing a filter for instance closing date, the jobs are sorted by closing date and displayed in table. The query is working fine. I have printed the results. Is there a way I update the page without refresh and paginate the new results? Please help.... Here is my code: template file <ul id="filter_list" class="dropdown-menu"> <li><a href="#">Alphabetical Order (A-Z)</a></li> <li><a href="#">Application Date (Ascending)</a></li> <li><a href="#">Application Date (Descending)</a></li> <li><a href="#">Closing Date</a></li> </ul> <div id="table_results"> <div> <script> $(".dropdown-menu a").click(function(){ var selected_filter = $(this).text(); $.ajax({ url:'{% url "stu_filter_applications" %}', data:{ "filter_category": selected_filter, }, dataType:'json', success: function (response) { //I want the page to not refresh here }, error: function (response) { console.log(response.errors); }, }); }); </script> views.py: def stu_filter_applications(request): filter_cat = request.GET.get("filter_category", None) student = StudentUser.objects.get(user=request.user) if filter_cat == "Alphabetical Order (A-Z)": int_applications = InternshipApplication.objects.filter(student=student). order_by('internship__internship_title') if filter_cat == "Application Date (Ascending)": int_applications = InternshipApplication.objects.filter(student=student). order_by('application_date') if filter_cat == "Application Date (Descending)": int_applications = InternshipApplication.objects.filter(student=student). order_by('-application_date') if filter_cat == "Closing Date": int_applications = InternshipApplication.objects.filter(student=student). order_by('-internship__internship_deadline') applications = [] for app in int_applications: internship = Internship.objects.get(id=app.internship.id) recruiter = Recruiter.objects.get(id=internship.recruiter.id) applications.append((internship,recruiter,app)) for internship, recruiter, app in applications: print(internship) print(recruiter) … -
how to create a decorator/ wrapper class in python to pass the attributes of error logs as a single parameter?
@api_view(['GET']) def test_api_method(self): print('This is Test API') db_logger = logging.getLogger('db') try: 1 / 0 except Exception as e: db_logger.exception(e, extra={'user': self.user.username, 'class_name': self.__class__.__name__,'method_name':sys._getframe().f_code.co_name, 'module_name':__package__,'ip_address': socket.gethostbyname(socket.gethostname())}) return Response({'data': True}, status=status.HTTP_200_OK) I want to create a decorator or a wrapper class to pass the parameters in the db_logger.exception() as a sin single parameter. Mainly, I wanted to replace this dictionary---> extra={............} with a single parameter so that this error logging method can be used to log errors across all classes and methods. -
Change Django Database : SQLITE3 to MARIADB
I am new to Django and python! I made a project on Django with the default database which is sqlite3. I want to now transfer the database from sqlite3 to Mariadb. There is no data which is present in current sqlite3. I just want to know how can I transfer the default database. I have followed the following documentation: And added, this to my settings.py : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Altiostar', 'USER': 'satharkar', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': '', } } I am not sure, how things will work with this now. I am looking if someone can help me with this. So what I did is by now : I deleted the db.sqlite3 from my project folder. Tried to run python manage.py makemigrations but it is throwing error that mysql client is not installed. I have followed the documentation and installed everything mentioned their. How will things work after this ? So whenever I will try to submit the form in my django project, database, table will be created and data will be then stored under the mariadb? I am new to all this, looking for a resolution in this case or any suggestions on … -
I am making an affiliate website where we can copy product link and share it in other medias. please help to get me with it with a little idea
This is the product page. I have highlighted the portion of which i want to convey about. Here, in the 'Get Link' option i want to create a link for this product so that if a user copies and shares it to other media, it will open this page. P.S: Project is still in development URLS.py urlpatterns = [ path('', views.blink_network), # redirect to root - path path('blink_network/', views.blink_network, name='blink_network'), path('AddNewProduct/', views.AddNewProduct, name='AddNewProduct'), path('blink_viewproduct/', views.showproduct), path('blink_viewproduct/', views.blink_viewproduct, name='blink_viewproduct'), path('blink_updateproduct/', views.blink_updateproduct, name='blink_updateproduct'), ]+static (settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Views.py def AddNewProduct(request): if request.method == "POST": current_user = request.user product_title =request.POST['product_title'] uid = request.POST['uid'] specification =request.POST['specification'] sale_price = request.POST['sale_price'] discount = request.POST['discount'] img1 = request.FILES['img1'] img2 = request.FILES['img2'] promote_method = request.POST['promote_method'] terms_conditions = request.POST['terms_conditions'] newproduct = AffProduct(user_id=current_user.id, product_title=product_title, uid=uid, specification=specification, sale_price=sale_price, discount=discount, img1=request.FILES.get('img1'), img2=request.FILES.get('img2'), promote_method=promote_method, terms_conditions=terms_conditions) newproduct.save() # Status message messages.success(request, 'Product added successfully') return render(request, 'blink_network.html') else: return render(request, 'blink_network.html') #Display only single-user products def showproduct(request): if request.user.is_authenticated: current_user = request.user# define current user result = AffProduct.objects.filter(user_id=current_user.id) return render(request, 'blink_viewproduct.html', {'result': result}) HTML File <div class="row py-3"> <div class="col-lg-12 col-md-12"> <h5 class="text-center"><b>Product Details</b></h5> <table class="table table-striped table-hover table table-responsive table-responsive-lg table-responsive-md table-responsive-sm"> <thead> <tr class="bg-primary text-white"> <th scope="col">Product ID</th> <th scope="col">Product Title</th> <th scope="col">Sale … -
if request.method == "POST": the pointer is not coming in the if statement can anybody tell?
views.py ... @login_required() def candidate_view(request): if request.method == "POST": can = candidate.objects.filter(position = 'President') return render(request,'poll/candidate.html',{'can':can}) else: return render(request, 'poll/candidate.html') ... ... vote.html {% extends 'base.html' %} {% block title %}Positions{% endblock %} {%block body%} <form action="" method="POST"> {%csrf_token%} <ul> <li><h2><a href='candidate_view'> President</a></h2></li> <li><h2><a href='candidate_view'> Vice President </a></h2></li> <li><h2><a href="#"> Secratary </a></h2></li> <li><h2><a href="#"> Vice Secratary </a></h2></li> </ul> </form> {% endblock %} ... Caandidate.html ... {% extends 'base.html' %} {% block title %}Positions{% endblock %} {%block body%} <form action="" method="POST"> {%csrf_token%} <ul> <li><h2><a href='candidate_view'> President</a></h2></li> <li><h2><a href='candidate_view'> Vice President </a></h2></li> <li><h2><a href="#"> Secratary </a></h2></li> <li><h2><a href="#"> Vice Secratary </a></h2></li> </ul> </form> {% end block %} ... -
How to pass a decimal value when making a post request in django?
I am trying to make a post request to a third party application along with some data and the data also have a decimal value up to two points, which I am getting from database (order.amount) but after making the request getting error saying data is not serializable to json then i passed it as '"%s"' % round(order.amount,2) then also getting error post data is empty.Looking for suggestion to solve this problem. request = Transfer.request_transfer(beneId=beneficiary_id, amount=round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer") getting error: decimal is not json serializable print('"%s"' % round((order.amount),2) #"5000.23" request = Transfer.request_transfer(beneId=beneficiary_id, amount='"%s"' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer") getting error : PreconditionFailedError: Reason = Post data is empty or not a valid JSON:: response = {"status": "ERROR", "subCode": "412", "message": "Post data is empty or not a valid JSON"} but when hardcoding amount then it is working request = Transfer.request_transfer(beneId=beneficiary_id, amount= "5000.23" transferId=transfer_identifier,remarks="Test transfer") -
Handling oracle database clob field in djangorestframework to get rid of to_clob()
I have an oracle database with a clob field as below: Name Null? Type ----------------------- -------- ------------- ID NOT NULL NUMBER MOVIE NOT NULL VARCHAR2(100) PLOT CLOB I am writing an API to retrieve this data and have the models.py defined as below: class MovieInfo(models.Model): id = models.IntegerField(primary_key=True) movie = models.CharField(max_length=100, unique=True) plot = models.TextField(null=True, blank=True) class Meta: managed = False db_table = 'movie_info' My serializer is defined as: class MovieInfoSerializer(serializers.ModelSerializer): class Meta: model = MovieInfo fields = '__all__' Views: class MovieInfoViewSet(viewsets.ModelViewSet): queryset = MovieInfo.objects.all() serializer_class = MovieInfoSerializer http_method_names = ['get'] However when I issue a get request, the data I'm getting looks as below: {"id":1,"movie":"Gravity","plot":"to_clob('The crew of the Space Shuttle Explorer is working on the STS-157 mission. Mission Commander Matt Kowalski, medical engineer Dr. Ryan Stone - who is on her first ever space mission - and flight engineer Shariff Dasari are on a space walk when they learn from Houston control that an explosion has just occurred at a Russian satellite. Before the crew can do anything about it, the explosion debris comes hurtling toward Explorer, irreparably damaging the shuttle and station, immediately killing all the crew except Kowalski and Stone, and knocking out at least incoming communication … -
im getting that type of error send_mail got multiple values for argument fail_silently
I'm writing a simple little program ... when I'm trying to email this info. from that form, I got that type of error I'm writing a simple little program ... when I'm trying to email this info. from that form, I got that type of error -
Field defines a relation with the model 'auth.User', which has been swapped out.(fields.E301)
I'm getting this error. ERRORS: subscriptions.StripeCustomer.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. I'm trying to configure Django Stripe Subscriptions following this manual https://testdriven.io/blog/django-stripe-subscriptions/ My models.py from django.contrib.auth.models import User from django.db import models class StripeCustomer(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE) stripeCustomerId = models.CharField(max_length=255) stripeSubscriptionId = models.CharField(max_length=255) def __str__(self): return self.user.username My admin.py from django.contrib import admin from subscriptions.models import StripeCustomer admin.site.register(StripeCustomer) My settings.py AUTH_USER_MODEL = 'accounts.CustomUser' DEFAULT_AUTO_FIELD='django.db.models.AutoField' SITE_ID = 1 AUTHENTICATION_BACKENDS = ( 'allauth.account.auth_backends.AuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', ) EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' ACCOUNT_EMAIL_VERIFICATION = "none" After setting above, I executed "python manage.py makemigrations && python manage.py migrate" then the error occurred. I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
Django Account Switching
I am creating a request approval system in Django with 4 user roles Request Initiator with rights to only raise the request and view it Approver with rights to approve the request and view it Viewer with only viewing rights Admin with all the rights I need to create a functionality that can switch me between first 3 users if I am logged in as the Admin so that I can test the functioning of system without having to log in and log out again and again. Basically I need to create a switch account that will show me the webpage as some other user will see it on a single button click, I created a view that switch the account to the other user but once I am switched to this other user I lose the functionality to switch again because now I am not logged in as Admin...can I modify this function to see how a web page will look like if some other user with different access rights was to view the page without logging out as the admin ? def switch_account(request): new_user_id = request.POST.get('userID') new_user_pwd = request.POST.get('password') user = fetch_user(request, new_user_id , pwdnew_user_pwd admin = check_if_admin(str(request.user)) … -
PyCharm debug Django REST framework apis: breakpoints don't stop
I'm trying to debug my Django REST framework apis with PyCharm. I followed the answer from PyCharm: debug Django Rest Viewsets but breakpoints don't stop. With the same debug setting on a regular django app, breakpoints work as I expect but with Django REST framework they don't. When I hit the debug icon, it stops where my breakpoints are, but when I call the api from chrome, it never stops. I have PyCharm Professional 2021.1 and my settings are below. Does anyone have a clue? Thank you. -
Providing user with logs for a long API call
I have a web app that is used to interface with some network devices. There's an API endpoint to query for network device state. Once user calls it (post request with json body containing device to connect to, credentials and what state to collect), server will establish SSH connection to network device, run bunch of commands, parse output and return dictionary to the user. I have also built a web page with javascript that takes in user input and makes a POST ajax call to the endpoint. All that is working fine. The problem is, some devices are quite far away (geographically) and due to that, it may take very significant time to query this device - sometimes up to a minute. Obviously it's not a good user experience to sit around without any feedback. I do have access to SSH session logs (they are available as any normal python logs, i.e. I can log them to a file or print them to console, I am sure I can do more as well, just never looked into it much). My question is - what's the best way to handle providing live feedback to users while the API call is being … -
Django - Cannot filter a query once a slice has been taken
I'm using class based views, and when I try to use the "paginate_by = 6" with the "def get_context_data(self, **kwargs):", I get the following error: AssertionError at / Cannot filter a query once a slice has been taken. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2 Exception Type: AssertionError Exception Value: Cannot filter a query once a slice has been taken. Exception Location: C:\Users\xxxx\xxxx\xxxx\env\lib\site-packages\django\db\models\query.py, line 953, in _filter_or_exclude Python Executable: C:\Users\xxxx\xxxx\xxxx\env\Scripts\python.exe Python Version: 3.9.1 Python Path: ['C:\\Users\\xxxx\\xxxx\\xxxx', 'C:\\Program Files\\Python39\\python39.zip', 'C:\\Program Files\\Python39\\DLLs', 'C:\\Program Files\\Python39\\lib', 'C:\\Program Files\\Python39', 'C:\\Users\\xxxx\\xxxx\\xxxx\\env', 'C:\\Users\\xxxx\\xxxx\\xxxx\\env\\lib\\site-packages'] Server time: Sat, 29 May 2021 00:11:20 +0000 I'm trying to do the pagination for the filters result, like if no filters applied it should do the pagination for all Tasks. I've only found solution that do not use the functions with the Paginator. I would like to know if it is possible to do with the class based view and how, I'm a little lost in this. my views.py: class TaskList(LoginRequiredMixin, ListView): model = Task context_object_name = "tasks" template_name = "todo/tasks.html" paginate_by = 6 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["tasks"] = context["tasks"].filter(user=self.request.user) context["count"] = context["tasks"].filter(complete=False).count() context["projects"] = Project.objects.all() search_input = self.request.GET.get("search") or "" project_input = self.request.GET.get("project") or "" complete_input = … -
Different behaviour of Count function on Django
I have a very strange case, in which the behaviour of Count() differs if it is applied to a filtered model by id, or from other filters. I have these models: class Segment(models.Model): is_completed = models.BooleanField(default=False) class Waypoint(models.Model): is_visited = models.BooleanField("is visited", default=False) segment = models.ForeignKey("Segment", on_delete=models.PROTECT, related_name="waypoints", null=True, default=None) Let say we have two waypoints both not visited yet, both related to the same segment. I have one of these waypoints in a queryset, call it wp. Now if I perform: to_visit_filter = Q(waypoints__is_visited=False) seg = Segment.objects.filter(waypoints__in=wp, is_completed=False).annotate( wp_to_visit=Count('waypoints', filter=to_visit_filter)) print(seg.first().wp_to_visit) // 1 Instead, if I do: to_visit_filter = Q(waypoints__is_visited=False) segm_id = [w.segment.id for w in wp] seg = Segment.objects.filter(id__in=segm_id, is_completed=False).annotate( wp_to_visit=Count('waypoints', filter=to_visit_filter)) print(seg.first().wp_to_visit) // 2 In both cases seg.first() give the same object instance, but the number of waypoint to visit is different. Why? -
So can't use weasyprint what is the best thing to do?
Thanks in advance. I am trying to load a django project onto a server. I realized I was unable to update Cairo for weasyrprint. I would like to to change the code to some thing else. I was thinking pylatex?? This is for html to pdf. In my orders app views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('orders/order/pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = f'filename=order_{order.id}.pdf' weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS( settings.STATIC_ROOT + 'css/pdf.css')]) return response In my payment tasks.py # generate PDF html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')] weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets) # attach PDF file email.attach(f'order_{order.id}.pdf', out.getvalue(), 'application/pdf') Finally in my orders app pdf.html <html> <body> <h1>Mom and Pops</h1> <p> Invoice no. {{ order.id }}</br> <span class="secondary"> {{ order.created|date:"M d, Y" }} </span> </p> <h3>Bill to</h3> <p> {{ order.first_name }} {{ order.last_name }}<br> {{ order.email }}<br> {{ order.address }}<br> {{ order.postal_code }}, {{ order.city }} </p> <h3>Items bought</h3> <table> <thead> <tr> <th>Product</th> <th>Price</th> <th>Quantity</th> <th>Cost</th> </tr> </thead> <tbody> {% for item in order.items.all %} <tr class="row{% cycle "1" "2" %}"> <td>{{ item.product.name }}</td> <td class="num">${{ item.price }}</td> <td class="num">{{ item.quantity }}</td> <td class="num">${{ item.get_cost }}</td> </tr> {% endfor %} <tr class="total"> <td colspan="3">Total</td> <td … -
Angular "Uncaught (in promise): ChunkLoadError: Loading chunk 12 failed." error
I have recently rewritten my angular application. The previous project worked fine and I've not changed my django or apache2 configuration as it should just slip in. n.b. I have changed the django home.html to include "-es2015" in the appropriate file names. I'm currently getting the below errors in the inspector Resource interpreted as Stylesheet but transferred with MIME type application/javascript: "http://146.148.41.45/static/assets/js/frontendwikiconverter.js". 146.148.41.45/:33 GET https://p.typekit.net/p.css?s=1&k=oov2wcw&ht=tk&f=39203&a=2613646&app=typekit&e=css net::ERR_CONNECTION_REFUSED oov2wcw.css:1 Uncaught SyntaxError: Invalid or unexpected token styles.css:1 Uncaught SyntaxError: Unexpected token '<' 12-es5.js:2 ERROR Error: Uncaught (in promise): ChunkLoadError: Loading chunk 12 failed. main-es5.js:1 My app.module: import { BrowserModule } from '@angular/platform-browser'; import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core'; import { LocationStrategy, HashLocationStrategy } from '@angular/common'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { PerfectScrollbarModule } from 'ngx-perfect-scrollbar'; import { PerfectScrollbarConfigInterface } from 'ngx-perfect-scrollbar'; import { ToastrModule } from 'ngx-toastr'; import { JwtTokenService } from './services/jwt-token.service' import { IconModule, IconSetModule, IconSetService } from '@coreui/icons-angular'; import { LocalStorageService } from './services/local-storage-service.service'; import { NgxSmartModalModule } from 'ngx-smart-modal'; const DEFAULT_PERFECT_SCROLLBAR_CONFIG: PerfectScrollbarConfigInterface = { suppressScrollX: true }; import { AppComponent } from './app.component'; import { DefaultLayoutComponent } from './containers'; import { CommonModule } from "@angular/common"; import {AddToPlannerModule} from './views/planner/add-to-planner.module' import { TooltipModule } from 'ngx-bootstrap/tooltip'; const … -
How to refactor ViewSet that retrieves records created by authenticated user
I need these methods to retrieve/update/delete records created by authenticated user only. I'm clearly violating one of the key principles of web/software development. How can i refactor this viewset? class AddressViewSet(viewsets.ModelViewSet): queryset = Address.objects.all() serializer_class = AddressSerializer authentication_classes = (JWTAuthentication,) permission_classes = (permissions.IsAuthenticated,) def perform_create(self, serializer): serializer.save(user=self.request.user) def list(self, request, *args, **kwargs): self.queryset = Address.objects.filter(user=self.request.user) return super(AddressViewSet, self).list(request, *args, **kwargs) def create(self, request, *args, **kwargs): self.queryset = Address.objects.filter(user=self.request.user) return super(AddressViewSet, self).create(request, *args, **kwargs) def retrieve(self, request, *args, **kwargs): self.queryset = Address.objects.filter(user=self.request.user) return super(AddressViewSet, self).retrieve(request, *args, **kwargs) def update(self, request, *args, **kwargs): self.queryset = Address.objects.filter(user=self.request.user) return super(AddressViewSet, self).update(request, *args, **kwargs) def destroy(self, request, *args, **kwargs): self.queryset = Address.objects.filter(user=self.request.user) return super(AddressViewSet, self).destroy(request, *args, **kwargs) -
How to filter by JsonField tuple or list (Filtering only works for dictionaries?)
The documentation has info on querying JsonFields for dictionaries but not for lists or tuples. # models.py class Item(model): numbers = JSONField() # tests.py a = Item.objects.create(numbers=(1, 2, 3)) b = Item.objects.create(numbers=(4, 5, 6)) Item.objects.filter(numbers=a.numbers).count() # returns 0 Item.objects.filter(numbers__0=a.numbers[0]).count() # returns 0 Item.objects.all().count() # correctly returns 2 a.numbers # correctly returns (1, 2, 3) a.numbers[0] # correctly returns 1 How can I query or filter by a JsonField if that field is a tuple or list? -
Add Allauth login_required decorator to Baton.Autodiscover Admin subclass
I'm using Django-Baton, which injects CSS and JS styles and utilities around core Django template files, along with Django-AllAuth for more robust authentication and account access features. I'm using the documented method to redirect admin login to the AllAuth login page: from django.contrib import admin from django.contrib.auth.decorators import login_required admin.site.login = login_required(admin.site.login) Which I'm supposed to apply to "every instance of AdminSite." URLs: from baton.autodiscover import admin from django.urls import path, include urlpatterns = [ path("", admin.site.urls), path("baton/", include("baton.urls")), path("integrations/", include("integrations.urls")), path("queryfilter/", include("core.urls")), path("accounts/", include("allauth.urls")), ] Without baton.autodiscover, http://127.0.0.1:8000/ forwards, as desired, to accounts/login, but not so with autodiscover present. INSTALLED_APPS = [ "dal", "dal_select2", "dal_queryset_sequence", "baton", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.sites", # required for allauth "users", "core", "integrations", "allauth", "allauth.account", "allauth.socialaccount", "baton.autodiscover", ] Wondering if I need to subclass django.contrib.admin and apply the auth decorator somehow prior to baton.autodiscover, but not sure how/where to do it. Thanks for your input, and I'm pretty new to Django so thanks also for your patience. -
I'm having a TypeError: 'module' object isn't iterable when i run "python mange.py runserver in termux
Exception in thread django-main-thread: Traceback (most recent call last): File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/urls/resolvers.py", line 600, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/data/data/com.termux/files/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/data/data/com.termux/files/usr/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/urls/resolvers.py", line 413, in check messages.extend(check_resolver(pattern)) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/urls/resolvers.py", line 412, in check for pattern in self.url_patterns: File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/utils/functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/urls/resolvers.py", line 607, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'blog.urls' from '/storage/emulated/0/application/blog/urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Search Error with django-datatable-view 0.9.0 using custom processor
I'm using a custom processor with django-datatable-view to provide a link to a related record. The DataTable search breaks when I use this approach. Sorting works fine. If I remove the custom processor, search works fine. Chrome console shows 500 (Internal Server Error) for the GET request. Is there a way to resolve this issue or approach the link in a different way? class MyDatatable(Datatable): some_id = columns.TextColumn( 'Some ID', sources='some_id', processor='get_some_id_link') class Meta: model = MyInventory columns = ['some_id', 'city', 'county', 'state', ] ordering = ['some_id'] def get_some_id_link(self, instance, *args, **kwargs): url = reverse('detail_view', kwargs={'slug': instance}) return '%s%s%s%s%s' % ("<a href='", url, "'>", instance, "</a>") -
not able to authenticate user
views.py def Login(request): if request.method == "POST" : username1=request.POST['usernm'] password1=request.POST['passwd'] user=authenticate( username=username1 , password=password1) if user is not None: login(request, user) return render(request,'loginsuccess.html') else: return render(request,'login.html') model.py class My_User(models.Model): first_name=models.CharField(max_length=70,primary_key=True) last_name=models.CharField(max_length=70) mail=models.EmailField() username=models.CharField(max_length=70) password=models.IntegerField(max_length=60) html form {% csrf_token %} username =<input type="text" name="usernm" id="usernm" ><br> password =<input type="password" name="passwd" id="passwd" ><br> <button type="submit" > Login </button> </form> here i am not able to authenticate data i don't know whats the issue i am facing here, i am getting the user in the views as none because of which i am not able to login