Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How do I "request.user" in django shell
I want to query my django User models on authenticated user on shell. How do I authenticate a user on shell? -
How to check index numbers from database using Django?
I've got a system built in Django which receives data. I store the data as follows: id | sensor | message_id | value ----+--------+------------+------- 1 | A | 1 | xxx 2 | A | 2 | xxx 3 | A | 3 | xxx 4 | B | 1 | xxx 5 | B | 2 | xxx 6 | B | 4 | xxx As you can see, the message_id increases per sensor with every subsequent message that we receive. The message_id number 3 is missing for sensor B though. I now want a way to know about this when it happens. So I want do a check whether a message is missing in the past five minutes. The simplest way I thought of doing this is by querying the message_id for one sensor and then loop over them to check whether any number is skipped. Something like this: five_minutes_ago = datetime.now() - timedelta(minutes=5) queryset = MessageData.objects.filter(created__gt=five_minutes_ago).filter(sensor='B').order_by('message_id') last_message_id = None for md in queryset: if last_message_id is None: last_message_id = md.message_id else: if md.message_id != last_message_id + 1: missing_messages = md.message_id - last_message_id - 1 print(f"{missing_messages} messages missing for sensor {md.sensor}") But since I've got hundreds of sensors … -
Django wkhtmltopdf loading stuck
same issue. Just checking if it has been solved. More context: I'm using django-wkhtmltopdf 3.3.0 and wkhtmltopdf 0.12.5 (with patched qt) on ubuntu. options = { 'title': "PDF Title", 'page-size': 'A4', 'orientation': 'portrait', 'margin-top': '20mm', 'margin-right': '10mm', 'margin-bottom': '20mm', 'margin-left': '10mm', 'load-error-handling': 'ignore', 'quiet': None, 'enable-local-file-access': True, 'header-spacing': 5, 'footer-spacing': 5, } When I run this command, my server gets stuck with this message: Loading pages (1/6) [=================> ] 29% If I ctrl C my server, I can see the command that was running: /usr/local/bin/wkhtmltopdf --enable-local-file-access --encoding utf8 --footer-spacing 5 --footer-html /tmp/wkhtmltopdfap_vk62a.html --header-spacing 5 --header-html /tmp/wkhtmltopdfhfdro6i1.html --load-error-handling ignore --margin-bottom 20mm --margin-left 10mm --margin-right 10mm --margin-top 20mm --orientation portrait --page-size A4 --title "PDF Title" /tmp/wkhtmltopdfku94woo9.html - The latter works fine when execute on bash (or python shell). Thank you random stack overflow shell deities. -
How to use first variable from first loop for second variable in another for loop in django template
How I can use the first variable from the first loop in the second loop in a Django template like this {% for key in data %} {% for value in data.key %} <div>{{value}}</div> {% endfor %} {% endfor %} I have the data is a nested dict in python like this data = { 'Google_Suite': {'Google Sheet': <QuerySet [<Course: Google Sheet level 1>, <Course: Google Sheet level 2>, <Course: Google Sheet level 3>]>, 'Google Docs': <QuerySet [<Course: Google Doc level 1>, <Course: Google Doc level 2>, <Course: Google Doc level 3>]>, 'Google Slide': <QuerySet [<Course: Google Slide level 2>, <Course: Google Slide level 3>]>}, 'Language': {'English': <QuerySet [<Course: English level 1>]>}} I tried but it's nothing to show -
Terminal mail 'my/path/manage.py': [Errno 1] Operation not permitted
settings.py CRONJOBS=[ ('* * * * *', 'my_app.cron.my_scheduled_job') ] cron.py def my_scheduled_job(): Test.objects.create(name='tested',date_generated=datetime.datetime.now()) After running "python manage.py crontab add" and "python manage.py runserver", Not object is added into Test model and I get terminal mail error "Terminal mail 'my/path/manage.py': [Errno 1] Operation not permitted" -
Django - Questionnaire - ModelFormSet - Cannot assign
Alright, so I'm following a tutorial on creating a small questionnaire with Django. A User can create a survey with different multiple choice questions. Since they're multiple choice questions, users can also set the options for the questions. A "survey taker" can then start a survey, select his or her preferred questions and submit the form. I would like to only show a single question per page so I'm trying to work with modelformset_factory and implement pagination using the build in paginator. The form is rendered correctly and a user can submit an answer, however, the form fails before "formset.is_valid()", I just can't figure out why; ValueError at /surveys/1/submit/4/ Cannot assign "'2'": "Answer.option" must be a "Option" instance. So I can not save an integer and I somehow have to relate the integer with the id from the option model... But I can't access cleaned_data yet so I guess I'm missing something here. Did I forget something within the formset? I've been staring at this for a while now so any help is appreciated. #Views def submit(request, survey_pk, sub_pk): # Let's retrieve the survey which is created by the survey-taker try: survey = Survey.objects.prefetch_related("question_set__option_set").get( pk=survey_pk, is_active=True ) except Survey.DoesNotExist: raise …