Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I upgrade pip version in cloud foundry for python buildpack
I am trying to host a django application on cloud foundry. I am getting error: "You are using pip version 9.0.1, however version 19.2.3 is available. You should consider upgrading via the 'pip install --upgrade pip' command." Now, how can I upgrade pip version for my application in cloud foundry environment I tried mentioning buildpack in manifest.yml from: https://github.com/cloudfoundry/python-buildpack Manifest.yml file applications: - name: app command: python manage.py runserver buildpack: https://github.com/cloudfoundry/python-buildpack.git -
how to reassign value to a variable after doing arithmetic operations in Django Template Language (jinja2)
I want to do arithmetic operations within Django Template format and also assign the new value to the same Variable I have so far used {{with}} {{set}} and also django-mathfilters but i am unable to reassign value back to the same variable. {% with count=0 %} {% for report in reports %} <tr> <th scope="row">{{set count count|add:"1"}}</th> <td>{{report.submit_time}}</td> <td>{{report.file_name}}</td> {% if report.is_complete %} <td>Complete</td> {% else %} <td>Pending</td> {% endif %} <td>{{report.score}}</td> </tr> {% endfor %} {%endwith%} i want to show numbers in serial in my table -
Changing Django's default list of Common Password
I just try to use Django. when i try to create superuser with the createsuperuser and i try to use some common password like abcd1234 (because abc or 123 isn't allowed), it cannot accept it because apparently that my password is too common, i know that the createsuperuser use somekind of password list to match mine with theirs. I want to ask that whether it is possible to change the password list. i already tried to open manage.py to find the createsuperuser method but i didnt find it because it only contains run(sys.argv) -
Try to build tv-series & movies site with django
I am trying to build a tv series and movies site , but I can't access the Ep from Tv. I am trying to make my url look like that www.SiteName.com/friends/ep/1 but I have no idea what I should write in views.py and urls.py . this is my models.py from django.db import models class Tv(models.Model): title = models.CharField(max_length=250) slug = models.SlugField() description = models.TextField() def __str__(self): return self.title class Episode(self): title = models.CharField(max_length=250) EpisodeNumber = models.IntegerField() slug = models.SlugField() def __str__(self): return self.title -
Run script.py to fetch values everytime the page is loaded in django
Trying to learn django, and I felt the best way to do so is building a simple project. My goal is to execute a bash command through subprocess by taking form input that has some choice fields based on a list derived from file. What I did was execute whatever command I needed to get the list, parse the log file to obtain the list and then use the list in the choice field as options. Then, use the input to fire another subprocess call to execute the required bash command. I have the following code, My form.py from django import forms from . import script from django.core.exceptions import ValidationError class PostForm(forms.Form): p1 = forms.ChoiceField(choices=enumerate(script.choices),label='Player 1') p2 = forms.ChoiceField(choices=enumerate(script.choices2),label='Player 2',required=False) x = forms.IntegerField(required=False) y = forms.IntegerField(help_text='Set to 70 if unknown',required=False) z = forms.IntegerField(required=False) def clean(self): cleaned_data = super(PostForm, self).clean() p2 = cleaned_data.get("p2") cordsx = cleaned_data.get("x") cordsy = cleaned_data.get("y") cordsz = cleaned_data.get("z") if p2 and (cordsx or cordsy or cordsz): # both were entered raise forms.ValidationError("Enter either co-ords or player 2 name") elif not p2 and not (cordsx or cordsy or cordsz): # neither were entered raise forms.ValidationError("You must enter either co-ords or player 2 name") return cleaned_data My script: import … -
Django rest related model not included
I have a TwitchChannel model which has a ForeignKey relationship to CustomUser. class TwitchChannel(models.Model): login = models.CharField(max_length=25) display_name = models.CharField(max_length=25) twitch_user_id = models.CharField(max_length=50) email = models.EmailField(null=True, blank=True) profile_image_url = models.URLField(null=True, blank=True) access_token = models.CharField(default="none", max_length=100) refresh_token = models.CharField(default="none", max_length=100) live = models.BooleanField(default=False) channel_data = JSONField() created = models.DateTimeField(auto_now=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) def save(self, **kwargs): make_password(self.access_token) make_password(self.refresh_token) super().save(**kwargs) def __str__(self): return self.display_name def get_channel_url(self): return f"https://twitch.tv/{self.login}" In my UserSerializer I want to include this TwitchChannel when it exists. The following are my serializers. class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) twitch_channel = TwitchChannelSerializer(read_only=True, many=True) def create(self, validated_data): user = UserModel.objects.create( email=validated_data["email"], first_name=validated_data["first_name"], last_name=validated_data["last_name"] ) user.set_password(validated_data["password"]) user.save() return user def update(self, instance, validated_data): if 'password' in validated_data: password = validated_data.pop('password') instance.set_password(password) class Meta: model = UserModel depth = 3 fields = ( "id", "first_name", "last_name", "email", "password", "twitch_channel") extra_kwargs = {"password": {"write_only": True, }} class TwitchChannelSerializer(serializers.Serializer): class Meta: model = TwitchChannel fields = ( 'user_id', 'login', 'display_name', 'email', 'profile_image_url', 'access_token', 'refresh_token', 'live', 'channel_data', 'created', 'user' ) However, when I do a request for the user the field isn't even included at all. { "id": 3, "first_name": "Patrick", "last_name": "Hanford", "email": "testing@streambeacon.tv" } I get no error, but the field is non-existent. -
I have Django project I want to show agreement and privacy and policy show one per user login first time
I want to add to agreement and privacy and policy show one per user login first time and after admin change, an agreements or policy .etc that time show a to a user. I have Django project I need to accept any way user agreement and user term and policy if the user accepts all then go to the user dashboard. other user needs to login then accept. then goes to dashboard. the same need to cookies and session accept don't show to the same user. django front end user login and registration added I have added models with user_checked modal. and templates for agreement term and privacy models class user_check(): agreement1 =models.BooleanField() agreement2 = models.BooleanField() pravacy = models.BooleanField() views from django.shortcuts import render # Create your views here. def aggement1(): return render('agreement1.html') def aggement2(): return render('agreement2.html') def pravacy(): return render('pravacy') when user login first time show an agreement 2 step and user term and policy need to accept. cookies and session notification show to user screen if they accept then don't show I am a Django beginner developer -
Order Filtered Queryset Count in Django
I am trying to create a kind of ranking: there are 'students' and there are transactions of items. And if the item is a beer, it counts towards the beer_list. I wrote this manually but this isn't sorted: beer_list = {} for transaction in Transactions.objects.all(): if transaction.item.beer: if transaction.student.student_ID in beer_list: beer_list[transaction.student.student_ID]['beer_count'] += transaction.item_count else: beer_list[transaction.student.student_ID] = { 'nickname': (transaction.student.nickname if transaction.student.nickname else 'Anon'), 'beer_count': transaction.item_count } I tried sorting it with beer_list = sorted(beer_list.items(), key=lambda x: x[1]) but this throws an error, that this comparison isn't usable with dict to dict usage. Is there a simple solution for this? I am thinking of something like Transactions.objects.filter(item.beer=True) and then using this filtered list to count the objects possibly with an annotation? -
django set boolean field value in views
I need to set all BooleanField values to False with button in my template. model: class VyberJedla(models.Model): nazov_jedla = models.CharField(max_length=100) ingrediencie = models.CharField(max_length=500) vybrane = models.BooleanField(default=False) def __str__(self): return self.nazov_jedla view: def vymazatVybrane(request): jedlo = VyberJedla.objects.all jedlo.vybrane = False jedlo.save() return redirect('/') template(button): <a href="{% url 'vymazatVybrane' %}"> <button type="button"> DELETE COMPLETED </button></a> error: AttributeError at /vymazatVybrane 'method' object has no attribute 'vybrane' -
Django NoReverseMatch error when I try to connect to my URL
I am getting a NoReverseMatch error when I try to connect to my URL, and I am not sure what the problem is. Thank you for any help. Here is my code: cart/models.py from shop.models import Product class Cart(models.Model): cart_id = models.CharField(max_length=250, blank = True) date_added = models.DateField(auto_now_add = True) class Meta: db_table = 'Cart' ordering = ['date_added'] def __str__(self): return self.cart_id class CartItem(models.Model): product = models.ForeignKey(Product, on_delete = models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) quantity = models.IntegerField() class Meta: db_table = 'CartItem' def sub_total(self): return self.product.price * self.quantity def __str__(self): return self.product cart/views.py It seems as though the error stems from the add_cart method here, saying that there is no reverse for it. from shop.models import Product from .models import Cart, CartItem from django.contrib import messages from django.core.exceptions import ObjectDoesNotExist def _cart_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) if cart_item.quantity < cart_item.product.stock: cart_item.quantity += 1 cart_item.save() else: messages.add_message(request, messages.INFO, 'Sorry, no more available!') except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity = 1, cart = cart ) cart_item.save() return … -
Render ajax post to HTML in Django with render_to_string
I am writing an page that with a form of several inputs wrapped in selectize.js on the top. By clicking a button, I wish to return some queries info based on inputs. I am using ajax to post inputs to avoid page reloading. I am following DJANGO render new result values from AJAX request to HTML page to render the queried result cat_result based on ajax post data in HTML. def cat_select(request): cat_result=[] cat_selected=[] cat_name=['l2','l3'] cat_selected=list(map(lambda x:request.POST.get(x, '').split(','), cat_name)) cat_result=c_result(["US"],cat_selected) #list of tuples I want to get print(cat_selected) print(cat_result) html=render_to_string(request, 'result.html', {'cat_result': cat_result}) return JsonResponse({'cat':cat_result,'html':html},safe=False) But I get below error on render_to_string File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\template\loaders\base.py", line 18, in get_template for origin in self.get_template_sources(template_name): File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\template\loaders\filesystem.py", line 36, in get_template_sources name = safe_join(template_dir, template_name) File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\utils\_os.py", line 32, in safe_join final_path = abspath(join(base, *paths)) File "C:\Users\AppData\Local\Continuum\anaconda3\lib\ntpath.py", line 115, in join genericpath._check_arg_types('join', path, *paths) File "C:\Users\AppData\Local\Continuum\anaconda3\lib\genericpath.py", line 149, in _check_arg_types (funcname, s.__class__.__name__)) from None TypeError: join() argument must be str or bytes, not 'WSGIRequest' There is the function that works with the main base.html which result.html extend from. def search_index(request): ##something to populate input options for l2 and l3 print(results) context = {'l2':l2, 'l3':l3} return render(request, 'esearch/base.html', context) base.html <form id="cat_select">{% csrf_token %} … -
Making a script that changes Django settings
I have a django project with 3 completely different templates, each with its own folder. Would it be possibile to make a python script that changes django's settings (file paths to static files and templates) when executed? Can anyone point me to a tutorial or give me advice on how would I go about achieving this on my own? -
{Django} How does the .env file stay hidden/secret?
How does the .env file stay hidden/secret when in the same dir as settings.py, urls.py, and wsgi.py? Should I do something additional to keep my env variables hidden? I will be deploying AWS elastic beanstalk and have the (environment variables ) set like: .env DEBUG=on SECRET_KEY=blah123456 MAILCHIMP_API_KEY=blah123456 Settings.py import os import environ env = environ.Env( #set casting DEBUG=(bool, False) ) # read .env file environ.Env.read_env() MAILCHIMP_API_KEY = env('MAILCHIMP_API_KEY') SECRET_KEY = env('SECRET_KEY') -
django-dynamic-formset add another / delete buttons failing
[enter image description here][1] [1]: https://i.stack.imgurstrong text.com/2D4l2.png Hi, I'm a beginner Django developer writing my first question in stackoverflow. I'm trying to use the django-dynamic-formset plugin to enable the user of my web application to add or delete forms dynamically, by clicking a button, however, instead of getting a "remove" button for every row, I'm getting one for every field in my form as you can see in the picture. Also, when I'm trying to customize the text in the "add another" or "delete" button, this is not working (you can see the script at the end of my html template). I would appreciate if you can tell me what I might be doing wrong. I'm attaching the code of my html template as well. `{% load crispy_forms_tags %} {% load staticfiles %} <table class="formset-test"> {{formset.management_form|crispy}} {% for form in formset.forms %} <tr class="{% cycle 'row1' 'row2' %} formset_row-{{formset.prefix}}"> {% for field in form.visible_fields %} <td> {% if forloop.first %} {% for hidden in form.hidden_fields %} {{hidden}} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field|as_crispy_field }} </td> {% endfor %} </tr> {% endfor %} </table> <!-- <p class='btn btn-warning' id='agregar'>Agregar Posición</p> --> <br> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="{% … -
Django Error: NameError name 'db_table' is not defined
so I am getting this error in cmd when I try to make migrations. Here is my code: from django.db import models from shop.models import Product class Cart(models.Model): cart_id = models.CharField(max_length=250, blank = True) date_added = models.DateField(auto_now_add = True) class Meta: db_table - 'Cart' ordering = ['date_added'] def __str__(self): return self.cart_id class CartItem(models.Model): product = models.ForeignKey(Product, on_delete = models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) quantity = models.IntegerField() class Meta: db_table = 'CartItem' def sub_total(self): return self.product.price * self.quantity def __str__(self): return self.product This is my models.py file. Thanks for any help you can give. -
pylint doesn't work correctly when pylint_django loaded
When pylint-django is installed error messages like Class 'MyModel' has no 'objects' member disappear. But with them being disappeared some real errors are skipped too. For example, the line MyModel.objectss.all() will not throw an error (note two s in the word objects). Actually, I find it quite interesting, how pylint is marking errors: MyModel.objects.all() (everything is correct) - gives no error. MyModel.objectss.all() (two s in objects) - gives no error. MyModel.objectss.alll() (two s in objects and three l in all) - gives Class 'MyModel' has no 'objectss' member. MyModel.objects.alll() (three l in all) - gives no error. It's like at least two errors must occur in order for pylint to throw an error. I am working withVisual Studio Code 1.39.1, pylint==2.4.2, pylint-django==2.0.11 My Visual Studio's settings.json file looks like this: { "python.linting.pylintArgs": [ "--load-plugins=pylint_django" ] } So, is this a bug or is there something wrong with my config? -
Bootstrap Navbar won't get colored when using with Django
I'm using Django to create an E-Commerce Website. Used Bootstrap navbar in it, but the css I copied from here doesn't work when I use it within the {%block css %} tag. I'm uploading the html here. Any help is largely appreciated. Also, if anybody needs the entire project to get an idea of what might be causing an issue, here's the project. basic.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <link rel="stylesheet" href="styles.css"> <title>{% block title %} {% endblock %}</title> <style> {% block css %} .navbar { background-color: #e74c3c; } .navbar .navbar-brand { color: #ecf0f1; } .navbar .navbar-brand:hover, .navbar .navbar-brand:focus { color: #ffbbbc; } .navbar .navbar-text { color: #ecf0f1; } .navbar .navbar-text a { color: #ffbbbc; } .navbar .navbar-text a:hover, .navbar .navbar-text a:focus { color: #ffbbbc; } .navbar .navbar-nav .nav-link { color: #ecf0f1; border-radius: .25rem; margin: 0 0.25em; } .navbar .navbar-nav .nav-link:not(.disabled):hover, .navbar .navbar-nav .nav-link:not(.disabled):focus { color: #ffbbbc; } .navbar .navbar-nav .nav-item.active .nav-link, .navbar .navbar-nav .nav-item.active .nav-link:hover, .navbar .navbar-nav .nav-item.active .nav-link:focus, .navbar .navbar-nav .nav-item.show .nav-link, .navbar .navbar-nav .nav-item.show .nav-link:hover, .navbar .navbar-nav .nav-item.show .nav-link:focus { color: #ffbbbc; background-color: #c0392b; } .navbar … -
(index):84 Uncaught ReferenceError: $ is not defined at (index):84
I try to work with jquery which is native to HTML5. But not success but failed. Because it says (index):84 Uncaught ReferenceError: $ is not defined at (index):84. Triyed many tecknics including copying google apis and microsoft apis. All the answers are related to php or depreciated. Here is my base.html: <script language="JavaScript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script language="JavaScript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> Here is the simple code I am using for ajax, you know not the page refresh every time like facebook commenting: <a class="btn btn-secondary btn-sm mt-1 mb-1" id="{{post.pk}}" href="{% url "post-update" post.id %}">{{post.pk}}</a> <script> $(document).ready(function(){ $("button").click(function(){ $("#{{post.pk}}").hide(); }); }); </script> <button>Click me</button> I want the end result as look we recognized $ sign and you can hide all buttons or related id = {{ comment.id }} without page refreshing but that was not the case. -
Why this save() function in django not working properly
`def save(self): super().save() img = Image.open(self.image.path) output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path)` I am currently practicing for a Django Project about Post uploading with some basic feature like login ,Register, Update/Profile , In profile section there is a feature to update profile picture of user selected png or jpg of any size and convert into 300x300 to fit in a page. But I don't know why this save feature is not working, Actually the image is saving in my local folder but the size is not updating. Thanks -
How to solve python Issue __import__(name) ImportError: No module named preferences
Stuck with issue as my project require Django==1.7.7 but couldn't proceed with this error. Library I have: Django==1.7.7 django-browserid==2.0.2 django-dynamic-preferences==1.7.1 django-preferences==1.0.0 -
django catch request error when deploy nameserver to ip
when i deploy nameserer to ip host,the django will catch error request from nameservr,may be nameserver sent hearbeat to ip host.How can skip this error from django? Exception happened during processing of request from ('127.0.0.1', 51975) Traceback (most recent call last): File "/data/home/anaconda3/lib/python3.6/socketserver.py", line 654, in process_request_thread self.finish_request(request, client_address) File "/data/home/anaconda3/lib/python3.6/socketserver.py", line 364, in finish_request self.RequestHandlerClass(request, client_address, self) File "/data/home/anaconda3/lib/python3.6/socketserver.py", line 724, in __init__ self.handle() File "/data/home/anaconda3/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 169, in handle self.handle_one_request() File "/data/home/anaconda3/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/data/home/anaconda3/lib/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 104] Connection reset by peer -
DjangoFilterBackend date search format
I have the following class with DjangoFilterBackend which work for query parameters like: localhost/ett/?date=2019-10-13 class EttListView(generics.ListCreateAPIView): queryset = models.Ett.objects.all() serializer_class = serializers.EttSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['date'] But I need to have call a different date format like below: localhost/ett/?date=Thu Oct 13 2019 Is it possible to achieve this in DjangoFilterBackend ? -
IIS with Hamachi
I am trying to share a Django webapp with IIS and Hamachi, all is fine in debug mode and if I bind the site to my real LAN IP Address. If i create an hamachi lan and put the hamachi IP address to binding the website I cannot reach the site anymore. I have already open the port TCP 90 (the one that i'm using now) on the firewall but nothing happen. In the site log I have no errors. What I am doing wrong? Thanks -
Am I writing my template tag urls correctly?
using Django 2 I am trying to add a shopping cart app to my django project. I am getting this error message: Reverse for 'add_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/add/(?P[0-9]+)/$'] From my understanding and doing some research I think my problem is that I am not inputting the correct urls in the template tags to link to my views. But I am only 4 weeks in to Django and am a bit lost. I have tried changing the "{% url 'cart_remove' cart_item.product.id %}" and "{% url 'cart_add' cart_item.product.id %}" tags. I have tried adjusting the app and project level urls.py. I have tried to change the base.html, cart.html I have tried changing the views and have read through every file a number of times trying to spot an error or typo. I have been changing things around for about 5 hours now but nothing seems to work. as I said I think it is a problem with my template tags. I reckon I am confused and am trying to link the wrong thing. cart.html {% for cart_item in cart_items %} <tr> <td>{{cart_item.product.name}}</td> <td>{{cart_item.product.brand}}</td> <td>{{cart_item.product.description}}</td> <td>€{{cart_item.product.price}}</td> <td>{{cart_item.sub_total}}</td> <td>{{cart_item.quantity}}</td> <td><a href="{% url 'cart_remove' cart_item.product.id%}"> <span class="glyphicon glyphicon-minus-sign"></span></a></td> <td><a … -
For loop into js object in template
I want to iterate over an object I return from django view to create dynamically columns in a table (each column is a field in a model and I want to be able to switch the model without changing the template) In the html body part of the template the same exact code worked fine, in the script section it's not. Working example non in the script section {% block content %} <div class="d-flex pt-5 pb-2"> <!-- Need to be set to colums initials names using django --> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Show </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton" id="swichable_column"> <!--reate fileds name and Showable names --> {% for name in columns_name %} <div class="checkbox"> <label> <input type="checkbox" checked="checked" class="chackable_name" value="{{ name.1 }}">{{ name.0 }}</label> </div> {% endfor %} </div> </div> </div> <div id="example-table"></div> {% endblock content %} Script section in my tamplet - not working even do it's the same code <script> //define some sample data var tabledata = [ {id:1, first_name:"Oli Bob", age:"12", col:"red", dob:""}, {id:2, name:"Mary May", age:"1", col:"blue", dob:"14/05/1982"}, {id:3, name:"Christine Lobowski the gratest and latest", age:"42", col:"green", dob:"22/05/1982"}, {id:4, name:"Brendon Philips", age:"125", col:"orange", dob:"01/08/1980"}, {id:5, name:"Margret Marmajuke", age:"16", col:"yellow", dob:"31/01/1999"}, …