Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i need to get 40 boxes in django output but i am getting only 2 boxes
from django.shortcuts import render import random Create your views here. def home(request): l=[] for i in str(random.randint(1,40)): l.append(i) return render(request, 'check/web.html', {'list':l} ) templates: {% for i in list %} {{i}} {% endfor %} I am getting only two boxes instead of 40 boxes -
how can i pass Form values to particle.io
Im using django,raspberry pi3, particle.io,relay I want to pass on\off value from Form to particle.io so that i can control lightbulb. <form action="https://api.particle.io/v1/devices/{{value1}}/relay?access_token={{value2}}" method="POST"> The code given above works perfectly fine but when i try to apply the same thing for a pop-up window , Particle.io is not able to receive the value on\off. The code is given below {% if user.is_authenticated %} <div class = "container"> <div class="wrapper"> <form action="javascript:my_c()" class="form-signin" method="POST"> <hr class="colorgraph"> <br> <p style="color:black; font-family:helvetica; font-size:20px;">Welcome to your home automation system.</p><br> <br> <h style="color:black; font-family:helvetica;">Greetings {{request.user.get_short_name}} </h><br> {% for Profile in UserD|slice:":1" %} <h style="color:black; font-family:helvetica;">Access {{value1}} </h><br> <h style="color:black; font-family:helvetica;">Device ID {{value2}} </h><br> <p style="color:black; font-family:helvetica; font-size:20px;">Tell your device what to do!</p> <center> <div id="donate"> <a style="color:black; font-family:helvetica; font-size:15px;">Lights:</a> <label class="green"><input type="radio" name="arg" value="on"><span>ON</span></label> <label class="red"><input type="radio" name="arg" value="off"><span>OFF</span></label> </div> </center> <center> <input class="btn btn-primary btn-xl js-scroll-trigger" type="submit" value="Do it!"> </center> <br> <br> <script type="text/javascript"> function my_c(){ var win = window.open('https://api.particle.io/v1/devices/{{value1}}/relay?access_token={{value2}}', '1366002941508','width=500,height=200,left=375,top=330'); setTimeout(function () { win.close();}, 6000); } </script> </form> {% endfor %} also is there anyway the instead of using setTimeout(function () { win.close();}, 6000); this , the window is closed automatically closed once the site is fully loaded eg. using onload or something … -
Delete 'Server' response header in Django framework - V3.0.5
Before I begin my question, I have referred the stackoverflow post - Delete header in django rest framework response. Please find the middleware code and settings.py below (referred to the django middleware docs): middleware.py: class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): response = self.get_response(request) response.__setitem__('Server', '') return response settings.py MIDDLEWARE = [ ...., ...., 'middleware_demo.middleware.SimpleMiddleware', ] With the above code, I get the server response with the server header set to empty string as below. Which is as expected and doesn't disclose the server header details: HTTP/1.1 200 OK Date: Tue, 21 Apr 2020 12:55:25 GMT Content-Type: text/html Server: X-Frame-Options: DENY Content-Length: 16351 X-Content-Type-Options: nosniff My goal is to remove the header altogether and tried 2 ways for the same in middleware.py: Method 1 - official docs class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): response = self.get_response(request) response.__delitem__('Server') return response Method 2 - referred stackoverflow blog - Delete header in django rest framework response class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): response = self.get_response(request) del response['Server'] return response But the response still has … -
Django don't render if regex match?
I have pseudo coded what I would like but cant see anything in the docs for using if statements alongside a regex? Any help is appreciated. <!-- if window.name includes Before|After dont render--> {{window.event_id}}-{{window.name}} <!-- end if --> the regex is easy: /(Before|After)/g -
How to reflect changes on both One-To-Many-Relationship instances when updating one of them at once in Django?
I have two tables connected with a Foreignkey. I have a field in the main model, its value depends on the child instances. For example, if I have a Library model and a Book model, Book has Foriegnkey to Library. And we have a field in the Library model which is equal to the "total_price" of all the books in the library. How I can update that field "total_price" whenever I increase the quantity of a certain book or decrease it. Note that I have to save each instance separately in order to get the value right. I have the Books as a TabularInline inside Library, so I make the change to the quantity and save the changes, and then I have to press save one more time to change the "total_price" field. -
Show month name instead of month number in django model choice field
Column acct_per_num in table SAPAdjustment contains the month number. The following code gives a dropdown with month number (1,2,3) but I want month name (January, February, March) instead. forms.py class SAPReconForm(forms.Form): month = forms.ModelChoiceField(queryset=SAPAdjustment.objects.values_list('acct_per_num',flat=True).distinct(), empty_label=None) models.py class SAPAdjustment(models.Model): acct_per_num = models.IntegerField( blank=True,null=True, verbose_name =_('Month'),help_text=_('Month')) -
How can we return multiple SQL table in a single postgre function?
How can we return multiple SQL table in a single postgre function I want something like this: postgrefuction('some parameters') RETURNS refcursor ... ... ... AS $BODY$ DECLARE ... ... ... BEGIN SQL:='some queries'; SQL2:= 'some queries'; RETURN SQL,SQL2 $BODY$ -
Model Formset showing error wen updating my form
The form is creating perfectly but when I am trying to update the form the model formset is not updating as it is showing the data but wen when i change the data and submit it the lecture_content fliefield is showing empty.`def content_edit_view(request, id): course = get_object_or_404(Course, id=id) LectureFormset = modelformset_factory(Lecture, fields=('lecture_title', 'lecture_content'), extra=0) if course.user != request.user: raise Http404() if request.method == 'POST': content_edit_form = ContentEditForm(request.POST or None, request.FILES or None, instance=course) formset = LectureFormset(request.POST or None, request.FILES or None) if content_edit_form.is_valid() and formset.is_valid(): content_edit_form.save() print('course is saved') data = Lecture.objects.filter(post=post) # give index of the item for a formset item strting form 0 and (f)the item itself for index, f in enumerate(formset): if f.cleaned_data: if f.cleaned_data['id'] is None: video = Lecture(course=course, lecture_title=f.cleaned_data.get('lecture_title'), lecture_content=f.cleaned_data.get('lecture_content')) video.save() else: video = Lecture(course=course, lecture_title=f.cleaned_data.get('lecture_title'), lecture_content=f.cleaned_data.get('lecture_content')) d = Lecture.objects.get(id=data[index].id) #get slide id which was uploaded d.lecture_title = video.lecture_title, # changing the database tiitle with new title d.lecture_content = video.lecture_content # changing the database content with new content d.save() return redirect('teacher-profile') else: print("form invalid") else: content_edit_form = ContentAddForm(instance=course) formset = LectureFormset(queryset=Lecture.objects.filter(course=course)) context = { 'contentForm': content_edit_form, 'course': course, 'formset': formset, } return render(request, 'apps/contentAdd.html', context) ` -
Checkout form not getting saved in admin
Hi I'm trying to develop an e-commerce site with Django. So I'm at this point where, users can add items to their cart, proceed to checkout but for some reason, my checkout form is not being saved. I made sure that I have registered my models, and ran migrations, but everytime I fill out my form and go to check in my admin panel, it says: 0 user addresses. What is the problem? Can anyone please help me out? My views.py: @login_required def checkout(request): if request.method == 'POST': address_form = UserAddressForm(request.POST) if address_form.is_valid(): new_address = address_form.save(commit= False) new_address.user = request.user new_address.save() return redirect(reverse("checkout")) else: address_form = UserAddressForm() context = {"address_form": address_form} template = "orders/checkout.html" return render(request, template, context) My checkout.html: <form method="POST" action=''> {% csrf_token %} <fieldset class="form-group"> {{ address_form|crispy }} </fieldset> <div class="form-group"> <input type="submit" class="btn btn-outline-dark" value="Place Order"/> </div> </form> My urls.py: from orders import views as orders_views path('checkout/', orders_views.checkout, name='checkout'), -
how to get data personal from the another user in single website
I am creating a website where tour and travels and truck transports record their data in the website, M done to make this but I have problem, one user logged in and enter their entries well, but another user logged in and he able to see first user data, that's the problem, pl z tell me how to solve this, M using sqlite3 db and django framework -
How do I create a new record in a related model, with just a button in django?
I have two models: class Post(models.Model): POST_TYPE_CHOICES = ( ('D','Declaration'), ('O', 'Offer'), ('R', 'Request'), ) post_type=models.CharField(max_length=1,choices=POST_TYPE_CHOICES, blank =False, default='D') content = models.CharField(max_length=144) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): title = f'{self.get_post_type_display()} from {self.author}' return title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) and class Match(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='matched_post') matchee=models.ForeignKey(User, on_delete=models.CASCADE, related_name='matchee') created_on=models.DateTimeField(auto_now_add=True) read=models.BooleanField(default = False) def __str__(self): return f'{self.matchee} matched with {self.post.author}: {self.post.get_post_type_display()}' I have a list view for all records in the Post model: class PostListView(ListView): model = Post template_name = 'marketplace/post_cards.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 15 I have created a template to display every one of the posts in the Post model: {% extends "base.html" %} {% block content %} <div class="container-fluid"> <div class="row"> {% for post in posts %} <div class="col-sm"> <div class="card" style="width:15rem"> <img class="rounded-circle card-img-top" src="{{ post.author.profile.image.url }}"> <div class="card-body"> <div class="card-title"> {{ post.get_post_type_display }} from <a class="mr-2" href="#">{{ post.author }}</a> </div> <div class="card-subtitle"> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <div class="card-text"> {{ post.content }} </div> {% if user.is_authenticated %} <p class="card-text">Click below to match with this {{ post.get_post_type_display }}.</p> <a href="#" class="btn btn-outline-info">Match</a> </form> {% else %} <p class="card-text">You must be logged in to match with … -
Error deploying Cookiecutter-Django app to Heroku
I'm working with the Django Cookiecutter boilerplate, using Docker. Everything works fine locally so now I'm trying to deploy the app to Heroku by following this guide: Deployment on Heroku. I'm using Django 3 and Rest framework. Docker for development. After running the config commands, I push to Heroku master and get this error: Error while running '$ python manage.py collectstatic --noinput'. Here's the trace: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.7/site-packages/environ/environ.py", line 273, in get_value remote: value = self.ENVIRON[var] remote: File "/app/.heroku/python/lib/python3.7/os.py", line 679, in __getitem__ remote: raise KeyError(key) from None remote: KeyError: 'SENDGRID_API_KEY' remote: During handling of the above exception, another exception occurred: remote: Traceback (most recent call last): remote: File "manage.py", line 31, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 231, in fetch_command remote: settings.INSTALLED_APPS remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 76, in __getattr__ remote: self._setup(name) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 63, in _setup remote: self._wrapped = Settings(settings_module) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 142, in __init__ remote: mod = importlib.import_module(self.SETTINGS_MODULE) remote: File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: … -
My cart items dont remove even after pressing remove button
I want my cart item to remove when clicked on remove but its not working cart page just refresh and end execution.. I want to create a cart function to remove items from it. please help me to get out over this its really frustating my template file views.html--- ''' {% extends 'pro/base.html' %} {% block content %} {% if empty %} <div class="container"> <h1 style="text-align:center">{{ empty_message }}</h1> </div> {% else %} <div class="row"> <div class="col-sm-8 col-sm-offset-2"> <table class="table"> <thead> <th>Item</th> <th>Quantity</th> <th>Price</th> <th></th> </thead> <tfoot> <th></th> <th></th> <th>Total:{{ cart.total }}</th> <th></th> </tfoot> {% for item in cart.cartitem_set.all %} <tr> <td>{{ item.product }} {% if item.variations.all %}<ul> {% for subitem in item.variations.all %} <li>{{ subitem.category|capfirst }}:{{ subitem.title|capfirst }}</li> {% endfor %} </ul>{% endif %}</td> <td>{{ item.quantity }}</td> <td>{{ item.product.price }}</td> <td><a href="{% url 'remove_from_cart' item.id %}">Remove</a></td> </tr {% endfor %} </table> </div> </div> {% endif %} {% endblock %} ''' my views.py--- ''' from django.shortcuts import render from .models import Cart,CartItem from django.http import HttpResponseRedirect from django.urls import reverse from app.models import Product,Variation def cart(request): try: the_id = request.session['cart_id'] except: the_id = None if the_id: cart = Cart.objects.get(id=the_id) context = {'cart':cart} else: empty_message = "you have notthing in your cart.Carry … -
Order object by field containing string value
I have a django model and a field representing an ip-address. I want order queryset of this model by ip-address value such "10.10.10.1" I do Model.objects.order_by("ip_address"), but I get this QuerySet["10.10.10.1", "10.10.10.11", "10.10.10.12", ...] I want this QuerySet["10.10.10.1", "10.10.10.2", "10.10.10.3", ...] I don't know how to do this. Anyone have any ideas? -
django: integration testing Update view: Select a valid choice. That choice is not one of the available choices
I'm trying to create an integration test for a Update View with update form. The issue I'm facing is that the form is marked as invalid with the all too common: Select a valid choice. That choice is not one of the available choices The model contains 2 related objects (foreign keys) for which this error happens. Note that the view and from work perfectly fine when running in the integrated test web server. This issue occurs when trying to create a TestCase using the client class. I'm creating all the required instances in the setUp method of the TestCase and in the actual test use client to POST new data. response = self.client.post( reverse('edit_form', kwargs={'pk': self.instance.id}), data={'id': self.instance.id, 'comment':self.instance.comment.id, 'sequence': self.instance.sequence.id, #more fields omitted }) This only shows the relevant fields. As one can see the actual ids used for the related objects really to exist as entries in the DB. Maybe relevant is that sequence is a hidden field. But both of them have this same validation error. What is causing this issue with form validation in the test case? -
Reorder nav bar from django admin
So I am currently working on a project and the client has asked for this requirement. Basically, I have to provide some sort of mechanism in the admin panel so that the admin can order the navbar items. Current nav bar Like in the image above, admin should be able to set the order to eg. SIGN-IN SIGN-UP ABOUT HOME I'm new to Django but have decent programming skill. Can anyone point me in the right direction? -
Dynamically access modules in django
I'm trying to dynamically access modules in django apps. I'm expecting that some apps contains the file foobar.py or a folder called foobar which contains more files. I've tried to access modules the following way. python manage.py shell from django import apps # accessing an app called account config = apps.app_configs['account'] module = config.module dir(module) But when I'm trying to do it that way only admin, forms and models are visible. No other modules inside the account app is visible. Is there a better way? -
Trouble With Django Bootstrap Modals
I am using django-bootstrap-modal-forms in order to implement modal forms in my project. I have implemented them in such a way that launching the modals can be done from my base.html, and therefore can be done from every different page in my app. The modal successfully launches on all pages, posts on all pages, but on a few pages it returns the form with validation messages even though it did post successfully and there are no issues. This package does use two post requests in order to make the messages framework operate, but I don't understand how it could work on some pages and not on other when I seemingly have done the same exact thing. For example, I have a modal to Create Shipment. This displays validation errors (despite successfully posting) on the home screen of the app, but does work perfectly on the View Shipments page. If anyone could please help this is driving me insane. I notice that on the pages where it does not work, I get a broken pipe error in my terminal. I also notice that it seems it is attempting to post 3 times on pages that it does not work. Please see … -
How to use column name dynamically inside insert query in djnago
cursor.execute("insert into demoapp_site ('name','firstname','lastname') values (%s,%s,%s)",site_data) in above query I want to pass column name dynamically and %s which is inside values also not predefine that how many times it need to write so, how can I write my sql query according to my data which comes from html table in 2d array from?? -
Django DateTimeField no seconds
I'm struggling with one case - i would like to have a field in my datatimefield model, but without seconds etc. just YYYY-MM-DD HH:MM, I've been trying to do like this, but it doesn't work: schedule_time = models.DateTimeField(format(['%Y-%m-%d %H:%M']), auto_now_add=True) Could someone provide me solution on any example? I've also been looking for solutions there, but i haven't found anything that would help me. Regards. -
Django form selecting from another view
I currently have a model, 'Organisation' with a class based list view and detail view for the organisations. I'm now creating a form for a different model which has a foreign key of Organisation and currently a select box to choose the organisation. Rather than the select box however, I'd like to be able to click a link to the list view and then select an organisation's detail view and from here click a select button to add the specific organisation to the form. What's the best way to do this in Django? -
My Django-ajax Like Button is not working..?
I had tried several times to fix this but not successfull, likes count are all updating when I use the admin panel but not in html template.. views.py from common.decorators import ajax_required @ajax_required @login_required @require_POST def like_post(request): # image_id = get_object_or_404(Post, id=request.POST.get('id')) image_id = request.POST.get('id') action = request.POST.get('action') if image_id and action: try: image = Post.objects.get(id=post_id) if action == 'like': image.likes.add(request.user) else: image.likes.remove(request.user) return JsonResponse({'status':'ok'}) except: pass return JsonResponse({'status':'error'}) post_view.html {% extends 'base.html' %} {% load static %} {% block title %}Users Posts{% endblock %} {% block content %} <div class="container-fluid"> <form method="post" enctype="multipart/form-data"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Post"> </form> </div> {% for post in posts %} <div class="w3-container w3-card w3-white w3-round w3-margin"><br> <img src="{% if post.user.profile.photo %} {{post.user.profile.photo.url}} {% else %}{% static 'img/user.png' %}{% endif %}" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:60px"> <span class="w3-right w3-opacity">{{ post.created }}</span> <h4>{{ post.user|title }}</h4><br> <hr class="w3-clear"> <p>{{ post.title }}</p> {% if post.image %} <div style="max-width:100%;height:auto;object-fit: cover;" class="img-fluid"> <img src="{{ post.image.url }}" class="img-fluid" style="max-width:100%;height:auto;object-fit: cover;"> </div> <p>{{ post.description }}</p> {% endif %} {% with total_likes=post.likes.count users_like=post.likes.all %} <div class="image-info"> <div> <span class="count"> <span class="total">{{ total_likes }}</span> like{{ total_likes|pluralize }} </span> <a href="#" data-id="{{ post.id }}" data-action="{% if request.user in users_like %}un{% … -
Django: Filter querys using checkboxes
hello everybody in my django website I've got an HTML page where are listed the results based on the input of a User in the search form (that is located in the homepage). Then when I've got all of them listed I'd like the user to be able to add one more filter, that's why I added two checkbox in that page. Anyway I don't know how to make the page reload and show the results based on the checked box. I added some comment to the code in order to make you understand what I was trying to do. Hope someone could really help me, I don't know where to go Here is the HTML template of the reuslt page: {% if sp %} <div class="filtro"> <h3 style=text-align:center> FILTRI RICERCA </h3> <div class="form-check"> <label class="form-check-label" for="grid-check"> Band </label> <input class="form-check-input" type="checkbox" id="grid-check" name="band"><br/> <label class="form-check-label" for="grid-check"> Album </label> <input class="form-check-input" type="checkbox" id="grid2-check" name="album"> <input type="submit" name="try"> filtra </input> </div> </div> {% for k in sp %} <div class="container_band"> <div class=album_band> <!-- insert an image --> {%if k.cover%} <img src= "{{k.cover.url}}" width="100%"> {%else%} <img src="static/search/images/no.jpg" width="100%"> {%endif%} </div> <div class="info_band"> <!-- insert table info --> <table> <tr><th colspan=2><h3>{{k.band}}</h3></th></tr> <tr><td> Disco: … -
Django: Bootstrap input group not rendering desired HTML/CSS with form
I'm relatively new to Django and having an issue with rendering a form as an input group in Bootstrap. The form is to add a message to a model for a chat. Here is what I am aiming for as an input group: Expected input group This can be achieved with the below HTML: <div class="input-group"> <div class="input-group-append"> <span class="input-group-text attach_btn"><i class="fas fa-paperclip"></i></span> </div> <textarea name="" class="form-control type_msg" placeholder="Type your message..."></textarea> <div class="input-group-append"> <span class="input-group-text send_btn"><i class="fas fa-location-arrow"></i></span> </div> </div> Now using Django to include the form within the input group I am using the below: <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text attach_btn"><i class="fas fa-paperclip"></i></span> </div> <form method="post" action="."> {% csrf_token %} {{ form.content }} <div class="input-group-append"> <button class="send_btn" type="submit"><i class="fas fa-location-arrow"></i></button> </div> </form> </div> This is using the below forms.py: class JobMessageForm(ModelForm): content = forms.CharField(required=True, widget=forms.Textarea(attrs={ 'class': 'form-control type_msg', 'placeholder': 'Type your message...'}), label=False) class Meta: model = JobMessage fields = ('content',) This is giving me the below: Current input group Any help in achieving the expected output would be greatly appreciated! Let me know if any further info would help. -
Django ORM - Join many-to-many with through table
I have 3 models: Task: A task, can be assigned to many employees. AssignedUser: (Bridge table) Store employees assigned to tasks completed: Indicate whether the employee has done the assigned task yet. Employee: An employee, can work on many tasks. (Extends from Django's user model) class Task(models.Model): name = models.CharField(max_length=50) detail = models.TextField() employees = models.ManyToManyField('Employee', through='AssignedUser', related_name='tasks') class AssignedUser(models.Model): task = models.ForeignKey(task, on_delete=models.CASCADE) employee = models.ForeignKey(Employee, on_delete=models.CASCADE) completed = models.BooleanField(default=False) class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.ForeignKey(to=Department, on_delete=models.CASCADE, null=False) If I want to select a task name and the assigned employee's username who hasn't done the task yet (completed=False) how can I do that with Django's ORM? Here's the equivalent SQL I wrote for the desired result which I have no idea how to achieve that with Django's ORM. SELECT t.name, u.username FROM appname_task t JOIN appname_assigneduser au ON (t.id = au.work_id AND au.completed = false) JOIN appname_employee ae ON (au.employee_id = ae.id) JOIN auth_user u ON (ae.user_id = u.id)