Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use pagination after you query for results?
I'm trying to make a search functionality with 2 parameters. Everything works fine, until I want to use pagination. I've been testing it by displaying only 1 element per page. This works, until I want to change the page. When I change the page, I get no results even though I have entries that should be displayed in the DB. Tbh I think that I should somehow store the search parameters and do the query when the page changes, but that makes no sense for me. How does pagination help if I still have to do the query everytime I change the page? Views.py def cautare(req): intrari_oferte = Oferta.objects.get_queryset().distinct('denumireMeserie') context = { 'title': "Cautare loc de munca | Best DAVNIC73", 'oferte': intrari_oferte } return render(req, "../templates/pagini/cautare-loc-de-munca.html", context) def locuridemunca(req): jud = req.POST.get('inputjudet') meserie = req.POST.get('inputmeserie') intrari_oferte = Oferta.objects.filter(judet=jud, denumireMeserie=meserie) pagIntrari = Paginator(intrari_oferte, 1) page = req.GET.get('page') pagina = pagIntrari.get_page(page) context = { 'title': "Cautare loc de munca | Best DAVNIC73", 'judet': jud, 'meserie': meserie, 'pagina': pagina } return render(req, "../templates/pagini/locuri-de-munca.html", context) cautare template {% extends 'base.html' %} {% load static %} {% block content %} <div class="container container-centru"> <h1 class="heading-contact">Cauta loc de munca</h1> <form class="form-contact" action="{% url 'locuridemunca' %}" method="POST"> … -
How to select/unselect/delete multiple django items in a table with the same checkbox?
I have this table of items with their details, and I have implemented a method to 'select' a few items using a submit button, which submits all checked checkboxes on each item. This is the code for the checkbox: <input name='quiz-pids' id='checkbox-{{ quiz.id }}' type="checkbox" value="{{ quiz.id }}" required> As you can see, I have passed the quiz.id in the checkbox value. This is my submit button I am using: <input type="submit" class="btn btn-primary select-btn myitems-select-btn" value='Finalize Items' required> Here, I have not mentioned what this button will do except than submit. This is the function which processes the data input by submit button. class UploadedItems(ListView): model = ItemBatch ordering = ('uploaded',) context_object_name = 'plan' template_name = 'classroom/teachers/item_list.html' def post (self, request, *args, **kwargs): # get the selected quizs quizs = request.POST.getlist('quiz-pids') # retrieves thoses quizes from the database: print("pids returned are ", quizs) # items = ItemBatch.objects.filter(pid__in=quizs) for i in quizs: print("before", i) i = get_object_or_404(ItemBatch, id=i) i.rtd = 'True' i.save() print("after", i.truck_type) # print("items are",items) return redirect('teachers:upload_batch') As you can see, my function 'post' accepts only quiz-pids because of this line request.POST.getlist('quiz-pids'). Now my question is, I also want to delete and unselect my items. But, because my … -
Is this okay to add slashes in below code at template of Django?
I am trying to solve a problem. During the process I got this question. {% if reuqest.path == '/{{sub_cat.sub_cat_parent.cat_slug}}/{{sub_cat.sub_cat_slug}}/' %} <div class="alert-secondary">Active</div> {% else %} How do I properly include slashes in here '/{{sub_cat.sub_cat_parent.cat_slug}}/{{sub_cat.sub_cat_slug}}/'? Is it okay to use {{ within {% template tags? what am I doing wrong in here? -
Annotate with count for each user then order by date of latest occurrence
I want to get the count of unread messages for each user_from which ordered by the date of last message from her/him. class Chat(models.Model): user_from = models.ForeignKey(settings.AUTH_USER_MODEL) user_to = models.ForeignKey(settings.AUTH_USER_MODEL) is_read = models.BooleanField(default=False) added_on = models.DateTimeField(auto_now_add=True) message = models.CharField(max_length=255) I'm seeking for some queryset(s) outputing like this: +-----------+--------------+--------------+ | from_user | unread_count | last_time | +-----------+--------------+--------------+ | 1| 1| 2019-05-17 | | 5| 6| 2019-05-13 | | 3| 3| 2019-05-09 | +-----------+--------------+--------------+ -
How to cahce edit form on POST requests in Django?
Question is about using cache_page decorator in Django. Goal is to cache form when it submitted , that is with filled POST data. Explanation: For example I have an edit form and I want to cache it state so that when next time user opens it it would be taken from cache filled with the data from the last submit( if it has passed validation of course). What cache_page does by default – caches get requests , that is form state before it has been corrected and submitted. Cache invalidation in this case on me, I know how to do it. Question – how to cache form after it got corrected/edited to show it next time from cache ? If it is possible to do with template {%cache%} tags -that's suitable as well. Sorry if the question is naive.. Thx. -
Get currently logged user to Comment Form
I have a Comment Form for my django project, which has a two columns: Author, Text. I would like to make a author to be the currently looged user and be not able to edit that value. Is there a way to do it? Here are my codes forms.py class CommentForm(forms.ModelForm): author = forms.CharField(label = "名前", max_length=10, widget=forms.TextInput(attrs={'style': 'position: relative;left: 0px;'})) class Meta: model = Comment fields = ('author', 'text',) views.py def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('Post-detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/add_comment_to_post.html', {'form': form}) models.py class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text -
How to monitor API throttling in Django
I am building a solution where I have one core API on which I have implemented the throttling as per the official documentation https://www.django-rest-framework.org/api-guide/throttling/. But I wonder how will I be able to monitor the requests so that no genuine user of the app gets blocked and if so should be able to unblock it. My settings.py file REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.ScopedRateThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'students': '1/minute', } } And My views.py class StudentViewSet(viewsets.ModelViewSet): throttle_scope = 'students' -
django rest_framework ckeditor error kode
I'm constantly getting a ckeditor problem and can't fix it. please help me! the error in the code is: GET /static/ckeditor/ckeditor/skins/moono-lisa/icons.png?t=e1836357e HTTP/1.1" I have received the same error at least a thousand times and can not solve. -
How to run django server from python script without using terminal?
Generally a django server is started using python manage.py runserver in the terminal. I want to run the server by running a python script. How to do so? -
Close user access to the page
I want to close access for users to page of survey if the survey is completed or the user has already passed this survey. How can I do this? My models.py class Survey(models.Model): title = models.CharField(max_length=1024) start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) description = models.CharField(max_length=1024, null=False, blank=True) class Ballot(models.Model): ip = models.GenericIPAddressField(default='127.0.0.1') survey = models.ForeignKey('Survey', models.CASCADE, null=True) My views.py from django.utils.timezone import now class SurveyView(View): def get(self, request, id): survey = get_object_or_404(Survey, id=id) if survey.end_date.date() < now().date(): return redirect('index') respond = Ballot.objects.filter(survey_id=id) x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ipc = x_forwarded_for.split(',')[-1].strip() else: ipc = request.META.get('REMOTE_ADDR') for ip in respond: if ip == ipc: return redirect('index') else: return render(request, 'polls/survey.html', {'survey': Survey.objects.get(id=id)}) In my code I get error: none type object has no attribute date; And if I delete the date condition, then the ip condition does nothing. -
How do I execute python script in html button to process files uploaded to Django temporary memory
I am having a challenge executing python script in a button click to process uploaded files existing in Django temporary memory I have developed a html code for the button on templates in django linked it to urls and also created a python script function to be executed in views. URLS from django.urls import path, include from . import views app_name = 'photos' urlpatterns = [ path('progress-bar-upload/', views.ProgressBarUploadView.as_view(), name='progress_bar_upload'), path('output/', views.output, name='Script'), ] VIEWS def processFiles(): #python script to process files files = files uploaded to memory read(files) data = (final table) return jsonResponse(data) HTML <div>Relay 1: <button onclick="href="{% url 'photos:Script'%}" ">Execute Script </button> </div> I expect to upload files, process them in Django temporary memory using python script through a button click then display the final table output to interface -
remember me not working in django custom admin
I am creating a custom admin page for my django project. I am trying to implement remember me while logging in. I enter my username and password and select the checkbox remember me. Log in is working fine but when I log out, the username and password are not remembered. I implemented the following code. Any solutions? views.py if request.method == 'POST': form = LoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] remember_me = request.POST.get('remember_me') user = authenticate(request, username=username, password=password) if user and user.is_superuser: login(request, user) if not remember_me: request.session.set_expiry(0) messages.success(request, 'logged in.') return redirect(redirect_url) else: messages.error(request, 'Invalid username or password') else: form = LoginForm() return render(request, '3home.html', {'form': form}) template <form action="" method="post" class="form-signin"> {% csrf_token %} <input type="text" class="form-control mb-2" name='username' placeholder="Username" required autofocus> <input type="password" class="form-control mb-2" name='password' placeholder="Password" required> <button class="btn btn-lg btn-primary btn-block mb-20" type="submit">Log in</button> <div class="checkbox float-left"> <input type="checkbox" name="remember_me" id="basic_checkbox_1" > <label for="basic_checkbox_1">Remember me</label> </div> </form> forms.py class LoginForm(forms.Form): username = forms.CharField(max_length=100) password = forms.CharField(widget=forms.PasswordInput) remember_me = forms.BooleanField(required=False) -
Django: find wrong static file
I got a problem with my static file in django project. When i try to runserver django find wrong file in debugger. My file http://127.0.0.1:8000/static/css/funkcje.js in debugger looks like this[https://i.stack.imgur.com/JKsX1.png]and my file in django project static/css [https://i.stack.imgur.com/MHqWW.png]. Its completely diffrent files. I tried commands like python manage.py collectstatic but it didnt help i checked whole folder and there are no file which looks like http://127.0.0.1:8000/static/css/funkcje.js -
'FilterExpression' object has no attribute 'value'
I am migrating from Django 1.8.17 to 1.11.21. I re-installed all compatible packages and did required code changes. But it is still giving "'FilterExpression' object has no attribute 'value'" error and i am stuck. It should render the page template. -
How to show the django ModelForm details in a table?
I created a model and just trying to store the details using the ModelForm in the backend but i'm unable to do it as whenever I try to submit my form it always shows else part of my views.py that is -> Please try again. If someone knows what i'm doing wrong please let me know. P.S -> I have two form methods in my templates.html but I haven't wrote any code for that now, just trying to save that first one now. I tried to solve this problem by looking for some answers here but didn't got any success. models.py class OrgMember(models.Model): org_poc = models.CharField(max_length=100, blank=False, verbose_name="Organization POC") org_name = models.CharField(max_length=100, blank=False, verbose_name="Organisation Name") phone = models.CharField(max_length=10, blank=False, verbose_name="Phone Number") email = models.EmailField(blank=False, unique=True, verbose_name="Email ID") def __str__(self): return self.email forms.py class OrgMembersForm(forms.ModelForm): class Meta: model = OrgMember fields = ['org_poc', 'org_name', 'phone', 'email'] views.py def org_member_view(request): if request.method == "POST": form = OrgMembersForm(request.POST) if form.is_valid(): form.save() messages.success(request, "Member Added Successfully.") return redirect('users-members') else: messages.error(request, "Please Try Again.") else: form = OrgMembersForm() members = OrgMember.objects.all() context = {'form': form, 'members': members} return render(request, 'users/members.html', context) template.html The table in which I want my data <table class="table table-responsive"> <thead> <tr> … -
How do I add `active` class for my current list group?
This is a sample of my current list-group: Since Python Flow Control link on side bar is active, I want it to be highlighted by adding a CSS active class. I think I can do that using current URL of the page, being in Python Flow Control page the current URL looks like http://localhost:8000/python/python-flow-control/ and in template if I type {{ request.path }} it would return /python/python-flow-control/. Using URL I tried this approach but it didn't work: <div class="list-group"> {% for sub_cat in sub_cats %} <a href="{% url 'tutorials:tutorials' sub_cat.sub_cat_parent.cat_slug sub_cat.sub_cat_slug %}" class="list-group-item list-group-item-action {% if request.path == '/{{sub_cat.sub_cat_parent.cat_slug}}/{{sub_cat.sub_cat_slug}}/' %} active {% endif %}"> {{ sub_cat.sub_cat_title }}</a> {% endfor %} </div> I added {% if request.path == '/{{sub_cat.sub_cat_parent.cat_slug}}/{{sub_cat.sub_cat_slug}}/' %} active {% endif %} to check if the current URL matches with url of the current clicked link and if it matches add css active class. How do I solve this problem, please help me. Thank you -
How to make a POST request to the end point, in views in django for chatterbot?
i am new to django! I want to make a chatterbot chatbot in my website, for which i need to make a POST request in views. I have created a model. I am using mysql database for this. I have visited github and other website and finally got a code, but it doesn't have the POST request this is my models.py: class Response(models.Model): statement = models.ForeignKey( 'Statement', related_name='in_response_to', on_delete=False ) response = models.ForeignKey( 'Statement', related_name='+', on_delete=False ) unique_together = (('statement', 'response'),) occurrence = models.PositiveIntegerField(default=0) def __str__(self): s = self.statement.text if len(self.statement.text) <= 20 else self.statement.text[:17] + '...' s += ' => ' s += self.response.text if len(self.response.text) <= 40 else self.response.text[:37] + '...' return s this is where i need to make a POST request in views.py def post(self, request, *args, **kwargs): response = Response.objects.all() if request.is_ajax(): input_data = json.loads(request.read().decode('utf-8')) else: input_data = json.loads(request.body.decode('utf-8')) self.validate(input_data) response_data = self.chatterbot.get_response(input_data) return JsonResponse(response, response_data, status=200) def get(self, request, *args, **kwargs): data = { 'detail': 'You should make a POST request to this endpoint.', 'name': self.chatterbot.name, 'recent_statements': self._serialize_recent_statements() } # Return a method not allowed response return JsonResponse(data, status=405) -
How to sum up amount in django choices
I'm trying to find the total amount of material costs in columns given I have to select the amount with django choices. I have tried adding up using self.amount1+ self.amount2 to no avail PO_STEEL_COST_CHOICES = ( ('10000' ,'10000'), ('20000','20000'), ('30000','30000'), ('40000','40000'), ) PO_ELECTRICAL_MATERIAL_CHOICES = ( ('10000' ,'10000'), ('20000','20000'), ('30000','30000'), ('40000','40000'), ) PO_SUBCONTRACTORS_CHOICES = ( ('10000' ,'10000'), ('20000','20000'), ('30000','30000'), ('40000','40000'), ) class ProcurementTeam(models.Model): project_name = models.OneToOneField(Project, on_delete=models.DO_NOTHING) po_steel = models.FileField(upload_to='files/ProcurementTeam/posteel/%Y/%m/%d/', blank=True, null=True) po_steel_cost = models.CharField(max_length=120,choices=PO_STEEL_COST_CHOICES, default='None', blank=True) po_electrical_materials = models.FileField(upload_to='files/ProcurementTeam/poelectrical/%Y/%m/%d/', blank=True, null=True) po_electrical_materials_cost =models.CharField(max_length=120, choices=PO_ELECTRICAL_MATERIAL_CHOICES, default='None', blank=True) po_subcontractors = models.FileField(upload_to='files/ProcurementTeam/posubcontractor/%Y/%m/%d/', blank=True, null=True) po_subcontractors_cost = models.CharField(max_length=120, choices=PO_SUBCONTRACTORS_CHOICES, default='None', blank=True) posted_by = models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING) is_approved = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) def __str__(self): return str(self.project_name) def total_material_cost(self): """Function to return total procurement PO cost""" total_procurpo = int(self.po_steel_cost + self.po_electrical_materials_cost + self.po_subcontractors_cost) return total_procurpo "I expect the output to be 40,000 given I have chosen 10000, 20000 and 10000 but the current output is 100002000010000 -
Django 2 migrate is not creating table in MySql?
I am using django and mysql. When i do migrate after making some models at first time then it creates all the table in the database properly but after that migrate succeed when i do some changes or create new models then it doesn't creates the new table in the database even it says the migrate successful.I always do python manage.py makemigrations and then python manage.py migrate after some changes in model .I deleted all the migrations and run python manage.py makemigrations it displays all the model i have created in the models.py but after migrate it doesnot creates the new table. I even tried python manage.py migrate --fake APPNAME and python manage.py migrate but nothing happened in the database.But when i delete the whole database and create the new one then it creates the all the tables but i am not interested to delete whole database after some changes or creating new models everytime settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'root', 'PASSWORD': '', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, } } -
Display specific data in other model
how to display specific data in other model in django here my code in my models.py class ProjectName(models.Model): BacProjectName = models.CharField(max_length=250) date_created: object = models.DateField(auto_now=True) def __str__(self): return self.BacProjectName class BacFileUpload(models.Model): Sproject = models.ForeignKey(ProjectName__date_created__year=2019, on_delete=models.CASCADE) Sproject = models.ForeignKey(ProjectName__date_created__year=2019, on_delete=models.CASCADE) TypeError: __init__() missing 1 required positional argument: 'to' -
Is there any limit of json size ajax post request?
Im postsing textarea content thourgh ajax to django. My problem starts. When i put < 1000 lines of text area, not thing happens and it's works okay. But if it put 1000 lines or greater than 10000 lines , i'm getting errors "Bad Requests". So my question is: Is it any limit of json post ajax, or any one have soulution of this? Thanks for help This is my ajax request: $.ajax({ type: "POST", // url: '/page-tools/inboxpage/setting_send_inbox_ajax/{{page.pk}}/', url: "{% url 'page-tools:page-settings-send-inbox-ajax' page.pk %}", data: $(this).serialize(), beforeSend: function(xhr, settings) { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { // Only send the token to relative URLs i.e. locally. xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } }, success: function(response) { if (response.error_connection) { alert(response.error_connection); } else if (response.error_token) { alert(response.error_token); } else { send_inbox(response.settings); } }, error: function (jqxhr, status, exception) { console.log('Exception: ', … -
ImproperlyConfigured Django API View
I am facing an Odd problem in django. It throws me a message that ImproperlyConfigured below is my Views.py class ArticleListCreateGet(ListAPIView, CreateAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializers and below is my serializers.py class ArticleSerializers(serializers.HyperlinkedModelSerializer): class Meta: model = Article fields = ['author', 'title', 'body', 'category'] and below is my models.py from django.db import models from django.contrib.auth.models import User class Author(models.Model): name = models.TextField(max_length=50) class Category(models.Model): name = models.CharField(max_length=100) class Article(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=200) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) and this my urls.py url('^api/v1/article$', views.ArticleListCreateGet.as_view(), name='articleGetAndPost') I guess my everything is ok but when i hit this url http://127.0.0.1:8000/api/v1/article It throws me this error message ImproperlyConfigured at /api/v1/article Could not resolve URL for hyperlinked relationship using view name "author-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Request Method: GET Request URL: http://127.0.0.1:8000/api/v1/article Django Version: 2.2.and bla bla bla bla bla bla bla How can get rid of this problem? -
Passing data from Django Filter to Nodejs
I have a dashboard written in Node.js to visualize the information. The data however are queried through Django rest framework. Now I want to put these data I queried from Django to the dashboard to visualize. More specific, I filtered information from Django based on date time range and correspondingly I need to visualize the data on dashboard in Nodejs. I am new to both Django and Nodejs, and have searched many resources but found no idea. Please help to guide me basic steps or leave some tutorials. Thank you very much. -
Select Specific data created in year in my parent table
Good day Im have trouble in my models.py I want to select date_created year = "2019" in my parent table but im having an error is there another way? thank you in advance ! class ProjectName(models.Model): BacProjectName = models.CharField(max_length=250) date_created = models.DateField(auto_now=True) -
How can I pass value in the stripe checkout.form?
I am using the stripe checkout.js, it's working good, but I want to pass the users fields in the billing name, billing city, billing postal code and billing country if the user has login. How can I do that? <form action="" method="POST"> {% csrf_token %} <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="{{ data_key }}" data-amount="{{ stripe_total }}" data-name="Russell Inn Beer Store" data-description="{{ description }}" data-image="{% static 'img/russell.png' %}" data-email = "{{ user.email }}" data-locale="auto" data-currency="cad" data-shipping-address="false" data-billing-address="true" data-allow-remember-me="false" data-label="Pay with card" > </script> </form> Is there any way to pass it in the stripe checkout.js or I will create my custom form.