Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: The view curd.views.emp didn't return an HttpResponse object. It returned None instead
ERROR:The view curd.views.emp didn't return an HttpResponse object. It returned None instead -
how to display pdfs in webpage using html in django
how to retreive multiple pdfs from database and display it in webpage using html in django? this is my function in views.py def PdfView(request): pdf = EbookModel.objects.all() form=SearchForm() context ={ 'pdf':pdf, 'form':form, } here's my html file: {% extends 'basic.html' %} {% block content %} {% for pdfs in pdf %} <a href="">{{pdfs.title}}</a> {% endfor %} <form method ='post'> {% csrf_token %} {{form}} <input type="submit" value = "Submit"> </form> {% endblock %} -
Can I access channel layer consumers in django channels?
I am working with django channels and got a resource intensive task which due to hardware limitations I try to run as little as possible. I run this task only when 1 consumer is connected to the channel layer, but I also need to run it when a new consumer connects (the data new consumers need is at the other consumers not on the main server). This might sounds a bit vague, but the how and why is not really import for this question. In short: whenever a new user joins I'd like 1 of the already connected users to send a message, (doesn't matter which user). Is there a way to access channel layer consumers and use consumer.send() that he needs to send a message? -
What is Token Claim In JWT?
I have been learning JWT authentication in Django Rest Framework I came across customizing Token claims I am pretty new to token based authentication https://django-rest-framework-simplejwt.readthedocs.io/en/latest/customizing_token_claims.html And I also saw certain custom token claims example from rest_framework_simplejwt.serializers import TokenObtainPairSerializer class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super(MyTokenObtainPairSerializer, cls).get_token(user) # Add custom claims token['username'] = user.username return token For what purpose are we using this? Any summarized details will be helpful :) -
Restricted login from WordPress main site to Django web app
I am looking to integrate a wordpress website at mydomain.com with a django web app set up at analytics.mydomain.com. The wordpress website is the main website, where payments are accepted, a user area are that contains the link to the Django analytics tools. The Django app is hosted on another site (e.g Heroku) but is set up as a subdomain. I would like the database and user authentication and information on WordPress to act as a master to the Django slave rather than vice versa. How can I integrate authenticated users on the wordpress site, who have paid for analytics functionality, to have access to the django app without requiring login in again, or how can I share the user logins automatically - like an single sign on or something similar? What is the best way to go about this? -
Passing parameters to links in a many to many field
I am trying to pass a parameter to the link so that when the user do click to one of the categories he will be redirected to a page listing all the posts with the clicked categor -
I have a question about making a POST request with Django rest api with uploading multiple images
enter image description here I have a question about making a POST request with Django rest api with uploading multiple images. My question : To get the images from a post Request i am using this : files_list = request.FILES.getlist('homeworkimage_set') the images are created in the database correctly. but in the response : i am not getting this : homeworkimage_set :{'image': url},{'image':url}. i don't know if i am missing something. my homeworkimage_set(image below) is empty in the response even though the images are correctly created in the database. Is it necessary to get the images urls in the response even though i the images are saved in the database? If you have any idea how can i get the images urls in the response could please help me on that. Thanks in advance. -
Django: Reverse for '<WSGIRequest: GET '/index/'>' not found. '<WSGIRequest: GET '/index/'>' is not a valid view function or pattern name
I am getting the above error when i tried to redirect from my UserAuth app to UserArea app. It says 'NoReverseMatch at /index/'. UserAuth/views.py def loginUser(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # return render(request, 'home.html') return redirect('nsUserArea:urlUserHome') else: messages.info(request, 'User name or password is incorrect') return render(request, "Login.html") USerAuth/urls.py urlpatterns = [ path('', views.loginUser, name="urllogin"), path('logout/', views.logoutUser, name="urllogout"), path('register/', views.register, name="urlregister"), path('home/', views.home, name="urlhome"), ] UserArea/urls.py urlpatterns = [ path('', views.IndexPage, name="urlUserHome"), ] My main project urls.py file is this: urlpatterns = [ path('admin/', admin.site.urls), path('', include('UserAuth.urls', namespace="nsUserAuth")), path('index/', include('UserArea.urls', namespace="nsUserArea")), ] Can some one help? -
More than one cart returned
I am getting errors while doing cart work. When plus button is clicked, it says error in line 60 and says more than one cart returned enter image description here -
django about deleteview and view
I'm a super newbie, so please refer to this and read it. I am creating a bulletin board that communicates by DB <> API <> WEB method. I want to create a view to delete comments, but an Improperly Configured error occurs when I request to delete comments from the web. Can I define a query set without Model,DB? Or is my code a problem? Which view should I use? Improperly Configured Error with deleteview, Method not allowed with view generic.deleteview view WEB view.py class Commentapi_delete(generic.DeleteView): def delete(self, request, *args, **kwargs): datas = { 'pk': self.kwargs['pk'], 'id': self.kwargs['id'] } url = 'http://127.0.0.1:8080/boardapi/' + str(datas['pk']) + '/comment/' + str(datas['id']) + '/delete/' c_delete = requests.delete(url, params=datas) print(datas) print(c_delete) return redirect(reverse('board_detail', kwargs={'pk': self.kwargs['pk']})) API view.py class CommentUpdateDeleteView(generics.RetrieveUpdateDestroyAPIView): model = Comment queryset = Comment.objects.all() serializer_class = CommentSerializer -
Serverless Django app (AWS Lambda via Zappa) times out when trying to OAuth to Twitter
I've got a Django app setup to use django-allauth to connect to Twitter. The flow is all working locally and I've followed the same setup steps on Lambda to add my tokens, site, etc. When I try to access the login url (/accounts/twitter/login/) the request eventually times out with this message from AWS Lambda: {"message": "Endpoint request timed out"} The last message from zappa tail before the timeout event is: [1619019159940] [DEBUG] 2021-04-21T15:32:39.939Z 7f66a0e3-58de-4612-82c0-54590d69676f Starting new HTTPS connection (1): api.twitter.com:443 I've seen that the gateways have a 30 second timeout but I don't think it should be taking this long anyway. Locally, it's taking a couple of seconds. Does anyone with knowledge of these platforms have an idea where the bottleneck might be and where the issue could be? Or have any pointed questions to help debug? Things I've already checked and (tentatively) ruled out: The database backend is AWS Aurora Serverless, and I did worry that the double-serverless setup might be causing the slow speeds. However, a simple call of the Django management command (zappa manage dev migrate returns takes less than a second so I've ruled that out for now. Plus the Admin dashboard loads fine which is … -
Testing request.resolver_match in a Django context_processor
I have a Django context processor that puts the name of the current URL into the template context: def url_name(request): url_name = False if request.resolver_match: url_name = request.resolver_match.url_name return {"url_name": url_name} This works - if I visit / then {{ url_name }} in the template will display "home" because I have a URL pattern like: path("", HomeView.as_view(), name="home"), I would like to write a unittest for this context processor. I could do it like this: from django.test import Client, RequestFactory, TestCase from myapp.context_processors import url_name class URLNameTestCase(TestCase): def test_url_name(self): response = Client().get("/") self.assertEqual(response.context["url_name"], "home") That succeeds, but I'd like to unitttest the url_name() method on its own, outside of the response cycle. I've tried this: class URLNameTestCase(TestCase): def test_url_name(self): request = RequestFactory().get("/") context = url_name(request) self.assertEqual(context["url_name"], "home") But that fails because, in this situation, within url_name(), request.resolver_match is None. Why is that? -
Filtering data based on a condition in django template
I want to count total objects based on a condition in django template. Lets suppose my model is below: class Vote(models.Model): election = models.ForeignKey(Election, on_delete=models.CASCADE) candidate = models.ForeignKey(UserProfile, on_delete=models.CASCADE) voting_booth = models.ForeignKey(Booth, on_delete=models.CASCADE) Here i want total, votes based on each voting_booth. I can filter it in views but want to show all the votes with its respective booth. Template is: {% for v in vote %} <div class="col-md-6 col-sm-6 col-lg-6 col-xl-4"> <div class="dash-widget" style="box-shadow: 5px 5px lightblue;"> <div class="dash-widget-info"> <h5>Total Voters:{{v.**???**.count}}</h5> <h5>Voting Booth:{{v.voting_booth}}</h5> <h5>Total Vote Earned:{{v.**???**.count}}</h5> </div> </div> </div> {% endfor %} Thanks in Advance.. -
Can We Create Custom Password Reset View In Django?
I am currently working on a my college project, I stuck in password reset functionality in project. I know Django provide built-in PasswordReset CBV(Class Based Views). but I want to implement custom template using bootstrap 4.0. I am using django v3.3.1 for development so there is any solution for my problem. -
Django Rest Framework - Attribute Error: 'function' has no attribute 'get_extra_actions'
everybody. So I'm learning about django rest framework and how to deploy on Heroku. I'm having this issue in my app and I have no ideia how to solve it. views.py: from rest_framework import viewsets, status from rest_framework.decorators import api_view from rest_framework.views import Response from api import models, serializers from api.integrations.github import GithubApi @api_view(['GET']) class LibrarynViewSet(viewsets.ViewSet): queryset = models.Library.objects.all() serializer_class = serializers.Library(queryset, many=True) lookup_field = "name" def retrieve(self, request, login=None): return Response(serializers.data) routes.py: from django.urls import include, path from rest_framework.routers import DefaultRouter from api import views routers = DefaultRouter() routers.register("organization", views.LibraryViewSet, basename="Library") urlpatterns = [ path("", include(routers.urls)), ] Error: extra_actions = viewset.get_extra_actions() AttributeError: 'function' object has no attribute 'get_extra_actions' As I said, I'm learning so I have no ideia how to solve it. I would appreciate if you help me. Thank's a lot. -
Password 1 password 2 cannot override label in model form django
So i was using crispy forms to display my register view as i wanted to override the defaults labels i ran into an issue when it comes to the password label and the confirmation password label, i simply cannot change then even when i override then as i did with the username one, would appreciate any help. Here is the abstractuser model class CustomUser(AbstractUser): setor_escolhas = ( ("R", "Revendedora"), ("C", "Concessionária"), ) setor= models.CharField(max_length=1,choices=setor_escolhas, blank=False, null=False) Here is mine register form: class UserCadastroForm(UserCreationForm): email = forms.EmailField() class Meta: model = CustomUser fields = ['username', 'email', 'password1','setor', 'password2' ] labels={'username':'Usuário','setor':'Setor da sua empresa','password1':'Senha'} And here is mine template format {% extends "APP_IVG/layout.html" %} {% load crispy_forms_tags %} {% block content %} <div class= "content-section"> <form method= "POST"> {% csrf_token %} <fieldset class = 'form-group'> <legend class= "border-bottom mb-4"> Junte-se hoje</legend> {{ form|crispy }} </fieldset> <div class = "form-group"> <button class= "btn btn-outline-info" type= "submit"> Cadastre-se </button> </div> </form> <div class= "border-top pt-3"> <small class= "text-muted"> Já tem uma conta? <a class= "ml-2" href = "{% url 'Login' %}"> Clique aqui </a> </small> </div> </div> {% endblock content %} -
Django: How to manage different versions of the settings.py
We need to have different settings for different regions. For example: settings_us.py settings_uk.py settings_au.py UK and AU are copied from settings_us.py. Most parts of the settings are the same across all regions except for some parameters like reading DB endpoints that need to be changed. Having three versions of the settings is very hard to manage. I wonder if there is a cleaner way to manage these settings? Thank you. -
django only redirecting to base url not
I am trying to redirect back to the url that made a request before request was made to an external login service, using amiddleware. The solution I currently have only redirects to the base url (http://127.0.0.1:8000) When I go to, http://127.0.0.1:8000/asasas I am redirected to https://external_login/login?abc=def&the_url=http://127.0.0.1:8000/asasas which is correct, after a successful login, I am redirected to http://127.0.0.1:8000 instead of http://127.0.0.1:8000/asasas. Is there any way I can redirect to the calling URL before temporarily redirect to external login? Middleware class AttemptRedirect(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): url = request.build_absolute_uri() if 'username' not in request.session: if request.GET.get('xyz'): validate = 'https://external_login/validate?abc=def&xyz={}&the_url={}'.format(request.GET.get('xyz'), url) req = urllib.request.Request(validate) gcontext = ssl.SSLContext() response = urllib.request.urlopen(req, context=gcontext).read() result = response.decode('utf-8') if result[0:3] == 'yes': request.session['username'] = result[3:] new_url = urlparse(request.build_absolute_uri()) query = parse_qs(u.query) query.pop('xyz', None) new_url = new_url._replace(query=urlencode(query, True)) new_url = urlunparse(new_url) return redirect(new_url) else: return redirect("https://external_login/login?abc=def&the_url={}".format(url)) else: response = self.get_response(request) return response -
Django query depth search
I have an djangorestframework app where I have data from external source which I cannot affect. There is tier structure with employees and supervisors. models.py : class Employee(models.Model): name = models.CharField(max_length=100) supervisor = models.CharField(max_length=100) date = models.DateField(max_length=100) I know this is wrong and the supervisor should be foreign key, but that is not under my controll. What I need is that I get a request for high level supervisor, so the final query will return all employees for the requested supervisor and if some of the employee is also a supervisor then return all his employees till it comes to the lowest level where the employees are not supervisors. It should work like Depth-first search. Is there any way to return this query? -
Django Redirect from one app to another after login
I want to redirect my userauth app to userarea app after login. The login happens in the view inside userauth. I want to go to userarea urls to acces my view there. MainProject/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('UserAuth.urls', namespace="nsUserAuth")), path('index/', include('UserArea.urls', namespace="nsUserArea")), ] userauth/urls.py urlpatterns = [ path('', views.loginUser, name="urllogin"), path('logout/', views.logoutUser, name="urllogout"), path('register/', views.register, name="urlregister"), path('home/', views.home, name="urlhome"), ] userauth/views.py def loginUser(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('nsUserArea:urlUserHome') else: messages.info(request, 'User name or password is incorrect') return render(request, "Login.html") userarea/urls.py app_name = "UserArea" urlpatterns = [ path('', views.IndexPage, name="urlUserHome"), ] userarea/views.py def IndexPage(request): return redirect(request, 'home.html') -
With Django/Bootstrap how can I load data from file into variable, make it global variable and use text/data
Want to load the file into a variable without saving file info the server. Used load fild: <div class="mb-3 col-md"> <label for="formFileSm" class="form-label">1. Load your data</label> <input class="form-control form-control-sm" id="formFileSm" type="file"> </div> But can not save into variable and access it from other views. -
'$' is not recognized as an internal or external command, operable program or batch file when running Django
I'm new to Django and I'm trying to run a project on cmd: ''' $ python3 manage.py runserver ''' However, it shows: ''' '$' is not recognized as an internal or external command, operable program or batch file. ''' -
How to show a loop from function inside a class in a template?
I want to create a table with the values in "a" but the function is inside a class: # Views.py class DashboardView(LoginRequiredMixin, TemplateView): template_name = 'dashboard.html' def get_test(request): a = ['hola','chau','como','va'] #return a return render(request, 'dashboard.html', {'name': a}) # HTML template <div class="table-responsive"> <table class="table table-striped"> <thead> <tr> <th><span>Date</span></th> </tr> </thead> <tbody> {% for i in name %} <tr> <td><span>{{i}}</span></td> </tr> {% endfor %} </tbody> </table> </div> I've tried this function (outside a class) in another template and it works: def get_test(request): a = ['hola','chau','como','va'] return render(request, 'test.html', {'name': a}) But I want that function inside the class because I call all the class at the URL.py: path('dashboard/', DashboardView.as_view(), name='dashboard'), I would like something like this: Thanks! -
Image search in Django
I'm trying to query images stores in 'Static' and stored in Postgres. How do I format the HTML to call the image from the Static folder based on the name? HTML file: {% for image in object_list %} {{ image.name }}, {{ image.photo }} it only shows the name of the image, not the view. models.py class image(models.Model): name = models.CharField(max_length=255) photo = models.ImageField(upload_to="static") class Meta: verbose_name_plural = "images" def __str__(self): return self.name views.py class SearchResultsView(ListView): model = image template_name = 'search.html' def get_queryset(self): # new query = self.request.GET.get('q') object_list = image.objects.filter( Q(name__icontains=query) | Q(photo__icontains=query) ) return object_list -
Django Crud Help - Update and Delete
I'm new to django and trying to complete a crud project, however I'm running into problems with updating and deleting. I have tried a numerous ways of troubleshooting, but I'm keep coming up short. I have provided the error message for the update portion of it. So I'm seeking advice. Error Message: RuntimeError at /update/1 Below is a the code for urls, views, and html. URL urlpatterns = [ path('admin/', admin.site.urls), path('add/', views.add, name="add"), path('', views.show, name="show"), path('update/<update_id>/', views.update, name="update"), path('delete/<delete_id>/', views.delete, name="delete"), ] Views def add(request): form = StudentForm(request.POST or None) #student = Student.objects.all() if form.is_valid(): form.save() return render(request, 'add.html', {'form': form}) def show(request): student = Student.objects.all() return render(request, 'show.html', {'student': student}) def update(request,update_id): student = Student.objects.get(id=update_id) form = StudentForm(request.POST, instance=student) if form.is_valid(): form.save() return HttpResponseRedirect('/') return render(request, 'update.html', {'student':student}) def delete(request,delete_id): student = Student.objects.get(id=delete_id) student.delete() return HttpResponseRedirect('/') **Update Html:** {% extends 'base.html' %} {% block content %} Update {% csrf_token %} ID Name Contact Update Record Show Details {% endblock content %} It will greatly appreciate for some guidance, maybe I'm not seeing something. Thank you in advance