Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I print out all the contents of a session in django on a template
I am trying to print out the content of a session on a template.Here's my code: def add_to_cart(request,pk,slug): product = get_object_or_404( Product, pk=pk,) product_document = { 'title': product.title, 'price': product.price, } request.session['cart'][str(product.id)] = product_document print(request.session['cart']) return render(request,'selling/cart.html') def cart(request): template = loader.get_template("selling/cart.html") cart = request.session['cart'] context ={ 'cart': cart, } return HttpResponse(template.render(context,request)) {%if cart%} {%for items in cart%} <div class="holla3" id="holla3" style="background-image: url({{ product.productimage_set.first.product_images.url }});"></div> <div class="alltext" id="textcontainer"> <p id="one">{{ product.title}}</p> <p id="two">${{ product.price }}</p> <!-- <p id="three">{{ product.product_description }}</p> --> </div> {% endfor %} {% else %} <h2>There don't seem to be any items in your cart!</h2> {% endif%} So basically I am trying to print out all the items in the django session dictionary onto the template. -
Getting values through a many 2 many field
I'm trying to return the value for container_id, it is used in the below code in this part pk=container.container_id. The Sample model has a many 2 many with Container, this is where the container_id column is. So how do I obtain the container_id from the Sample model? How do I get the {{ container_name }}I think I need a reverse lookup since the m2m is in the Container model. How is this achieved. See my code: #models.py (simplified) class Sample(models.Model): sample_id = models.AutoField(primary_key=True) area_easting = models.IntegerField(choices = EASTING_CHOICES) area_northing = models.IntegerField(choices = NORTHING_CHOICES) context_number = models.IntegerField() sample_number = models.IntegerField() def __str__(self): return str(self.sample_id) class Meta: db_table = 'kap\".\"sample' managed = True class Container(models.Model): container_id = models.AutoField(primary_key=True) container_name = models.CharField(max_length=50, blank=True, null=True) samples = models.ManyToManyField('Sample', through='ContainerSamples') def __str__(self): return self.container_name class Meta(): managed=True db_table = 'kap\".\"container' # template {% for unassigned in unassigned_samples %} <tr> {% if unassigned not in container_contents %} <td><a href="{% url 'depot:change_container' operation='add' pk=container.container_id fk=unassigned.sample_id %}" class="badge badge-primary" role="button"> << </a></td> <td>{{ unassigned.area_easting }}.{{ unassigned.area_northing }}.{{ unassigned.context_number }}.{{ unassigned.sample_number }}</td> <td>{{ unassigned.sample_id }}</td> <td>{{ container.container_id }}</td> <td>{{ container.container_name }}</td> </tr> {% endif %} {% empty %} {% endfor %} # views.py def detailcontainer(request, container_id): container = get_object_or_404(Container, … -
How display a bucle for 'post' in a booststrap carousel?
I'm new to django and i'm doing my first project. my question is how display my posts in a bootstrap carrousel? this is my code: {% extends 'blog/base.html' %} {% block content %} <br> {% for post in posts %} <div class="post"> <div class="date"> <p>published: {{ post.published_date }}</p> </div> <h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a> </h1> <h5 class="badge badge-secondary">by {{ post.author }}</h5> <p>{{ post.text|linebreaksbr }}</p> <a href="{% url 'post_detail' pk=post.pk %}">Comments: {{ post.comments.count }}</a> </div> {% endfor %} {% endblock %} I tried with this code but it doesn´t work: <div class="carousel-inner"> {% for post in posts|slice:":3" %} {% if forloop.first %} <div class="active item"> {% else %} <div class="item"> {% endif %} <blockquote> <p>{{ post.title }}</p> </blockquote> <label>{{ post.text }}</label> </div> {% endfor %} </div> I want it to look like this without the img: https://i.imgur.com/yPmIWF5.png thanks guys! -
Django Celery Installation Error: TypeError: argument of type 'NoneType' is not iterable
I'm trying to implement celery into a current ongoing django 2 project. Here the code in the init.py: import os from celery import Celery CONFIG_SETTING = 'lp.settings.development_test' # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', CONFIG_SETTING) app = Celery('myproject') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('hello world') Here is the code in the base settings: CELERY_BROKER_URL = 'amqp://guest:guest@localhost//' #: Only add pickle to this list if your broker is secured #: from unwanted access (see userguide/security.html) CELERY_ACCEPT_CONTENT = ['json'] CELERY_RESULT_BACKEND = 'django-db' CELERY_TASK_SERIALIZER = 'json' CELERY_CACHE_BACKEND = 'django-cache' INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... 'django.contrib.auth', 'django.contrib.admin', 'django_celery_results', ] When I run celery -A proj worker -l info I get the error: 019-05-01 16:08:50,424: CRITICAL/MainProcess] Unrecoverable error: TypeError("argument of type 'NoneType' is not iterable") Traceback (most recent call last): Any idea as to what I'm doing wrong? RabbitMQ is running as a service. Thank You! -
Django dictonary not passing to template
So I'm passing a variable to Django using ajax. That part works fine as I can print the value on the terminal. The issue I'm having is passing that variable to my template. Instead of returning the date, it returns None. If I manually set the value of data_input = "testing", it would display on the template. views.py if request.method == 'POST': form = AppointmentForm(request.POST) if form.is_valid(): form.save() form = AppointmentForm return render(request, 'scheduling/make_appointments.html',{"form":form}) elif request.method == 'GET': data_input = request.GET.get('date') print(data_input) form = AppointmentForm args = { "form" : form, "data_input": data_input, } return render(request, 'scheduling/make_appointments.html', args) main.js $(document).ready(function () { $("#datetimepicker").on("dp.change", function (e) { e.preventDefault(); date = $('#datepicker').serialize().replace('date=', ''); console.log(date); $.ajax({ type: 'GET', url: '../make_appointments/', data: { 'date': date } }); }); }); make_appointments.html <form id="datepicker" method="get" name="select_date"> <div id="datetimepicker"> <input type="hidden" name="date" id="date"> </div> </form> {{data_input}} -
How to use PostgreSQL schemas with Django dbshell?
How do you update your Django database settings so all database-related management commands use the correct schema defined in the DATABASES OPTIONS parameter? I'm attempting to host multiple logical databases on the same PostgreSQL database, isolated by schema. This is explained in multiple questions, like this one, so my database settings look like: DATABASES[DEFAULT_DB] = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mycommondatabase', 'USER': 'somecommonuser', 'PASSWORD': 'somecommonpassword', 'HOST': 'localhost', 'PORT': 5432, 'OPTIONS': { 'options': '-c search_path=the_real_database_name' }, } However, when I run manage.py dbshell, I find it's ignoring the options and not setting the search_path, and using the incorrect "public" schema by default. $ ./manage.py dbshell psql (11.2 (Ubuntu 11.2-1.pgdg16.04+1)) SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off) Type "help" for help. mycommondatabase=> SELECT schema_name FROM information_schema.schemata; schema_name -------------------- information_schema public pg_catalog the_real_database_name (4 rows) mycommondatabase=> select count(*) from sometable; count ------- 0 (1 row) mycommondatabase=> SET search_path TO the_real_database_name; SET mycommondatabase=> select count(*) from sometable; count ------- 1 (1 row) The user does have the public schema assigned to it as default, so it looks like either PostgreSQL is ignoring the passed in schema and using the user-assigned schema, or Django isn't passing in the schema to use. How do … -
How to add multiple input from one field in django model
I have this models.py code where I want to get multiple values/file from single field without creating another table just for images. Currently I am just repeating these field class contentimage(models.Model): content = models.ForeignKey(element, on_delete=models.CASCADE) title = models.CharField(max_length=200) titleimg1 = models.CharField(max_length=200) image1 = models.ImageField(blank=True, upload_to='media/') img1description = models.TextField() titleimg2 = models.CharField(max_length=200) image2 = models.ImageField(blank=True, upload_to='media/') img2description = models.TextField() titleimg3 = models.CharField(max_length=200) image3 = models.ImageField(blank=True, upload_to='media/') img3description = models.TextField() titleimg4 = models.CharField(max_length=200) image4 = models.ImageField(blank=True, upload_to='media/') img4description = models.TextField() titleimg5 = models.CharField(max_length=200) image5 = models.ImageField(blank=True, upload_to='media/') img5description = models.TextField() An optimal output will be an input field in django admin where a plus sign can add multiple images It would be really very helpful if someone can just guide me in the right direction. -
Objects creation
I have a dataset which return me a set of tuples in this format (region, district, city, role), and I want to create a hierarchy, but the loop doesn't work in correct way, it creates only region objects and also duplicates this objects class Command(BaseCommand): help = 'Fill DB with initial data' def handle(self, *args, **options): for entry in list(get_dataset())[:10]: region, region_created = Place.objects.get_or_create(name=entry[0], role=Place.REGION) district, district_created = Place.objects.get_or_create(name=entry[1], role=Place.DISTRICT, parent=region) city_obj, city_created = Place.objects.get_or_create(name=entry[2], role=entry[3], parent=district) self.stdout.write(self.style.SUCCESS('Database updated successfully!')) -
Elasticsearch prioritise one field in query
I have created an elasticsearch index of documents that have a title field and a text field. Given a query, the desired behavior for my search is that it first checks the title field and, if there are any documents where the title is a "good" match with the query, then those documents must be ranked top. Only after good title matches should documents be returned that have a good text match. By "good title match" I mean something along the lines of "the query is close to some subset of the title, where close means levinshtein distance less than some given number". This is a threshold condition. So either a title is a "good" match, and should rank high, or it is not, and should receive no benefit for getting "some" match with the query. The outcome is binary. So if there is a query "How to garden like the best", a document with the title "garden like the best" should be ranked first, followed by documents that have a good match for the query in their "text" field. A document with title "Budget Gardening" should receive no bonus for having "Gardening" in its title, because it is not … -
Why is my Django sessions storing only two variables in the dictionary
I am using django to create a shopping cart without user authentication. My shopping cart only stores a maximum of two items. def add_to_cart(request,pk,slug): product = get_object_or_404( Product, pk=pk,) product_document = { 'title': product.title, 'price': product.price, } request.session['cart'][str(product.id)] = product_document print(request.session['cart']) return render(request,'selling/cart.html') For example lets say I add shoes for $200, a hat for $20 and a bag for $10. Only the shoes and the hat will be added to the dictionary and the bag will be omitted. -
Vue server and django running on same machine, django server not able to fetch client files
I am trying to run vuejs server and django server on a same machine. It works very well on my local machine where django by default runs on http://127.0.0.1:8000 and vue.config.js has public path listed as 0.0.0.0:8080. But when I run this on my remote machine, I start the django server like ‘python3 manage.py runserver 0.0.0.0:8000’ and to access my django server, I hit the browser with {{ubuntu_machine_ip}}:8000. The browser console complains saying app.js could not be found. I am pretty much sure I am passing wrong IP onto my vue.config.js but couldn't figure out what the IP would be. I have tried 127.0.0.1:8080 but could not make it work. Added my vue.config.js baseUrl settings. const BundleTracker = require("webpack-bundle-tracker"); module.exports = { baseUrl: "http://0.0.0.0:8080/", ''' } -
Uploading file in Django using Dropzone
I'm using Django to develop a website and I want to upload files using dropzone box in HTML template and then send it to a view function and send some message if the file was successfully uploaded This is the code in the HTML template(inputFile_pannel.html): <p>{{mess}}</p> <form action="{% url 'upload_file' %}" enctype="multipart/form-data" class="dropzone" id="myDropzone" > {% csrf_token %} </form> and This is the view function(uplosd_file): @login_required def upload_file(request): uploaded_file_url='' mess='' if request.method == 'POST' and request.FILES['file']: myfile = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) mess='The file is uploade successfully, you can check the status in your pannel' return render(request, 'app/inputFile_pannel.html', { 'mess':mess }) return render(request, 'app/inputFile_pannel.html', { 'mess':mess }) But the mess variable doesn't appear on the web page, could anybody say what's the problem? -
Javascript problem while converting into django template
I'm struggling with a conversion of a html file into a django template. It seems like the main.js file is not working but debug console doesn't throw any errors. I have just copied the files from my local filesystem onto my webserver and changed the url of the static files. There are no 404 errors. This is how my html document looks like on the local file system This is how the templated version on the web server looks like This my include order of the javascript files: <script src="{% static "js/jquery.js" %}" ></script> [...] <script src="{% static "js/main.js" %}" ></script> -
Does my templates directory need a __init__.py file?
I'm using Django and Python 3.7. I have the following in my project hierarchy ... + project + web + views tax_calculator.py + forms __init__.py tax_calculator_form.py + templates tax_calculator.html My view file, "tax_calculator.py" is attempting to render a GET request, using # Basic function that serves the default page def get(request): tax_calculator_form = TaxCalculatorForm() return render(request, "web/templates/tax_calculator.html", {'form': tax_calculator_form}) but I'm getting the error TemplateDoesNotExist at /calculate_taxes when I visit my URL and it's complaining about this line in my view return render(request, "web/templates/tax_calculator.html", {'form': tax_calculator_form}) The path looks correct to me. Why isn't my URL finding my template path? -
How to store multiple variables in a django session
I am trying to create a shopping cart in django that isn't dependent on user accounts. I am using django sessions. The issue I am having is that when I try to add a new item to the session and print out the list of items in the session only the newest item is printed out instead of the whole list of of items in the session. def add_to_cart(request,pk,slug): product = get_object_or_404( Product, pk=pk,) product_document = { 'title': product.title, 'price': product.price } request.session['cart'] = {} request.session['cart'][str(product.id)] = product_document print(request.session['cart']) return render(request,'selling/cart.html') So lets say I add shoes for $400 and then socks for $10, when I print out the session instead of getting both items in a dictionary only the $10 socks are printed out. -
Query django default user model object using email
I am using django's custom user model. I want to query a user object based on email attribute. I am doing like: user = User.objects.get(email = email) but it gives me error File "D:\stocksapp\winenv\lib\site-packages\django\db\models\query.py", line 399, in get self.model._meta.object_name main.models.Code.DoesNotExist: Code matching query does not exist. -
MySQL Community Server 8.0.16 - django.db.utils.OperationalError: (1045, "Access denied for user (using password: YES)")
I'm using Django2.2 with Python3 and MySQL8.0.16 to build out an ETL engine. I have the correct login information for my MySQL instance configured in my Django settings.py file. I know this data is correct because I have tested it to manually log in to MySQL from the CLI. I am having trouble with connecting to the MySQL instance from Django and the 'user' field in the error log does not match up with any users I have configured on my MySQL instance. As a matter of fact, the 'user' field in the error log is actually the user on the UNIX system on my corporate issued laptop. I have already setup a user, john, to have access to the following tables: (note: I want to use production_tab once I can actually connect). mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | production_tab | | mysql | | performance_schema | | sys | +--------------------+ I'm on a corporate issued Macbook so I can't change the default user on my UNIX system: ➜ project git:(master) ✗ dscl . list /Users | tail -5 my_corporate_username root I've tried looking into the MySQL users to further diagnose the issue and … -
Django) queryset filtering in view with ManyToMany Relationship
I've been spending hours on queryset handling of ManyToMany field type. I want to GET objects(model B) which has ManyToMany relationship with another object(model A), by using filter on model A. views.py I get my_user_id from urls.py, which is str. id part works fine, but... class UserUserId(generics.RetrieveUpdateAPIView): #permission_classes = (IsOwner,) queryset = User.objects.all() serializer_class = UserSerializer #serializer for User model def get(self, *args, **kwargs): id = self.kwargs['my_user_id'] return self.queryset.filter(user_id=id).user_schedules.all() urls.py path('user/<str:my_user_id>', views.UserUserId.as_view()), models.py class User(models.Model): user_id = models.TextField(blank=True, null=True) user_schedules = models.ManyToManyField('Schedule', related_name='%(class)s_id') class Schedule(models.Model): sched_id = models.IntegerField(blank=True, null=True) sched_name = models.TextField(blank=True, null=True) It gives me following error : AttributeError: 'QuerySet' object has no attribute 'user_schedules' I tried to resolve this issue by put [0] at the end of filter(), but It seems wrong and It doesn't work if I have to check multiple User objects. So how can I GET user_schedules list of specific User whose user_id is my_user_id? I'm stuck on this for hours, any help would be much appreciated. -
How do I reference my from from my Django view?
I'm using Django and Python 3.7. I have the following in my project hierarchy ... + project + web + views tax_calculator.py + forms __init__.py tax_calculator_form.py The contents of tax_calculator_form.py are as follows ... from django import forms from localflavor.us.forms import USStateSelect class TaxCalculatorForm(forms.Form): state = forms.CharField(widget=USStateSelect) net_income = forms.IntegerField() s_corp_salary = forms.IntegerField() The init.py file is empty. The views/tax_calculator.py file contains this line ... from web.forms import TaxCalculatorForm but I'm getting the error ImportError: cannot import name 'TaxCalculatorForm' from 'web.forms' What's the proper way to include my form in my view file? -
Change image size with PIL in a Google Cloud Storage Bucket (from a VM in GCloud)
This is what I need: when a user upload an image, verify if that image exceeds some size, if so change the size. This code works with no errors, but the image saved has the size without changes. The image is in a Google Cloud Storage Bucket, it is uploaded just before, but it works fine. from PIL import Image from django.core.files.storage import default_storage from google.cloud import storage from google.cloud.storage import Blob import io if default_storage.exists(image_path): client = storage.Client() bucket = client.get_bucket('mybucket.appspot.com') blob = Blob(image_path, bucket) contenido = blob.download_as_string() fp = io.BytesIO(contenido) im = Image.open(fp) x, y = im.size if x>450 or y>450: im.thumbnail((450,450)) im.save(fp, "JPEG") # im.show() here it shows the image thumbnail (thumbnail works) blob.upload_from_string(fp.getvalue(), content_type="image/jpeg") blob_dest = Blob('new_image.jpg', bucket) blob.download_as_string() blob_dest.rewrite(blob) -
How to enforce forms inside formset to have different values?
I have 3 forms in a formset and I need to make sure the submitted value in each form is different. The following code works. I am adding cleaned_data to a list and checking if the cleaned_data from each form is already on the list. If it is, I return an error. Otherwise, I add it to the list. views.py. def my_view(request): MyFormSet = formset_factory(MyForm, extra=3, max_num=3) formset = MyFormSet(request.POST or None) if formset.is_valid(): a_list = list() for form in formset: if form.cleaned_data in a_list(): messages.error('error') return redirect('app:my_view') else: a_list.append(form.cleaned_data) ... forms.py class MyForm(forms.Form): my_field = forms.ModelChoiceField(queryset=MyModel.objects.all()) Is there a better way to make sure every value in each form is different? Perhaps validate this on the clean function in MyForm? -
Including primary key in django url for included namespaces?
I have the following in my urls.py: ta_patterns = [ path('no_pk_needed/', view1.as_view()), path('pk_needed/<int:campaign_pk>/', view2.as_view()), ] campaign_patterns = [ path('ta/', include((ta_patterns, 'ta'), namespace='ta')), ] This generates the following url: campaign/ta/no_pk_needed/ campaign/ta/pk_needed/<int:campaign_pk>/ I would like campaign_pk to be as close to campaign/ as possible. Ideally, I would like to achieve this: campaign/ta/no_pk_needed/ campaign/<int:campaign_pk>/ta/pk_needed/ But I don't know how this could be done using my current pattern. How can I do this? -
How to execute code automatically after manage.py runserver
I need to read a csv file just after running server. It can't be done in any view because it need to be preload to execute all views, so I need to do it immediately after "manage.py runserver". Is there any file where I can write the code that I need to execute in first place? -
TypeError at /ask update() got multiple values for argument 'id'
When i try to ask question I got an error, TypeError at /ask update() got multiple values for argument 'id' but after reload homepage , question that i asked saved. from models.py def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super().save(force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields) elasticsearch.upsert(self) #PROBLEM HERE from views.py def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super().save(force_insert=force_insert, #PROBLEM HERE force_update=force_update, using=using, update_fields=update_fields) elasticsearch.upsert(self) from elasticsearch.py def upsert(question_model): client = get_client() question_dict = question_model.as_elasticsearch_dict() doc_type = question_dict['_type'] del question_dict['_id'] del question_dict['_type'] response = client.update( settings.ES_INDEX, doc_type, id=question_model.id, body={ 'doc': question_dict, 'doc_as_upsert': True, #PROBLEM HERE } ) return response -
Accessing an image stored with FileStorage from a custom template tag in Django
I have used Django's FileStorage to store an image, and I have sent the url of this image from a template to a custom templatetag. But I am not able to access the image at this url. I have also tried accessing the media directory to get the uploaded image but I get the following error: IsADirectoryError at / [Errno 21] Is a directory: '/media/' views.py def index(request): context = {} if request.method == "POST": up_image = request.FILES['image'] fs = FileSystemStorage() name = fs.save(up_image.name,up_image) context['url'] = fs.url(name) return render(request,"ind.html",context) settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' template ind.html {% load testing %} <p>{% fname url %}</p> custom templatetag testing.py from django import template import webbrowser from PIL import Image register = template.Library() @register.simple_tag def fname(url): x = url[7:] #getting only the name of the file uploaded path = '/media/'+x with Image.open(path) as image: width, height = image.size return width I have also tried opening the image with the url passed itself but I could not get it to work. I am just trying to access the uploaded image so I can do some further processing for it, but for now I am just returning the width of the image …