Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Pagination with graphql and django
I am using react(fe), django (be) and graphql. Currently I send request when I reach bottom of my page to fetch more "posts" to my infinitescrolling feed. In django-graphene this would work like Return Post.objects.all() [offset, offset+limit]. But what should I do if for example my return statement weren't as easy as just fetching all posts? What if I need to return the posts in a sorted way that they aren't already in the DB? Right now, I am doing it like Return custom_sort(Post.objects.all())[offset, offset+limit]. Still working, but I need to sort them on every request (I think, if django aren't cashing it). How would one do this so I only need to sort them once, and then save those values for say a minute so I doesn't need to sort everytime I request? -
Add button on Image ( JavaScript )
I am building a BlogApp and I am trying to add button on Image. I am showing image from django database in javascript (HTML). I am trying to add clickable button on Image. views.py def user_stories(request): posts = BlogPost.objects.filter(user=request.user) template.html <script> var currentSkin = getCurrentSkin(); var blogposts = new BlogPost('blogposts', { skin: currentSkin['name'], autoFullScreen: currentSkin['params']['autoFullScreen'], localStorage: true, stories: [ // {% for post in posts %} BlogPost.buildTimelineItem( '{{ post }}', '{{ user.profile.file.url }}', '{{ post.user }}', '{{post.id}}', timestamp(), [ [ '{{post.id }}-1', 'photo', 3, '{{ post.image.url }}', '', false, false, timestamp(), ], ] ), // {% endfor %} ], }); </script> {{ post.image.url }} is showing image, AND i am trying to add on it. I also tried by adding :- '{{ post.image.url }}<button type='submit' </button>', BUT it is not showing on image. I have no idea , how can i add button on image. Any help would be Appreciated. Any help would be Appreciated. -
Moving from function view to class based view
I have already running table with quite a lot of data. This table was designed years ago with not very clear assumption. Table contains list of "services" we own. There is column 'service_id' which points to given entity. This entity has many instances. In fact, each month, we add new row (new instance), with new data but same 'service_id' for given entity. Now, let's move to Django. I use generic class based views, like ListView, CreateView, DetailView, etc. For this only specific case I need to use function view. How to rewrite this function view to class based view? VIEW: def EsiDetailedView(request, requested_service_id): last_object=Esi.objects.filter(service_id=requested_service_id).aggregate(Max('id')) last_object_id=last_object.get("id__max") last_service=Esi.objects.get(id=last_object_id) args={} args['service'] = Esi.objects.filter(service_id=requested_service_id).order_by('-end_date') args['details'] = last_service #to show details of single service return render(request, 'esi/esi_details.html', args) URLS: urlpatterns = [ path('<int:requested_service_id>/', EsiDetailedView, name='esi-detail') ] -
How to handle emailserver exceptions in django-allauth eg ConnectionRefusedError?
I have implemented django-allauth ok in my django project . however if there is an issue with connecting to the mail server i get this ugly error. How can I handle these kind of exceptions for allauth so that the user gets friendly user error on the page. -
I am getting this error :-ERRORS: P: (corsheaders, E006) CORS ALLOWED ORIGINS should be a sequence of stringsg
I am getting this error :-ERRORS: P: (corsheaders, E006) CORS ALLOWED ORIGINS should be a sequence of stringsg How to solve this error... And move forward... -
Is there any way to create Custom management command to test a task in django framework?
I have to design a custom management command to test a task of loyalty point creation functionality available in tasks.py. This task takes arguments as csv_file_upload_id,csvfilename,orgid,groupid from api. task reads the csv file and validates data and save the data to DB. Now Ihave to design a custom management command to execute above task. any help is most valuable..... thankyou -
Config.js file in django-ckeditor not applying configurations
I have been trying to style Django-CKEditor by modifying the config.js file, all to no avail; my custom configuration in config.js is not working. I have gone as far as manually modifying the default CSS files, but all these modifications fail to work as well. Although when I use Chrome's developers tool to make some modifications, they all worked. My question is, is the config.js file not usable in Django? config.js CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; config.uiColor = '#000000'; config.enterMode = CKEDITOR.ENTER_BR; config.width = "100%"; config.height = "300"; config.extraPlugins = 'autogrow'; config.autoGrow_minHeight = 250; config.autoGrow_maxHeight = 600; }; settings.py CKEDITOR_UPLOAD_PATH = "images/avatar/" CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono-lisa', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar_Custom': [ {'name': 'styles', 'items': ['Styles']}, {'name': 'basicstyles', 'items': ['Bold', 'Italic', 'Underline']}, {'name': 'colors', 'items': ['TextColor']}, {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']}, {'name': 'insert', 'items': ['Smiley']}, ], 'toolbar': 'Custom', }, } HTML <script type="text/javascript" src="{% static 'ckeditor/ckeditor/ckeditor.js' %}"></script>