Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django strange behaviour when using Dygraph
I have a server written in django and i want to show some graph using dygraph on a template. I have written one view and its associated url and also pass some variables through context to template. Using those context variables i want to show graph. But the issue is, the graph is not showing and there is strange behaviour in urls. Below i am posting the template, url and view code. @login_required def profile(request, mid): user = request.user context = {} delta_T = 1000 data = subprocess.check_output("tail -n {0} {1}".format( delta_T, filename ), shell=True) data = data.split("\n".encode()) heatcsv = "" fancsv = "" tempcsv = "" plot = [] for t in range(len(data)): line = data[t].decode("utf-8") entry = line.strip().split(" ") try: plot.append([int(float(i)) for i in entry[0:-1] \ + [float(entry[-1])]]) heatcsv += "{0},{1}".format(t+1, entry[1]) fancsv += "{0},{1}".format(t+1,entry[2]) tempcsv += "{0},{1}".format(t+1, entry[3]) except: continue plot = zip(*plot) context["mid"] = mid context["delta_T"] = delta_T context["heat"] = heatcsv context["fan"] = fancsv context["temp"] = tempcsv return render(request,"dashboard/profile.html",context) Template Code: {% load staticfiles %} {% block title %} Dashboard - Profile {% endblock %} {% block headerfiles %} <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script> <script type="{% static 'js/jquery-ui.js' %}"></script> <link rel="stylesheet" type="text/css" href="{% static 'css/jquery.datetimepicker.css' %}"/> <link rel="stylesheet" … -
django relationships into a cbv
I have this two models: class MenuGroup(models.Model): name = models.CharField(max_length=30) class MenuProduct(models.Model): name = models.CharField(max_length=30) ingredients = models.CharField(max_length=250) price = models.FloatField(null=True, blank=True, default=0.0) group = models.ForeignKey(MenuGroup, on_delete=models.CASCADE) I want to get all the records of MenuGroup with all the MenuProduct records related. Template side i need to have structure like this: {% for group in menugroups %} ... {% product in group.menuproducts %} How to express this into a Django CBV view? -
How to get http response code w.r.t. a url in django?
I need to apply a if statement in template file based on response code with respect to a url. As I'm not aware of any direct method, I'm planning to make a custom template tag like: from django import template register = template.Library() @register.filter(name='code') def code(url): a = http.response(url) return a I will then call this within the template as: {% if model.fileurl|code==200 %} <div>..............</div> Also, is there any way to do it directly within the template as I'm trying to fill in the shoes of our django developer. -
Aggregate annotation results to annotate model
I'm working on a crowdsourcing engine, in which each Task can have multiple items. Each Item can have multiple Annotations - one from each User. I also have created model for Package, which can store items from multiple tasks. All packages have the same number of items. class Package(models.Model): items = SortedManyToManyField(Item) class Item(models.Model): task = models.ForeignKey(Task) class Annotation(models.Model): item = models.ForeignKey(Item) user = models.ForeignKey(User) I want to sort packages based on how many users finished all items from a certain package. I've tried to: group packages by ("packages", "packages__items__annotations__user") pair then use annotate function to achieve count of annotations done by user in a certain package after that I've divided it by number of items in package and I named it "full_annotations". But I don't know how I can now annotate "package" with a sum of all "full_annotations" in this "package". My current code: items_in_package = 2 mission.packages.values("packages", "packages__items__annotations__user").annotate(full_annotations=Count('packages__items__annotations')/items_in_package) QuerySet [{'packages': 1, 'packages__items__annotations__user': 1, 'full_annotations': 1}, {'packages': 1, 'packages__items__annotations__user': 2, 'full_annotations': 1}, {'packages': 2, 'packages__items__annotations__user': 1, 'full_annotations': 1}, {'packages': 3, 'packages__items__annotations__user': 1, 'full_annotations': 0}, {'packages': 3, 'packages__items__annotations__user': None, 'full_annotations': 0}, {'packages': 4, 'packages__items__annotations__user': None, 'full_annotations': 0}] I managed to do it using SQL query, but I need a QuerySet … -
How can I show a specific django field in html?
So I want to do what the title says and I don't know how since I'm new at this. <p>{{ form.description }}</p> That's the way I show information from different models in a listing using {% for form in forms %} But I want to show the description of an specific object. Thanks in advance. -
Django, deleting an object and creating new one at the same moment(in new model)
I am looking for a way how to delete an object and create new one(in new model) in the same time. I mean I want to have, a base of deleted elements. I got table with delete button within form(DeleteView). Thank you for answers. -
Docker Nginx does not listen to browser
I have this docker-compose.yml file: version: '2' services: nginx: image: nginx:latest container_name: nz01 ports: - "8001:8000" volumes: - ./src:/src - ./config/nginx:/etc/nginx/conf.d depends_on: - web web: build: . container_name: dz01 depends_on: - db volumes: - ./src:/src expose: - "8000" db: image: postgres:latest container_name: pz01 ports: - "5433:5432" volumes: - postgres_database:/var/lib/postgresql/data:Z volumes: postgres_database: external: true And this dockerfile: FROM python:3.5 ENV PYTHONUNBUFFERED 1 RUN mkdir /src RUN mkdir /static WORKDIR /src ADD ./src /src RUN pip install -r requirements.pip CMD python manage.py collectstatic --no-input;python manage.py migrate; gunicorn computationalMarketing.wsgi -b 0.0.0.0:8000 The web and postgres server does not return an error log, just the succes when run docker-compose build and docker-compose up -d. At this moment the three containers are running, but when I go to the browser and navigate to: localhost:8001 it does not work. It shows the "connection has been restarted" error message. Despite that, the web server still withou returning any error, so I guess that I have all properly configurated in my django app. I really believe that the problem is related to nginx, because when I review the nginx log (using kinematic) it stills empty. Why can be happening to nginx to do not listen to petitions? Hint: … -
Django Model not Defined in views.py
I have a django app that I'm trying to provide an ID and have it return records from a mysql database based on that ID. Here's my models.py: from django.db import models class RateskioskMain(models.Model): EID = models.BigIntegerField(unique=True, default=0,) ETISmUnits = models.BigIntegerField(blank=True, default=0) ETISmHours = models.FloatField(blank=True, default=0) It created a table in my database called rateskiosk_rateskioskmain. Here's my views.py: def homepage_view(request): result_obj = None if request.method == 'GET': pass elif request.method == 'POST': eid = request.POST.get('eid') result_count = RateskioskMain.objects.filter(EID=int(eid)).count() if result_count > 0: result_obj = RateskioskMain.objects.get(EID=eid) return render(request, 'ratekiosk/homepage.html', {'result_obj': result_obj}) But then when I try to run it, I get: Exception Type: NameError at / Exception Value: name 'RakesKioskMain' is not defined Not sure what I'm missing, but any help is greatly appreciated. -
what is the procedure to create Django forms and how to save it in a postgre database?
I want to create an application form for my student management system using Django. Can anyone describe the whole procedure, I am confused about using ModelForms or rendering forms simply via HTML. How do we actually create forms and save it and view it in our database? Can the database be viewed only on Django' admin panel or via terminal too? -
Django admin site shows not related models
I have two models. Question and Choice. Every Question can have multiple Choices but every Choice can only have one Question. When I create the first question everything works fine but when I add a second one, Django tries to implement the Choices from Question 1 to Question 2... Here are my files: models.py: class Question(models.Model): question = models.CharField(max_length=127, help_text="Frage, höchstens 127 Zeichen lang.") pub_date = models.DateTimeField(auto_now=True) onlyFor = models.CharField(max_length=63, default="All", help_text="Wer darf an dieser Umfrage teilnehmen? Frei lassen wenn jeder dran teilnehmen darf") must_verified = models.BooleanField(default=True, help_text="Muss der Benutzer verifiziert sein um an dieser Umfrage teilnehmen zu dürfen?") tags = models.CharField(max_length=511, default="Django;", help_text="Tags, um Benutzern personalisiertere Fragen zu zeigen, höchstens 511 Zeichen lang, mit Semikolon abtrennen.") id = models.CharField(max_length=16, default="0000000000000000", primary_key=True) def __str__(self): return self.question def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) def save(self, *args, **kwargs): while Question.objects.filter(id=self.id).exists(): self.id = "".join(random.choices(string.ascii_letters + string.digits, k=16)) super(Question, self).save(*args, **kwargs) class Choice(models.Model): Question = models.ForeignKey(Question, on_delete=models.CASCADE) CssStyle = models.CharField(max_length=1023, help_text="CSS, höchstens 1023 Zeichen lang.", blank=True, null=True) color = models.CharField(max_length=31, help_text="Farbe (In CSS), welche für Statistik verwendet wird, höchstens 31 Zeichen lang.", default=None) choice = models.CharField(max_length=127, help_text="Antwortmöglichkeit, höchstens 1023 Zeichen lang.") votes = models.CharField(max_length=16384, blank=True, default="0") def __str__(self): return self.choice admin.py: class … -
Django: How to assign foreign key in URL to a Createview form
I'm trying to create a review system to items on the site. in order to do that I created 2 models one for the item (Festival) and one for the reviews. the item is a foreign key of the review. What I'm trying to do is passing the PK of the item in the url and set it as a foreign key of the review. I'm currently getting this error: NoReverseMatch at /festivals/55/ Reverse for 'create_review' with arguments '(55,)' not found. 1 pattern(s) tried: ['festivals/create/review/$'] I spent ages trying to solve this :/ Views.py: class CreateReview(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): form_class = forms.ReviewFormCreate model = models.Review template_name = 'festival_list/review_form.html' success_url = '/' def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() form.instance.festival = get_object_or_404(models.Festival, pk=self.kwargs['pk']) return super(CreateReview, self).form_valid(form) urls.py path('create/review/',views.CreateReview.as_view(),name='create_review'), Models class Review(models.Model): user = models.ForeignKey( User, related_name='Reviews', on_delete=models.CASCADE, ) festival = models.ForeignKey( Festival, related_name='Festival_Reviews', on_delete=models.CASCADE ) template link: <a class="btn btn-success" href="{% url 'festival_list:create_review' festival.pk %}">Add Review</a> Many thanks for your help =] -
Include Django template with Ajax
Im using mmenu from jquery in my Django app and I'm loading subpages with iframes. Everything works fine but I would like to remove iframes and load content with ajax to let user use app without reloading whole page after menu click. template - home_desktop.html {% load compress %} {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width initial-scale=1.0 maximum-scale=1.0 user-scalable=yes" /> <title>(BETA) icci - inteligent interface for blockchain</title> <meta name="description" content="Platforma informacyjna i narzędziowa dla blockchain. Standaryzacja w sektorze kryptowalut. Ułatwienie dostępu do technologii."> <link rel="icon" type="image/png" href="{% static "favicon.ico" %}"/> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous"> {% compress css %} <link rel="stylesheet" href="{% static "style.css" %}" > <link rel="stylesheet" href="{% static "menu-nav.css" %}" > <link rel="stylesheet" href="{% static "jquery.mmenu.all.css" %}" > {% endcompress %} {% compress js inline %} <script src="{% static "scripts/jquery-3.3.1.js" %}"></script> {% endcompress %} {% compress js inline %} <script src="{% static "jquery.mmenu.all.js" %}" ></script> <script src="{% static "./script.js" %}" ></script> {% endcompress %} </head> <!-------------- BODY --------------> <body> <!-------------- MENU --------------> <nav id="menu"> <div id="panel-information"> <ul> <li class="Divider">Blockchain / Kryptowaluty</li> <li><a id="2">News</a> <li><a id="4">Events</a></li> </ul> </div> </nav> <!-------------- END OF MENU --------------> <!-------------- INTERFACE --------------> <div id="inferface"> <div class="interface " … -
Django: need to render form options manually
I need to replicate this form: I've been reading the docs on how to render fields manually, but cannot render the radio inputs an their values manually. https://docs.djangoproject.com/en/2.1/topics/forms/#rendering-fields-manually My problem specifically is with the "Select a quantity part". 1) My form inheriets from forms.ModelForm and only contains the quantity, no the cost (in $) neither the savings part. That's why I need to put the quantity in a tag, pulling it from the form, and use other 2 tags in pure html to manually put the cost and the savings. Unless there is a way to put these values in the model as others field, but related to the field quantity (cantidad, in spanish). Desired HTML: Copied from this page I need to replicate: https://www.stickermule.com/products/die-cut-stickers <form> <div id="variants" class="product-option-group"> <legend>Select a size</legend> <ul id="variant-options" class="options"> <li> <input id="variant_79" name="variant_id" readonly="" type="radio" value="79"> <label for="variant_79"> 2" x 2"</label> </li> <li> <input id="variant_78" name="variant_id" type="radio" value="78"> <label for="variant_78"> 3" x 3"</label> </li> <li> <input id="variant_80" name="variant_id" type="radio" value="80"> <label for="variant_80"> 4" x 4"</label> </li> <li> <input id="variant_81" name="variant_id" type="radio" value="81"> <label for="variant_81"> 5" x 5"</label> </li> <li> <input id="variant_77" name="variant_id" type="radio" value="77"> <label for="variant_77"> Custom size</label> </li> </ul> </div> <div id="quantities"> <legend>"Select … -
NoReverseMatch at / Django
I am new to Django and I am trying to create sample project in it. Please help me in resolving this error. My Main URLs.py file urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^t20_predict/', include('PredictMatch.urls')), ] My Apps URLs.py file app_name = 'PredictMatch' urlpatterns = [ # t20_predict url(r'^$', views.index, name='index'), # t20_predict/id url(r'^(?P<t20_id>[0-9]+)/$', views.detail, name='detail'), # t20_predict/id/favorite url(r'^(?P<t20_id>[0-9]+)/favorite/$', views.favorite, name='favorite'), # t20_predict/T20 url(r'^T20/$', views.t20index, name='t20index'), ] My Views.py file def index(request): match_types = Matchs.objects.all() return render(request, 'PredictMatch/portal-1/index.html', {"match_types": match_types}) def detail(request, id): t20_match = get_object_or_404(T20Match, id=id) return render(request, 'PredictMatch/portal-1/detail.html', {'t20_match': t20_match}) def t20index(request, match_id): match_type = get_object_or_404(Matchs, match_id=1) return render(request, 'PredictMatch/portal-1/index.html', {'match_type': match_type}) My index.html file {% if error_message %} <p>{{ error_message }}</p> {% endif %} {% if match_types %} <h2>Match Types</h2> <ul> {% for m in match_types %} <li><a href="{% url 'PredictMatch:t20index' m.id%}" >{{ m.match_type }}</a> </li> {% endfor %} </ul> {% endif %} The error I am getting is Reverse for 't20index' with arguments '(1,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['t20_predict/T20/$'] If I remove m.id from my index.html file and just keep as {% url 'PredictMatch:t20index'%} then it is running file. -
Django Eliminating Duplicate HTML not relying on model data.
I need the most efficient way to eliminate HTML elements in my Django application. Here is an example. <body> <input="text", id="a", class="class"> <input="text", id="x", class="class"> <input="text", id="c", class="class"> <input="text", id="w", class="class"> </body> As you can see, there is much repeated HTML here but they differ in id. I would like a function like gen_input(id) that I can put directly into the HTML file. These ids do not rely on data, this is all static HTML. I found some features that accomplish things like this but do not support arguments. What is the best way of going about this? Thanks for the help. -
Django: Creating permissions that relate two `User` objects together
Is there any way to set up a permissions system where permissions relate User objects together, i.e. where one User may have the permission to read another User's info (but not necessarily the other way around)? I've read the documentation but it's sparse and from what I can tell permissions are not capable of handling dynamic use-cases. Basically, I want a permission system that determines what two+ model objects can "do" to each other. Bonus points if you have any input on how to integrate this into Django Rest Framework. -
Django ListView with filter option, like DjangoAdmin
I am trying to implement a ListView with the filter capability like the one in Django Admin. I looked into django-filter, but its not clear how to use that on my template. This is my ListView: @method_decorator(login_required, name='dispatch') class ListProjects(ListView): model = Project paginate_by = 100 list_filter=('start_dt','end_dt','status') In this case I would like to filter by those three fields. -
Getting the first 3 children(items) for each owner in a list of primary keys
I have the following models class Item(models.Model): owner = models.ForeignKey(Owner, related_name='owner_items', on_delete=models.CASCADE) # general information name = models.CharField(max_length=255) class Owner(models.Model): # general information name = models.CharField(max_length=255) For each owner I want to get the first 3 items if exist. I created the following query: qs = qs.filter(owner_id__in=owner_id_list)[:3] owner_id_list is a list of ids(primary keys of the Owner objects) The resulting query(django-debug-toolbar) is: select "items_item"."short_description" FROM "items_item" WHERE ("items_item"."owner_id" IN (64, 65, 130, 99, 43, 140, 108, 143, 115, 154)) ORDER BY LIMIT 3 Clearly is not ok, because is selecting just 3 items from all owners, not a maximum 3 items per owner. -
libreries django taggit haytack, colab, image
always when i tried to install with pip install Image, PIL, colab, a few libraries... i can't because i have this problem. I tried to learn deep learning , but i can't work because i never can't use the appropriate libraries ( problem when i tried to install them) tried to install django-taggit...django haytack... dj>1.11... django-taggit 0.23.0 has requirement Django>=1.11, but you'll have django 1.7.11 which is incompatible. django-haystack 2.8.1 has requirement Django>=1.11, but you'll have django 1.7.11 which is incompatible. :( -
name 'HttpsResponse' is not defined
from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpsResponse("Hello World, I am there") Create your views here. -
How to access extended User attributes in django template
I am trying to access extended field of User model in Django template but it doesn't work, there are my files: models.py: class Author(models.Model): user = models.OneToOneField(User, related_name='user', on_delete=models.SET_NULL, null=True) bio = models.TextField( max_length=1400, help_text="Enter author biography.") def __str__(self): return self.user.username def create_profile(sender, **kwargs): user = kwargs["instance"] if kwargs["created"]: user_profile = Author(user=user, bio='my bio') user_profile.save() post_save.connect(create_profile, sender=User) template: {% extends "base_generic.html" %} {% block title %} <title>Author {{user}}</title> {% endblock %} {% block content %} <h1>{{user}}</h1> <h2>Bio:</h2> <p>{{user.author.bio}}</p> <div> {%for item in user.author.blogs_set.all%} <p>{{item.title}}</p> <hr> {%endfor%} </div> {% endblock %} I want to get access to the bio field through user.author.bio but nothing displays I have also tried user.bio is there any tricky way to get access to this field? -
Django 2.2 most basic website with one template-file and without database
These are the folders of my django project: project/ manage.py server/ ... urls.py app/ html/ index.html urls.py views.py I have already tried to understand the django documentation for hours, but I just don't get it. I simply want to start with displaying the html-content of index.html in my browser at http://localhost:8000/ and nothing else. No database, no models, just plain html as a start. (Why does the django-guys start the tutorial so complicated?) How do I have to setup which file to render ìndex.html? Right now the content of project/app/views.py looks like this: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the app index.") I tried the instructions concerning the render shortcut at tutorial 3, but the server always respond with that yellow TemplateDoesNotExist-Error. -
How to display html tables from external database in django?
Data is fetched from an external database using regular python. I would like to display the data as tables in my django application. Thanks in advance. -
Django direct sql template loops
I'm working on a Django project where we would like to implement additional app (catalog) where data is stored in a existing db (MS SQL) and we only have access to some of its functions, views and stored procedures. Additional to that the db is using composite keys for its joints. The composite key between two models is supplier + article models.py class Articles(models.Model): supplier = models.IntegerField() article = models.CharField(max_length=15) category = models.CharField(max_length=15) brand = models.CharField(max_length=50) description = models.CharField(max_length=250) class Meta: managed = False class TradeNumbers(models.Model): supplier = models.IntegerField() article = models.CharField(max_length=15) tradenumber = models.CharField(max_length=15) class Meta: managed = False I pupulate models with raw SQL where I call for MS SQL functions. views.py def article_list(request): articles = ReferenceNumbers.objects.using('db2').raw("SELECT * FROM dbo.fn_SearchEngine_AddField ('{}')".format(a)) tradenumbers = TradeNumbers.objects.using('db2').raw("SELECT * FROM dbo.fn_SearchEngine_TradeNr ('{}')".format(a)) return render(request, '/articlelist.html', {'articles': articles, 'tradenumbers': tradenumbers}) Now I would like to render a table where data should be: supplier1; article1; category; description; tradenumber1, tradenumber2... supplier1; article2; category; description; tradenumber5, tradenumber78.. articlelist.html {% for art in articles%} <tr> <td>{{art.supplier}}</td> <td>{{art.article }}</td> <td>{{art.category }}</td> <td>{{art.description }}</td> <td> {% for tradenr in tradenumbers %} {% if art.supplier == tradenr.supplier and art.article == tradenr.supplier %} {{ tradenr.refnr|default_if_none:"" }}, {% endif %} {% endfor … -
Django can't find a file stored in my application folder
I have a folder that stores a json file in my django application folder, ie, test_data/data.json. In my tests.py, I am trying to read this file using the following code: with open('/test_data/data.json', 'r') as f: self.response_data = json.load(f) However, I keep on getting the following error: FileNotFoundError: [Errno 2] No such file or directory: '/test_data/data.json' What am I doing wrong? Thanks.