Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django mock timezone aware datetime on creating model
I have a test where I create a few objects: def test_get_courier_task_returns_couriers_tasks(self): with patch('django.utils.timezone.now', return_value=make_aware(datetime(2018, 1, 24, 11, 57))): task1 = TaskFactory() response = json.loads(MyAPI.get_tasks_list(self.user.username)) print('[*] Response timestamp: {}'.format(response['content'][0]['timestamp'])) The Task has created_timestamp field with auto_add_now set to True and to_json() method which is used in get_tasks_list() above: class Task(models.Model): created_timestamp = models.DateTimeField(auto_now_add=True) def to_json(self): to_return = { 'timestamp': self.created_timestamp.strftime('%d-%m-%Y %H:%M') } return to_return Unfortunately tests give this output: [*] Response timestamp: 24-01-2018 10:57 I have checked that this is timezone aware, but instead of giving me UTC+1 it gives UTC+0 on saving. What do I have to do? I have USE_TZ = True in my settings and I have applied migrations. This question did not help with my problem. -
NoReverseMatch at /posts/ Error in Django project
I write simple Django-blog, django.VERSION - (2, 0, 1, 'final', 0) But I receive an error and don't understand how to fix it. NoReverseMatch at /posts/ Reverse for 'detail' with keyword arguments '{'id': 16}' not found. 1 pattern(s) tried: ['posts\\/(?P<id>\\d)/$'] And Error during template rendering In template djangoblog/posts/templates/posts/base.html, error at line 0 Reverse for 'detail' with keyword arguments '{'id': 16}' not found. 1 pattern(s) tried: ['posts\\/(?P<id>\\d)/$'] 1 {% load staticfiles %} 2 <!DOCTYPE html> 3 <html lang="en"> 4 <head> 5 <meta charset="UTF-8"> 6 <title>{% block head_title %} 7 Django-blog! {% endblock head_title %}</title> 8 <link rel="stylesheet" 9 models.py from django.db import models from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=200) image = models.FileField(null=True, blank=True) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"id": self.id}) class Meta: ordering = ['-timestamp', '-updated'] My def in views.py look like def post_list(request): queryset_list = Post.objects.all() paginator = Paginator(queryset_list, 5) page = request.GET.get('page') queryset = paginator.get_page(page) context = { 'object_list': queryset, 'title': 'List' } return render(request, 'posts/post_list.html', context) in urls.py urlpatterns look like re_path('^$', post_list, name='list') Thank you very much. -
How can I do join in django?
I'm working with django, expecially with QuerySet right now and I have a very big problem. so, this is my code: resources_rights = Resources_rights.objects.filter( group_id__in = groups ) resources = Resources.objects.filter( id__in = resources_rights__resource_id ) Resources_rights refers to a models that have resource_id, group_id, read, write and execute. Resources, instead, contains last_modify, name, description and of course the id. So, in resource_rights i save some objects and everyone has his resource_id. I would filter Resources using resource_id fields in resource_rights, but like I had do is not possible because the first query returns objects. So, how can I do? there is an operator for that? thank you all! -
How to deploy Django with Channels and Celery on Heroku?
How one deploys the following stack on Heroku platform ? Django Django Channels Celery The limitation surely is on the Procfile. To deploy Django with Celery it would be something like: web: gunicorn project.wsgi:application worker: celery worker --app=project.taskapp --loglevel=info While deploying Django with Channels: web: daphne project.asgi:channel_layer --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker -v2 The web process can use ASGI, but the worker process will be used by Channels and I don't see how Celery can be started alongside it. -
Django Update and CreateView using the same Crispy Form, Add view Error
I'm using the same crispy form for add and edit and have added a variable to so I can change the submit button text from add to edit and vice versa. However the add view is coming up with the below error: Traceback: (removed the in built references) ... File "/itapp/itapp/sites/views.py" in dispatch 954. return super(AddSubnet, self).dispatch(*args, **kwargs) ... File "/itapp/itapp/sites/views.py" in get_context_data 969. context = super().get_context_data(**kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/edit.py" in get_context_data 93. kwargs['form'] = self.get_form() File "/usr/local/lib/python3.6/site-packages/django/views/generic/edit.py" in get_form 45. return form_class(**self.get_form_kwargs()) Exception Type: TypeError at /sites/site/add_subnet/7 Exception Value: 'SubnetForm' object is not callable im not sure as to why as the code for the form looks good to my unskilled eyes at least anyway forms.py: class SubnetForm(forms.ModelForm): class Meta: model = SiteSubnets fields = ['subnet', 'subnet_type', 'circuit', 'device_data', 'vlan_id', 'peer_desc'] def __init__(self, *args, **kwargs): site_id = kwargs.pop('site_id', None) self.is_add = kwargs.pop("is_add", False) super(SubnetForm, self).__init__(*args, **kwargs) self.fields['circuit'].queryset = Circuits.objects.filter(site_data=site_id) self.helper = FormHelper(self) self.helper.form_id = 'subnet_form' self.helper.form_method = 'POST' self.helper.add_input(Submit('submit', 'Add Subnet' if self.is_add else 'Edit Subnet', css_class='btn-primary')) self.helper.layout = Layout( Div( Div( Field('subnet', placeholder='Subnet'), Div('subnet_type', title="Subnet Type"), css_class='col-lg-3' ), Div( Div('circuit', title='Circuit'), Div('device_data', title="Device Data"), css_class='col-lg-3' ), Div( Field('vlan_id', placeholder='VLAN ID'), Field('peer_desc', placeholder="Peer Description"), css_class='col-lg-3' ), css_class='row' ) ) Views: … -
django update many to many field in update view
I am currently working on a project using Django. Below, I have a model that has manytomany fields. employees = models.ManyToManyField(user_model.EmployeeProfile, blank=True) How to add an object from a related model to that field? I use the update view and override the form_valid function. def form_valid(self, form): self.object = form.save(commit=False) self.object.save() employee = user_model.EmployeeProfile.objects.get(user=self.request.user.id) self.object.employees.add(employee) return super().form_valid(form) The above code is not working properly. I need help. Thank you in advance. -
makemigrations failing after moving from Windows to Linux with Postgres
I have a small web app (using Postgres) that I have been developing in a Django Windows environment and it is working fine. I'm now trying to move it to Redhat 6.8 and makemigrations is failing. I've installed Postgres and created the database on Linux. I created the database new because I didn't need any of the old test data on Windows. I moved over all of the files (except the .pyc files). Below is the error I'm getting. It seems it is trying to access a table that is not yet created. (It's not yet created because I haven't been able to run a migration yet( sort of a chicken/egg paradigm). Note, from what I've read, I also removed all of the migrations files except init.py. I've been wrestling with this for many hours. Any help would be greatly appreciated. Thank you. webtest2) [asilver@SDNAUTOS02 sdnlabs2]$ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/management/ utility.execute() File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/management/ self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/management/ self.execute(*args, **cmd_options) File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/management/ self.check() File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/management/ include_deployment_checks=include_deployment_checks, File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/management/ return checks.run_checks(**kwargs) File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/checks/regi new_errors = check(app_configs=app_configs) File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/checks/urls return check_resolver(resolver) File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/checks/urls return check_method() File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/urls/resolvers.p for pattern in self.url_patterns: … -
Saving URL field value from Django view
I am trying to add the value of a URLField in my views as game_url = "https://stackoverflow.com/" here the value I am assigning is of type string.a in my models I have game_url = models.URLField() but my game_url is saved as (u"https://stackoverflow.com/"). I know it is because of encoding, but I don't know how exactly to solve it in Django. -
How to add Keyboard event in Django
I want to control my website use keyboards buttons, if i press the key "a" i will call an url from my liste of urls , for examples the url who call my index view, is there any recommendation of django packages ? -
nginx Permission denied on Ubuntu
I'm trying to set up my Django app with uWSGI and nginx by following this guide. I'm able to run my app with Django's development server, as well as being served directly from uWSGI. I'm running everything on a university managed Ubuntu 16.04 virtual machine, and my user has sudo access. My problem: When getting to this bit of the tutorial, and try to fetch an image, I get a 403 error from nginx. The next section results in a 502. /var/log/nginx/error.log shows connect() to unix:///me/myproject/media/image.jpg failed (13: Permission denied) while connecting to upstream connect() to unix:///me/myproject/project.sock failed (13: Permission denied) while connecting to upstream for the 403 and 502, respectively. I have read multiple questions and guides (one here, another here and yet another one, and this is not all of them), changed my permissions and even moved my .sock to another folder (one of the SO answers recommended that). What else can I try? Here's my nginx.conf # exam_grader_nginx.conf # the upstream component nginx needs to connect to upstream django { # server unix:///path/to/your/mysite/mysite.sock; # for a file socket server unix:///usr/share/nginx/html/exam_grader.sock; # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of … -
ImportError: No module named blog Django
I am new in python i try to create blog in django, when i try to create module by typing python manage.py startapp blog this command python version : 2.7 django-admin version : 1.8 In settings.py INSTALLED_APPS when i add 'logicmindblog.blog', and try to runserver It give me error ImportError: No module named blog Django But when i remove project name and just add 'blog' in and run server this migration and admin working fine, i can add blog , blog category from admin section Can anyone help me figure this, Thanks in advance logicmindblog/ ├── blog │ ├── admin.py │ ├── admin.pyc │ ├── __init__.py │ ├── __init__.pyc │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0001_initial.pyc │ │ ├── __init__.py │ │ └── __init__.pyc │ ├── models.py │ ├── models.pyc │ ├── __pycache__ │ │ └── __init__.cpython-35.pyc │ ├── tests.py │ ├── views.py │ └── views.pyc ├── db.sqlite3 ├── logicmindblog │ ├── __init__.py │ ├── __init__.pyc │ ├── __pycache__ │ │ ├── __init__.cpython-35.pyc │ │ └── settings.cpython-35.pyc │ ├── settings.py │ ├── settings.pyc │ ├── urls.py │ ├── urls.pyc │ ├── views.py │ ├── views.pyc │ ├── wsgi.py │ └── wsgi.pyc ├── manage.py └── views ├── … -
Django button in Modelclass
I'm making an inventory app in which I could update the values of the products from my 'home.html'. My proj name is Inventory App name is myapp Problem I am facing is that every time I update the value of a Stock from my homepage, it adds a new Product instead of updating the one that I want! I am using the ModelsForm Class provided by Django. Using Django=1.11 and Python=3.6 My project's urls.py: from django.conf.urls import url,include from django.contrib import admin from myapp.views import home urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^myapp/', include('myapp.urls', namespace="myapp")), url(r'^myapp/home/', home, name='home'), ] My forms.py: from django import forms from .models import Inventory class Operations(forms.ModelForm): class Meta: model = Inventory fields = ('stocks_left',) My app's Model.py: from django.db import models import uuid class Inventory(models.Model): """ Model representing a the inventory. """ id = models.UUIDField(primary_key=True, default=uuid.uuid4) inventory_name = models.CharField("INVENTORY NAME" ,max_length=200, help_text="This contains the Inventory name:") short_name = models.CharField(max_length=20, help_text="This contains an abbreviation:") inventory_code = models.IntegerField("INVENTORY CODE" ,default = '0', help_text="This contains the Inventory code:") price = models.IntegerField(default = '0') stocks_left = models.IntegerField("STOCKS LEFT",default = '0') def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return '{0} ({1}) ({2})'.format(self.inventory_name,self.inventory_code,self.stocks_left) My app's … -
How to make a writable ManyToManyField with a Through Model
I have a Product class that has "source products"; I use a many-to-many field with a through model to represent it (the database tables already exist, and that's the only way I found to configure the models): class Product(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) product_name = models.TextField() source_products = models.ManyToManyField('self', symmetrical=False, related_name='derived_products', through='Link', through_fields=('product', 'source'),) class Meta: db_table = 'product' managed = False class Link(models.Model): product = models.ForeignKey('Product', models.CASCADE, db_column='uuid', related_name='source_links') source = models.ForeignKey('Product', models.CASCADE, db_column='source_uuid', related_name='+') class Meta: db_table = 'link' unique_together = (('product', 'source'),) managed = False My serializer is dead simple: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('uuid', 'product_name', 'source_products', ) A GET request returns: { "product_name": "dummy.fra", "source_products": [ "17b021e7-3d6b-4d29-a80b-895d62710080" ], "uuid": "48c5a344-877e-4e3f-9a4b-2daa136b68fe" } The since ManyToManyFields with a Through Model are read-only, how do I go about to create a product including the link between products? I'd like to send a POST request that follows the same format as the GET response (i.e., a source_products field that lists UUIDs of existing products). -
Django: Returning Json from view and parse value into d3.js
views.py def get_graph(request): # do some stuff # return json nodes & links back to template return render(request, 'anomaly/index.html',{"nodes": nodes, "links": rels}) index.html <script type="text/javascript"> var width = 800, height = 800; var force = d3.layout.force() .charge(-200).linkDistance(30).size([width, height]); var svg = d3.select("#graph").append("svg") .attr("width", "100%").attr("height", "100%") .attr("pointer-events", "all"); d3.json("/anomaly/graphTEST", function(error, graph) { if (error) return; force.nodes(graph.nodes).links(graph.links).start(); var link = svg.selectAll(".link") .data(graph.links).enter() .append("line").attr("class", "link"); var node = svg.selectAll(".node") .data(graph.nodes).enter() .append("circle") .attr("class", function (d) { return "node "+d.label }) .attr("r", 10) .call(force.drag); // html title attribute node.append("title") .text(function (d) { return d.title; }) // force feed algo ticks force.on("tick", function() { link.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); node.attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); }); }); </script> /anomaly/graphTest is the url to call my get_graph method in views.py I couldn't get the json from my method to return into my d3.json function. How can I do that? What I'm trying to do is something similiar to this https://github.com/neo4j-examples/movies-python-bolt to display stuff on a graph using d3.json. Is it because of the python version that is different which causes my application … -
Holoviews and Django - Widgets are not working
I am trying to migrate a Holoviews/Bokeh to a Django app. The code is working just fine with Bokeh server. For django I am converting holoviews DynamicMaps to Bokeh figures using: plot_rm = renderer.get_widget(rmeans, None, position='above').state Then to serve the figure in django: script1, div1 = components(plot_rm) and let Django render the template with these elements in it. in the template I load the following js libraries: <script src="http://cdn.pydata.org/bokeh/release/bokeh-0.12.13.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.13.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-tables-0.12.13.min.js"></script> The figures render correctly but the widgets do not callback into the server to update the figures. It seems to be missing some JS code to close the AJAX loop. What am I missing? -
Must the app folder be inside the django project folder for a Django REST Framework project?
I'm diving through the Django REST framework learning material. I noticed that in the Quickstart page, they recommend to create the app INSIDE the Django project folder (using the dot at the end of the command django-admin.py startproject tutorial .), whereas the Tutorial starts by just creating the normal Django folder structure: the project folder "tutorial", containing the root app "tutorial" folder and the "snippets" app folder. The Quickstart page defends its way of structuring the folders by stating that it's to avoid name clashes. I just don't understand why, if that would be a best practice, the tutorial doesn't start off the same way. Can someone clarify if this odd folder restructuring (like in the Quickstart page) is really necessary? After having finished learning the Django REST framework, I'm going to set up a real project, and I'd like to know if I can stick to the normal folder structures that I'm used to in Django projects that don't use the Django REST Framework, or not. Kind regards. -
Queryset select latest record for group
Using Django 1.65 Python 3.4.1 Oracle db Table in the db 'Locations': location | update_time | num_01 | num_02 | num_03 | -----------+-----------------+-----------+--------+-------- B | 06 Feb 18 04:14 | 42 | 43 | 55 C | 22 Feb 17 04:14 | 77 | 99 | 23 A | 05 Feb 18 04:14 | 48 | 43 | 21 A | 01 Feb 18 04:14 | 82 | 83 | 74 I would like to select the row with the latest update_time for each location. The results for the above table should be: location | update_time | num_01 | num_02 | num_03 | -----------+-----------------+-----------+--------+-------- A | 05 Feb 18 04:14 | 48 | 43 | 21 B | 06 Feb 18 04:14 | 42 | 43 | 55 C | 22 Feb 17 04:14 | 77 | 99 | 23 I can use a queryset to return the latest update time for each location: latest_updates = Locations.objects.values('location').annotate(max_date=Max('update_time')).order_by('location') but this only returns the location and max update_time when I'm looking for the entire row - num_01, num_02, num_03. I've spent a lot of time searching stackoverflow but nothing quite fits. Oracle doesn't seem to support a sort by and distinct option … -
Django-taggit kwargs understanding
I'm using-django taggit and it works fine. But there are need to make some changes to extend DetailView url and after them TagListView chushed with 404 error. So i'm undestand that problem with kwargs in get_absolute_url function, but i can't understand how to fix it. So, work fine: models.py def get_absolute_url(self): return reverse("posts:detail", kwargs={"slug": self.slug}) urls.py: url(r'^(?P<slug>[\w-]+)/$', Detail.as_view(), name='detail'), url(r'^tag/(?P<slug>[\w-]+)/$', TagListView.as_view(), name='tagged'), views.py: class TagListView(ListView): template_name = "posts/postlist.html" paginate_by = "3" def get_queryset(self): return Post.objects.filter(tags__slug=self.kwargs.get("slug")).all() def get_context_data(self, **kwargs): context = super(TagListView, self).get_context_data(**kwargs) context["tag"] = self.kwargs.get("slug") return context And when I add "category": self.category to get_absolute_url and urls it crush: models.py: def get_absolute_url(self): return reverse("posts:detail", kwargs={"category": self.category, "slug": self.slug}) urls.py: url(r'^(?P<category>[\w-]+)/(?P<slug>[\w-]+)/$', Detail.as_view(), name='detail'), url(r'^tag/(?P<slug>[\w-]+)/$', TagListView.as_view(), name='tagged'), I suppose that there shoulb be changes in get_context_data func, but can't see what exactly. Any ideas or advices please? -
Django auth_view redirecting me in the admin panel instead to html file
I'am creating a login, registration and change password panel in Django. Everything is going ok, but I don't know why Django redirecting me in the Admin Panel when I click 'logout' and 'password change'. I've create the html files for this, and I don't want to use a admin panel. My code: urls.py from django.urls import path from django.contrib.auth import views as auth_views from konto.views import dashboard urlpatterns =[ path('login/', auth_views.login, name='login'), path('logout/', auth_views.logout, name='logout'), path('logout-then-login/', auth_views.logout_then_login, name='logout_then_login'), path('password-change/', auth_views.password_change, name='password_change'), path('password-change-done/', auth_views.password_change_done, name='password_change_done'), path('', dashboard, name='dashboard'), ] views.py from django.shortcuts import render from django.contrib.auth import authenticate, login from .forms import LoginForm from django.http import HttpResponse from django.contrib.auth.decorators import login_required def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['username'], password=cd['password']) if user is not None: if user.is_active: login(request,user) return HttpResponse ('Uwierzytelnianie zakończyło się sukcesem') else: return HttpResponse ('Konto jest zablokowane') else: return HttpResponse('Podano nieprawidłowe dane logowania') else: form = LoginForm() return render(request, 'konto/login.html', {'form': form}) @login_required def dashboard(request): return render(request, 'konto/dashboard.html', {'section': dashboard}) dashboard.html <!DOCTYPE html> <html> <head> <title>Panel główny</title> </head> <body> <h1>Witaj</h1> {% if request.user.is_authenticated %} Witaj, {{ request.user.username}} <a href="{% url 'password_change' %}">Zmiana hasła</a> | <a href="{% url 'logout' %}">Wyloguj</a> … -
Python geocoding name 'latitude' is not defined
I'm a new in django. I want to bulid a webapp to search map by address.(Geocoding) My code shows it has name error at/map/. I dont know the reason. Thanks for kindly reply. from django.shortcuts import render import urllib from urllib.request import urlopen import json def searchMap(request): if request.method == "POST": global latitude global longitude city_name = request.POST.get('address') city_name_Url="https://maps.googleapis.com/maps/api/geocode/json? address"+city_name city_name_Url_Quote=urllib.parse.quote(city_name_Url,':?=/') response=urlopen(city_name_Url_Quote).read().decode('utf-8') response_json = json.loads(response) latitude = response_json.get('results')[0]['geometry']['location']['lat'] longitude = api_response_dict('results')[0]['geometry']['location']['lng'] return render(request,'WebPage1.html',{'Latitude':latitude,'Longitude':longitude}) -
Url pattern for retrieving object with hash as primary key
I have objects that contains metadata about a file. I want to implement a retrive based on the primary key, which is the md5 hash of the file. I am a little rusty on my regex, so how one could implement the urlpattern for this retrive? -
How to get filtered Django ORM query result in Django rest framework response
My question is about getting Django query result in Django-rest-framework api's response. I have the following models of Product, Attribute and Productoptions in my Django project: class Product(models.Model): productid = models.AutoField(db_column='productId', primary_key=True) productname = models.CharField(db_column='productName', max_length=200) class Attribute(models.Model): attributeid = models.AutoField(db_column='attributeId', primary_key=True) attributename = models.CharField(db_column='attributeName', max_length=200, blank=True, null=True) class Productoptions(models.Model): optionsid = models.AutoField(db_column='OptionsId', primary_key=True) optionproductid = models.ForeignKey(Product, models.DO_NOTHING, db_column='optionProductId', blank=True, null=True) optionattributeid = models.ForeignKey(Attribute, models.DO_NOTHING, db_column='optionAttributeId', blank=True, null=True) I have filled sample data in all three tables and when trying to get the products whose attribute name is nike, the following Django query perfectly worked in Python shell. Productoptions.objects.filter(optionattributeid__attributename='nike').values('optionproductid__productname') Get the result <QuerySet [{'optionproductid__productname': 'nike shirt'}, {'optionproductid__productname': 'nike tracksuit'}]> But the related model class query is not working in my view class ProductOptionsView(APIView): serializer_class = ProductOptionsSerializer def get(self,request): filteredproduct = Productoptions.objects.filter(optionattributeid__attributename='nike').values('optionproductid__productname') serializer = self.serializer_class(queryset, many=True) return Response(serializer.data) I am not getting the desired result from this view. Is there any way that all Django query will simply provide result with Django-rest-framework. All get and post queries are perfectly working in Python shell. Is there any other way or DRF has its own method for it to use nested models result in rest api. I have read Django Filter too but … -
django, how to mapping no other address, but just domain?
myproject/urls.py urlpatterns = [ url(r'^$', include('website-app.urls', namespace='website')), ] website-app/urls.py urlpatterns = [ url(r'^$', views.somedef, name='somename') ] I want to connect url domain.com/ to views.somedef which is not in myproject. What domain.com/ means is just domain and end of address with /. It is with No other parameters. domain.com/other/parameters/ has other parameters (other/parameters/), so it is not what I want. If I run django with that above code, django says ?: (urls.W001) Your URL pattern '^$' uses include with a regex ending with a '$'. Remove the dollar from the regex to avoid problems including URLs. Is there any good way to use url domain.com/ in website-app/urls.py , Not in myproject/urls.py? -
How to register a function in template tags in Django?
I want to keep a function without arguments in template tags in django and to be able to call it in a template. Example of the function: def my_count(): return models.MyModel.objects.count() Example of the template: Count: {{ my_count }} How should I define the function my_count in my template? -
Save OneToManyRelationship based on url input in Django
I have two database which are OneToManyRelationship as shown below. I am preparing interface for Data to be uploaded. I want to specify the project attribute in Data model by inputting the url of the Project path like http://project/13. Does anyone know how I can construct the relationship from url input of parent data? Models.py class Project(models.Model): project = models.CharField(max_length=50, blank=True) version = models.IntegerField(default=0) class Data(models.Model): project=models.ForeignKey(project) csv=models.FileField(upload_to=dir_path)