Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to return a specific response from DRF Serializer?
If you look at the try/except block under is_valid() method, I'm trying to check if an object exists and if so, return a 202 error. My question is can I directly return a a response from the serializer or do I need to raise a specific exception and then handle the exception in the views? class CreateJobSerializer(GenericSerializer): class Meta: model = Job fields = ('name',) validators = [] def is_valid(self, raise_exception=False): if hasattr(self, 'initial_data'): super(CreateJobSerializer, self).clean_ids() try: Job.objects.get(name=self.initial_data['name']) return Response(serializer.errors, status=status.HTTP_202_ACCEPTED) except: return super().is_valid(raise_exception) -
Django_Tables Adding a new custom column not found in model
I have the following table: class TaskTable(tables.Table): def render_foo(self): raise Exception() class Meta: model = Task fields = ['foo'] for the following model: class Task(models.Model): priority = models.PositiveIntegerField() title = models.CharField(max_length=1024) content = models.TextField(null=True, blank=True) According to the docs, render_foo won't be executed if it is considered an empty value. My requirement is that foo is not found in the Model. How can I implement the column foo? -
Django Rest Framework use of `permissions.IsAuthenticated` rises an erro
I have a ModelViewSet and I want it to be accessed only by authenticated users, so I added the permission_classes = (permissions.IsAuthenticated), but I get an error: TypeError at /es/general/countries/ 'type' object is not iterable This is the ViewSet: class CountryViewSet(viewsets.ModelViewSet): permission_classes = (permissions.IsAuthenticated) queryset = models.Country.objects.all() serializer_class = serializers.CountrySerializer If I remove the IsAuthenticated assignment line, the ViewSet works, but with it, I get the error. I'll appreciate your help. -
WSGI reverse error that I can figure out
I have a django project and for the past 4 hours i have been trying to figure out why I am getting this message and how to fix it. Idk if it is a simple issue I cant see or if there is something i need to change. error: NoReverseMatch at /login/ Reverse for '<WSGIRequest: GET '/login/'>' not found. '<WSGIRequest: GET '/login/'>' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/login/ Django Version: 2.0.5 Exception Type: NoReverseMatch Exception Value: Reverse for '<WSGIRequest: GET '/login/'>' not found. '<WSGIRequest: GET '/login/'>' is not a valid view function or pattern name. Exception Location: /Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 632 here is my views.py file: def user_home(request): if not request.user.is_authenticated: return redirect('user_login') else: return render(request, 'users/home.html') def user_login(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data username = cd['username'] password = cd['password'] user = is_authenticated(username=username, password=password) if user: login(request, users) return redirect('user_home') else: form = LoginForm() error = 'Username/Password dont match' parameters = { 'form':form, 'error':error, } return redirect(request, 'users/login.html', parameters) else: form = LoginForm() parameters = { 'form':form, } return redirect(request, 'users/login.html', parameters) Here is the urls.py file: from django.conf.urls import url from . … -
django-facebook api No module named 'django.conf.urls.defaults'
I installed django_facebook (django-facebook==6.0.3). I am using Django 1.11. I got an error: File "path/lib/python3.5/site-packages/django_facebook/urls.py", line 4, in <module> from django.conf.urls.defaults import patterns, url ImportError: No module named 'django.conf.urls.defaults' I was tring solved this problem with: try: from django.conf.urls import include, url except ImportError: from django.conf.urls.defaults import include, url but without success. Please for hint. -
Creating a password field for a custom user model in Django
In my project, I have 2 types of users. One of them is being modeled using the default Django User model, however, the other one needs to be totally custom. I do not want to extend the default one because these are very different use cases. Anyway, so far I am trying to do it this way: class CustomUser(models.Model): ... password = models.CharField(_('password'), max_length=128) ... def set_password(self, raw_password): import random algo = 'sha1' salt = get_hexdigest(algo, str(random.random()),str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw_password) self.password = '%s$%s$%s' % (algo, salt, hsh) This is of course based on the one used by Django. Now, I get what is going on. We don't really save the password, but we get the password and we use an algorithm to turn it into a weird string and save that string instead. I want to create a login view for my CustomUser. Lets say, one of my CustomUsers uses the username=admin, password=MyPassword23 to login, how can I take the string 'MyPassword23' and turn that into the weird string so I can match it and return the user? Is this actually the way these things are done? Or am I completely off the standard with my approach? Thanks … -
Nginx Is Displaying a 502 Bad Gateway Error Instead of the Django Application
I am trying to follow this tutorial (https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-16-04#setting-up-the-uwsgi-application-server) for deploying a django server but somehow I keep on getting 502 gateway error and I checked that the .sock file is not created though. I checked permission, I believe I set them right already but no luck. I have my project git cloned right under the root folder so when I type pwd it shows /root/wxr/wxr for this file /etc/uwsgi/sites/wxr.init I have [uwsgi] project = wxr base =/root chdir = %(base)/%(project)/%(project) home = %(base)/%(project)/%(project) module = main.wsgi:application master = true processes = 5 socket = /run/uwsgi/%(project).sock chmod-socket = 660 vacuum = true req-logger = file:/tmp/reqlog logger = file:/tmp/errlog as for /etc/systemd/system/uwsgi.service, I have [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown www-data:www-data /run/uwsgi' # at one point, I tried root:www-data ExecStart=/usr/local/bin/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target as for my site-available file server { listen 80 default_server; listen [::]:80 default_server; # root /var/www/html; # Add index.php to the list if you are using PHP # index index.html index.htm index.nginx-debian.html; server_name _; location = /favicon.ico { access_log off; log_not_found off; } location /media { root /root/wxr/wxr/mediafiles; } location /static/ { root /root/wxr/wxr/static; } location / { include … -
How to use Simple Query String Query in Django Elasticsearch-dsl python?
I am unable to find any documentation regarding how do i implement Simple Query String Query in my Django Elasticsearch-dsl https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-simple-query-string-query.html Can someone guide me through it ? This is my search function. def search(q_string): client = Elasticsearch( [ 'elasticsearch' ] ) s = Search(using=client).query(SimpleQueryString(q_string)) Above code is showing me paring error. -
django using jinja and render_to_response
I am trying to have my view load index.html and then once the document is ready another view gets called to render the template values to index.html using the django render_to_response function. However, I keep getting errors saying ImportError: No module named ' django' when trying to import django.shortcuts.render_to_response Is render_to_response specific only to the django template enjine? Here is how I am trying to call the HTTPResponse function and render_to_response function def index(request): env = Environment(loader=FileSystemLoader('templates')) template = env.get_template('index.html') elif request.method == "POST" and request.POST.get("type", "") == "ajax": return ajax(request) return HttpResponse(template.render()) def ajax(request): template_values = {'popular_stocks': []} popular = fetcher.get_tops() for instrument in popular: r = requests.get('https://api.iextrading.com/1.0/stock/%s/quote' % (instrument['symbol'])) quote = json.loads(r.content.decode('utf-8')) template_values['popular_stocks'].append(quote) return render_to_response('index.html', template_values) -
How can get Django Search Autocomplete working with Jquery? Search Engine is Solr with django-haystack
I have been trying to get search suggestion/auto complete working in my web application and unable to get it working. Below is the full snaps of my code. I have main search box on my home page and i need to auto complete for my post titles in this search area. Below code is used. I have been trying since last 3 days without success :( . PLease advice whats wrong with my code. home.html {% load staticfiles %} {% load crispy_forms_tags %} <!DOCTYPE <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script> <!-- jQuery UI !--> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> </head> <div class="bgimg"> {% include 'rincon/nav.html' %} <div class="search-unit"> <form role="search" class="search" data-search="" action="." accept-charset="UTF-8" method="get"> <!-- {{ form.as_table }} --> <!-- <input name="utf8" value="✓" type="hidden"> --> <label for ="query"></label> <input name="query" id = "query" placeholder="Search" aria-label="Search" type="text" input name="commit" type="submit" <button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button> </div> </form> </div> </div> <script> $(function() { $("#query").autocomplete({ source: "{% url 'rincon:autocomplete' %}", select: function (event, ui) { //item selected AutoCompleteSelectHandler(event, ui) }, minLength: 2, }); }); function AutoCompleteSelectHandler(event, ui) { var selectedObj = ui.item; } </script> {% block content %} <div class="body"> <div class="welcome_title"> {% if not user.is_authenticated %} <div class="suggested-login" style="font-weight:normal; … -
How to return custom status code via DRF?
If a user sends a POST request to create a job, but that job already exists - I am trying to return a 202. Instead, it is returning a 400.. views def post(self, request, format=None): serializer = CreateJobSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer class CreateJobSerializer(GenericSerializer): class Meta: model = Job fields = ('name') def create(self, validated_data): try: obj = Job.objects.create(**validated_data) return obj except: return Response(serializer.errors, status=status.HTTP_202_ACCEPTED) I assume that Job.objects.create will fail if unique=true is violated on that model, if that is the case I would expect a 202 to be returned. What am I doing wrong? Is it because the unique=true error is actually being caught during validation so create() is never actually called? -
Getting CSRF token missing or incorrect for one route but not the other
Working on React/Django and have run into an issue I can't resolve. On the front end, there is the following JS sending data to the Django API. In this case, rejectedDocuemts() is sending an array of filenames to the backend so eventually an email can be created and sent to the admin to review. Files that don't match an approved list of extensions make it on this list. This is where the error occurs. The submitDocuments is where files that meet the approved list of file extensions are submitted. The entire files object is sent to the server to be saved. This one is working perfectly fine. export function rejectedDocuments(filenames, id) { return function (dispatch) { axios.post( `${URL}/api/${(id)}/documents/upload/error`, filenames, { headers: { 'content-type': 'text/plain', 'Authorization': 'JWT ' + sessionStorage.getItem('token') } } ) } } // Creates the error state to be used in components export function submitDocuments(files, id) { return function (dispatch) { const uploaders = _.map(files, f => { const formData = new FormData(); formData.append('file', f); return axios.post( `${URL}/api/${(id)}/documents/upload/success`, formData, { headers: { 'content-type': 'multipart/form-data', 'Authorization': 'JWT ' + sessionStorage.getItem('token') } } ) }); axios.all(uploaders) .then(response => { dispatch({ type: SUBMIT, payload: response[0].status }); }) } } The rejectedDocuments … -
bootstrap 4 modal open works on localhost with ng serve. But not on heroku with ng build django
All text as it is best to describe the problem this way. I have an angular 5 app. When I run the app locally by using ng serve a button I use to open a modal works. When I use ng build take the dist folder and add it to the static files of a django instance then load it to a heroku instance the button does not work. I am using ng build not ng build -prod which I am trying now. the bootstrap is being imported by using the script imports on the index.html head files. What could be the issue. -
repr vs str in python classes - both are given
I have read and understood the difference between repr and str and noted the difference. repr - unambigous str - readable What happens is both is used? I wrote a simple class and found that repr is called when both are given. class test(): def __repr__(self): return 'repr called' def __str__(self): return 'str called' x = test() print x Now, when I check the implementation of both the classes in Django ValidationError, Im not sure when str will be called as the repr function is already overloaded. https://docs.djangoproject.com/en/2.0/_modules/django/core/exceptions/#ValidationError def __str__(self): # print 'validationerror str' if hasattr(self, 'error_dict'): return repr(dict(self)) return repr(list(self)) def __repr__(self): # print 'validationerror repr' return 'ValidationError(%s)' % self How and when the __str__ function will be called? -
can't run my server because of mysql errors
I am doing a project in django and when i run my server python manage.py runserver i get the following errors. Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x1045406a8> Traceback (most recent call last): File "/Users/x/Desktop/bakeinsta/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/Users/x/Desktop/bakeinsta/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/Users/x/Desktop/bakeinsta/env/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 236, in get_new_connection return Database.connect(**conn_params) File "/Users/x/Desktop/bakeinsta/env/lib/python3.6/site-packages/MySQLdb/__init__.py", line 86, in Connect return Connection(*args, **kwargs) File "/Users/x/Desktop/bakeinsta/env/lib/python3.6/site-packages/MySQLdb/connections.py", line 204, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (61)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/x/Desktop/bakeinsta/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/x/Desktop/bakeinsta/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/Users/x/Desktop/bakeinsta/env/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Users/x/Desktop/bakeinsta/env/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Users/x/Desktop/bakeinsta/env/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/Users/x/Desktop/bakeinsta/env/lib/python3.6/site-packages/django/core/checks/model_checks.py", line 27, in check_all_models errors.extend(model.check(**kwargs)) File "/Users/x/Desktop/bakeinsta/env/lib/python3.6/site-packages/django/db/models/base.py", line 1200, in check errors.extend(cls._check_fields(**kwargs)) File "/Users/x/Desktop/bakeinsta/env/lib/python3.6/site-packages/django/db/models/base.py", line 1272, in _check_fields errors.extend(field.check(**kwargs)) File "/Users/x/Desktop/bakeinsta/env/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 894, in check errors = super().check(**kwargs) File "/Users/x/Desktop/bakeinsta/env/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 206, in check errors.extend(self._check_backend_specific_checks(**kwargs)) File "/Users/x/Desktop/bakeinsta/env/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 303, in _check_backend_specific_checks return connections[db].validation.check_field(self, **kwargs) File "/Users/x/Desktop/bakeinsta/env/lib/python3.6/site-packages/django/db/backends/base/validation.py", line 21, in check_field field_type = … -
Django javascript cannot be loaded after doing changes
Guys Currently, I am doing the Django website development Django version: 1.11.13 I added static folder in each app. and DEBUG = True in the settings.py the static files(javascript and css) can be found, but when I changed/added content in css, it can be reloaded. but the javascript cannot. what I did are: <script src="{% static 'assets/js/dashboard.js' %}?{% cache_bust %}" type="text/javascript"></script> cache_bust is templatetags which will add uuid at the end of js link. it does not work for the reloading of javascript in the browser. I chose the all time to clear the cache in the browser. it does not work for the reloading of javascript in the browser. python manage.py collectstatic, it still does not work only I can do was create another js file, this change can be detected by the browser. I do not think it makes sense. do you have this same issue, and how to figure it out? any suggestion? thanks. -
Bulk create in related objects
I have 2 models in my app - In models/parent.py I have - from django.db import models class Parent(models.Model): class Meta: db_table = "parent_table" start_date = models.DateField() end_date = models.DateField() In models/child.py I have - from django.db import models from models.parent import Parent class Child(models.Model): class Meta: db_table = "child_table" some_ref = models.ForeignField(Parent) We can do single insert into child table using the parent table reference as - self.child_set.create(**args) Is there a way by which we can do bulk insert into related table, as the normal bulk_create -
Django Make dynamic delete Function
I have a views.py file like this def delete_post(request): id = request.GET.get('id') post = models.Post.objects.get(id=id) return render(request, 'system/ajax/delete.html', {'post': post}) class PostDelete(DeleteView): model = models.Post success_url = reverse_lazy("system:post_list") and my urls.py file looks like: url(r'^post-list/$',views.PostList.as_view(),name='post_list'), url(r'^post-delete/(?P<pk>\d+)/$',views.PostDelete.as_view(),name='post_delete'), url(r'^ajax/delete/$',views.delete_data,name='ajax_delete_data'), my delete.html look like this: <form method="post" action="{% url 'delete_post' pk=data.pk %}"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="delete"> </form> my post_list.html is the following: <button data-id="{{post.id}}" data-url="{% url 'system:ajax_delete_data' %}" type="button" class="delete-post" > delete </button> <script> $(document).on('click','.delete-post',function(){ var url = $(this).data('url'); var id = $(this).data('id'); $.ajax({ url:url, data:{ 'id':id, }, success:function(data){ $('#delete-data').html(data); }, }); }); </script> in my script its only can delete one data model called post, I want to make it dynamic, so I don't need to write many functions. on this post = models.Post.objects.get(id=id) <--- any have a suggestion? -
Cannot read property 'toString' of null using jstree and django
sorry for bother you guys I'm trying jstree and django-restframework to solve my problem with multi select, but I'm getting this error Cannot read property 'toString' of null but when I remove id from my serializer it show all the items but not as a tree. thanks in advance this is my model class ApplicationArea(models.Model): title = models.CharField(verbose_name="Nome da Área de conhecimento", max_length=255, blank=True, null=True) text = models.CharField(verbose_name="Descrição da Área de conhecimento" ,max_length=255, blank=True, null=True) level = models.TextField(verbose_name="Nível") created = models.DateTimeField(auto_now_add=True) code = models.CharField(verbose_name="Código", max_length=255, null=True) parent = models.ForeignKey('self', null=True, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'Application Area' def __str__(self): return self.text my serializer class ApplicationAreaSerializer(serializers.ModelSerializer): class Meta: model = models.ApplicationArea fields = ('id','parent', 'text') and my template {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <div class="row"> <div class="card"> <div class="card-body"> <h2 class="text-center card-title">Informações Gerais</h2> <form method="post" enctype="multipart/form-data" novalidate> {{form|crispy}} <input class="btn btn-primary btn-block" type="submit" value="Update" /> </form> </div> <div class="card-footer"> <div id="tree"></div> </div> </div> </div> </div> <script> var application_area = "/api/application-area/" var cnpq = "/api/cnpq/" $.getJSON(application_area, function(area){ try{ createJSTree(area); }catch(ex){ console.log(ex) } }); function createJSTree(area) { if(area.parent == null || area.parent == undefined){ area.parent = '#' } $('#tree').jstree({ 'core': { "multiple": true, "themes": … -
python 3.4 mod_wsgi error installing
I'm having a heck of a time trying to install mod_wsgi for apache 2.4 / python 3.4 right now. I've been looking at some other answers but don't seem to be helping. I set up a virtual environment and attempted: pip install mod_wsgi to start the process, but I keep getting an error: Failed building wheel for mod-wsgi building 'mod_wsgi.server.mod_wsgi' extension error: Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows SDK 7.1": www.microsoft.com/download/details.aspx?id=8279 Some people mentioned the easiest remedy is to install the visual studio community edition, but I already have Visual Studio 2017 installed. I also checked my installations and I have the Microsoft Visual C++ 2010 x64 and x86 Redistirbutables installed. -
Can't save related objects in django models using pre_save signal
I have to implement multi-aspect type of inheritance from UML in Django ORM. I have Contract data type which depending on type of customer (regular or business customer) can be classified as RegularContract or BusinessContract. Also contract can have expiration date or be non-expirable (it is not specified how long it will be valid), so it also can be of type ExpiringContract or NonExpiringContract. This is how concept diagram looks: And this is how I've implemented this: models.py code: class Contract(models.Model): approval_date = models.DateTimeField(null=False) def __getattr__(self, item): if self.expiringcontract: return getattr(self.expiringcontract, item) elif self.nonexpiringcontract: return getattr(self.nonexpiringcontract, item) class ContractExpirationExtension(models.Model): base = models.OneToOneField("website.Contract", on_delete=models.CASCADE) class Meta: abstract = True class ExpiringContract(ContractExpirationExtension): termination_date = models.DateTimeField() @property def duration(self): return self.termination_date - self.base.approval_date class NonExpiringContract(ContractExpirationExtension): @property def duration(self): return timedelta(days=100) class ContractTypeExtension(models.Model): base = models.OneToOneField("website.Contract", on_delete=models.CASCADE) termination_delay = models.PositiveSmallIntegerField(default=30) class Meta: abstract = True @classmethod def create(cls, approval_date, contract_expiration_type, termination_delay, **kwargs): type_extension = cls(termination_delay=termination_delay) base = Contract(approval_date=approval_date) expiration_type = contract_expiration_type(**kwargs) expiration_type.base = base type_extension.base = base if contract_expiration_type.__name__ == ExpiringContract.__name__: type_extension.base.expiringcontract = expiration_type elif contract_expiration_type.__name__ == NonExpiringContract.__name__: type_extension.base.nonexpiringcontract = expiration_type return type_extension def __getattr__(self, item): if self.base: return getattr(self.base,item) class RegularContract(ContractTypeExtension): termination_delay = models.PositiveSmallIntegerField(validators=[validate_term_delay_regular], blank=False) class BusinessContract(ContractTypeExtension): termination_delay = models.PositiveSmallIntegerField(validators=[validate_term_delay_business], blank=False) When we … -
Update database view structure in Django
I changed a database view from DateField to DateTimeField but when I run ./manage.py makemigrations it says "No changes detected" Any ideas on how to do properly update my database view? -
Split Django queryset into a many sublists based on a given field
I have the following model: class Game(models.Model): users = models.ManyToManyField(User, through='Membership', related_name='users') date_game = models.DateField(default=datetime.date.today) class Membership(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_('joueur')) game = models.ForeignKey(Game, on_delete=models.CASCADE) score = models.IntegerField(_('score'), default=0, validators=[ MaxValueValidator(50), MinValueValidator(0) ]) I also have this ListView, which aims at retrieving all the Membership object associated with a Game played by a given User: class GameListView(ListView): model = webapp_models.Membership template_name = 'list_games.html' form = webapp_forms.UserChoiceField def get_queryset(self): if self.request.method == 'GET': form = self.form(self.request.GET) if form.is_valid(): user = form.cleaned_data['user_choice_field'] # all games played by the user tmp = Game.objects.filter(membership__user=user) # all memberships associated to games played by the user out = Membership.objects.filter(game__in=tmp) for obj in out: print(obj.game.date_game, obj.game.id, obj.user.username, obj.score) return out return Membership.objects.all() def get_context_data(self, *args, object_list=None, **kwargs): context = super(GameListView, self).get_context_data(*args, object_list=None, **kwargs) # use the GET data to avoid resetting the form context['form'] = self.form(self.request.GET) return context I thus would like to split out (queryset of Membership) into sublists to gather all the Membership matching the same Game. Ideally, I would do this in the view rather than in the template. -
event loop error with django and asyncio
I have a management command that starts an asyncio loop, but when i call django runserver, i get: RuntimeError: There is no current event loop in thread 'Dummy-1'. (this is on initializaton of my library) Why is django initializing on a dummy thread? Is there a correct way to mix django and asyncio? How can I use await with a django database call? -
Error during template rendering: cache issue in django
I'm running django on my local machine for development, within a docker instance. However, frequently I run into errors of this kind: Error during template rendering "so-and-so" is not a valid view function or pattern name. This happens when I add a new line to my urls.py file, like so: path('test', views.test, name='test') If I then create a link using {% url 'app:test' %} then I will get the error mentioned above. However, the odd thing is that this is not a valid error. It only seems to appear due to some sort of a caching problem. I write the url name correctly, it's all in place, but the system acts as if the URL was not defined. When I restart Django, then it works just fine! Clearly I don't want to be restarting Django all the time. Any idea what could cause this? I have no special cache settings whatsoever in settings.py.