Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert django form data into pdf?
I have a form that takes user request for what kind of service they are looking for and when the users click submit, I want the form data to get converted into a pdf file. And also I want that pdf to be sent to my email. How can I achieve this? Code sample is highly appreciated. Thanks in advance. -
delete and update method not workin in not django rest framework
I am trying to build an API using DRF, get() and post() method is working fine but the delete and update methods are not working. I am getting this error, can anyone please help me to rectify this error is coming. TypeError: delete() missing 1 required positional argument: 'pk' views.py file class MenuList(APIView): def get(self, request): menu = Menu.objects.all() serializer = MenuSerializer(menu, many=True) return Response(serializer.data) def post(self, request): serializer = MenuSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk): menu = self.get_object(pk) menu.delete() return Response(status=status.HTTP_204_NO_CONTENT) class MenuDetail(APIView): """ Retrieve, update or delete a Menu instance.""" def get_object(self,pk): try: return Menu.objects.get(pk=pk) except Menu.DoesNotExist: raise Http404 def get(self, request,pk): menu = self.get_object(pk) menu = MenuSerializer(menu) return Response(menu.data) def put(self, request, pk): menu = self.get_object(pk) serializer = MenuSerializer(menu, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_404_BAD_REQUEST) def delete(self, request, pk): menu = self.get_object(pk) menu.delete() return Response(status=status.HTTP_204_NO_CONTENT) class MenuItemList(APIView): def get(self, request): menuitem = MenuItem.objects.all() serializer = MenuItemSerializer(menuitem, many=True) return Response(serializer.data) def post(self, request): serializer = MenuItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk): menuitem = self.get_object(pk) menuitem.delete() return Response(status=status.HTTP_204_NO_CONTENT) class MenuItemDetail(APIView): def get_object(self,pk): try: return MenuItem.objects.get(pk=pk) except MenuItem.DoesNotExist: raise Http404 def … -
Django template rendering does not display my data
I just can't solve my problem, don't see where/what do i wrong. Here is my model class Account(models.Model): uuid = ShortUUIDField(unique=True) name = models.CharField(max_length=80) desc = models.TextField(blank=True) address_one = models.CharField(max_length=100) address_two = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=50) state = models.CharField(max_length=2) phone = models.CharField(max_length=20) owner = models.ForeignKey(User, on_delete=models.DO_NOTHING,) created_on = models.DateField(auto_now_add=True) Here is my view class AccountList(ListView): model = Account @login_required() def account_detail(request, uuid): account = Account.objects.get(uuid=uuid) if account.owner != request.user: return HttpResponseForbidden() variables = { 'account': account, } return render(request, 'accounts/account_detail.html', variables) Im tried to render it in my accaunt_detail template with following code: {% extends 'base.html' %} {% block content %} <div id="content-container" class="container p-none"> <div id="ad-container"> <div id="gi-container" class="ad-container"> <div class="row gi-body"> <div class="col-md-9"> <h5 class="gi-sh">Description</h5> <p>{{ account.desc }}</p> </div> <div class="col-md-3"> <h5 class="gi-sh">Address</h5> <p class="nm">{{ account.address_one }}</p> <p class="nm">{{ account.address_two }}</p> <p class="nm">{{ account.city}}, {{ account.state }}</p> <p class="nm">{{ account.phone}}</p> </div> </div> </div> </div> {# List Contacts #} {# List Communications #} </div> {% endblock %} But i get just empty Page. I do not get any errors, like everything works fine but the user details are not displayed. I have created ~15 users, so i have users in my database. -
Persistence issues with checkboxes
My Goal Is to create a shopping webpage where users can filter through the product selection by checking checkboxes. Instead of having a "submit" button I wanted the page to submit as soon as the user checked the checkbox. Example: the "refine by" section on Amazon. My Solution The best way would have been to use AJAX however I opted for a simple javascript / jquery function instead: $(":checkbox").change(function () { $('#product-filters').submit() }); Clicking the checkbox would correctly refresh page and apply filters, however the checkbox would appear un-checked to the user. So in Django I implemented following workaround: filters = request.GET.getlist('filters', None) selected_filters = [] try: for f in filters: selected_filters.append(int(f)) except TypeError: selected_filters = None return { # ..... 'selected_filters': selected_filters, } And then in my template: <input {% if filter.id in selected_filters %}checked="checked"{% endif %} ... all my other attrs></input> My Issue While all of the above works correctly I now have the issue that if a user clicks on a checked checkbox in order to uncheck it, it will simply refresh the page and keep it checked, with that filter applied. How should I go about fixing this? -
Converting a table from html file to pdf using xhtml2pdf
Hi guys I am having a problem using xhtml2pdf. I am following a tutorial and it worked (note: the data in the tutorial is hardcoded). So I change a bit of the code from the tutorial so I can fetch data from a database using django-rest-framework. When I run the project there were no errors but I typed the url to see my pdf file, its error 404. here is my views.py class GeneratePdf(ReadOnlyModelViewSet): queryset = DirectoryTb.objects.all() serializer_class = DirectoryTbSerializer def get(self, request, queryset, *args, **kwargs): pdf = render_to_pdf('directory.html', queryset) return HttpResponse(pdf, content_type='application/pdf') here is my urls.py router = DefaultRouter() router.register(r'^pdf', GeneratePdf) urlpatterns = router.urls -
Vue.js in Django Templates
I am trying to use Vue.js in Django templates. One such template is the following: {% load static %} <!DOCTYPE html> <html> <head> </head> <body> <div id="myApp"> <span>Hello [[ message ]]</span> <div id="map"></map> </div> <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> <script src="https://v1.vuejs.org/js/vue.js"></script> <script src="{% static 'js/script.js' %}"></script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC62HW0L7DIhL7oLbWvCEekHOkPWdxBPwk&callback=initMap"></script> </body> </html> I changed Vue's interpolation delimiters to [[ ]] to avoid conflict with Django. My script.js looks as follows: $(function() { var app = new Vue({ el: '#myApp', delimiters: ['[[', ']]'], data: { message: 'Hello, world!' } }); }); Unfortunately, the HTML rendered contains [[ message ]]. Has anyone else faced a similar issue? -
Django, How to avoid 'matching query does not exist'
views.py try: testmodel2 = TestModel_2.objects.get(description='a') except TestModel_2.DoesNotExist: testmodel2 = None models.py @python_2_unicode_compatible class TestModel_2(models.Model): description = models.CharField(max_length=34) created = models.DateTimeField(auto_now_add=True) def __str__(self): return "TestModel %s" % self.description Question: Why though I set DoesNotExist, myapp.models.DoesNotExist: TestModel_2 matching query does not exist. is occurred? -
Include keyword in url.py not working without app_name(Django 2.0)
When I try to use the include keyword in url.py to reverse match url in model.py reverse("products:detail", kwargs={"slug": self.slug} it says: Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. I see that in Django 2.0, you have to provide app_name with namespace. As I have created my app with python manage.py startapp products, I thing my app name is products. My url.py: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from .views import hello_world, home_page, about_page, contact_page, login_page, register_page urlpatterns = [ url(r'^hello/$', hello_world), url(r'^$', home_page), url(r'^admin/', admin.site.urls), url(r'^about/$', about_page), url(r'^contact/$', contact_page), url(r'^login/$', login_page), url(r'^register/$', register_page), url(r'^products/', include(products, namespace='products')), ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)` And my products/model.py: import random import os from django.db import models from django.db.models.signals import pre_save, post_save from django.urls import reverse from .utils import unique_slug_generator def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(filepath) return name, ext def upload_image_path(instance, filename): new_filename = random.randint(0, … -
NOT NULL constraint failed error when populating foreign key field
I'm trying to run a script I wrote to move some data from json files into my database, and keep getting the same error. Traceback: Traceback (most recent call last): File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: clan_participant.completed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "participant_updater.py", line 32, in <module> message = participant_updater() File "/home/jamtime/clansite/database_updaters.py", line 548, in participant_updater update_db() File "/home/jamtime/clansite/database_updaters.py", line 512, in update_db character=char_obj File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 653, in create return super(RelatedManager, self.db_manager(db)).create(**kwargs) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/base.py", line 923, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/base.py", line 962, in _do_insert using=using, raw=raw) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/query.py", line 1076, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1107, in execute_sql cursor.execute(sql, params) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) … -
Unaable to install django2 on python
I install ubuntu And use python 3 When i want install django 2 I have an error : no module named 'django' Thankyou for your attention -
ImportError: no module named website.settings
ImportError: module not found When attempting top run a Django project on my virtual enviornment, Give me this error, project works on original computer. -
DJango + nginx + gunicorn: how to stop caching
I am running Django 2.0 using gunicorn on nginx server. All my pages are not reflecting the changes immediately. How to stop caching the below are my files: nginx.conf server { listen 80; server_name sample.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/testapp/testapp_project/test_artciles; } location /media/ { root /home/testapp/testapp_project/test_artciles; } location / { include proxy_params; proxy_pass http://unix:/home/testapp/testapp_project/test_artciles.sock; } } Django settings.py import os from django.contrib import messages BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'ssdjhasjdkhjaskdhkajsdhkjasdhkjh' DEBUG = True ALLOWED_HOSTS = ['xx.xxx.xx.xxx','127.0.0.1'] INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django_extensions', # local apps 'articles', 'fcm_django', 'corsheaders', 'rest_framework', ) MIDDLEWARE = ( 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'webarticles.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.join(BASE_DIR, 'templates')), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'webarticles.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'test.sqlite3'), } } LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ =True AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL … -
Forms are not shown
Forms are not shown.How should I show forms in one url?I wanna make a writing comment&recomment system.I wrote in comment.html {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>COMMENT</title> </head> <body> <div> <h2>{{ object.text }}</h2> </div> <div id="comment-area"> {% for comment in post.comment.all %} <div class="media m-3"> <div class="media-body"> <h5 class="mt-0"> <span class="badge badge-primary badge-pill">{% by_the_time comment.created_at %}</span> {{ comment.name }} <span class="lead text-muted">{{ comment.created_at }}</span> <a href="{% url 'recomment' comment.pk %}"Reply</a> </h5> {{ comment.text | linebreaksbr }} {% for recomment in comment.recomment.all %} <div class="media m-3"> <div class="media-body"> <h5 class="mt-0"> {{ recomment.name }} <span class="lead text-muted">{{ recomment.created_at }}</span> </h5> {{ recomment.text | linebreaksbr }} </div> </div> {% endfor %} </div> </div> {% endfor %} </div> <form action="" method="POST" enctype='multipart/form-data'> {% for field in form %} <div class="form-group"> {{ field.errors }} <label for="{{ field.id_for_label }}"> {{ field.label }} </label> {{ field }} </div> {% endfor %} {% csrf_token %} <input class="btn btn-primary" type="submit" value="comment"> </form> </body> </html> in views.py class DetailView(generic.DetailView): model = POST template_name = 'comment.html' class CommentCreateView(generic.CreateView): model = Comment form_class = CommentCreateForm def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['post_pk'] = self.kwargs['pk'] return context def form_valid(self, form): post_pk = self.kwargs['pk'] self.object = form.save(commit=False) self.object.target = … -
Django 2.0 url() to path()
I am currently learning Django. Until now I was working with Django 1.1 but now I am working with Django 2.0. Django 2.0 uses path() instead of url() and I don't quiet understand that. In Django 1.1 my urls looked like this: url(r'^about/$', views.AboutView.as_view(), name='about'), Now with Django 2 it looks like this path('about/', views.AboutView.as_view(), name='about'), So far so good but I just don't undertand how I can convert this url(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(), name='post_detail'), So that it works with the new version. Just chagning url to path doesn't work, and changing url to re_path doesn't work either. Can someone help me with that Problem? Thanks in advance -
"AttributeError: 'psycopg2' has no attribute '__version__'" when switching from sqlite to postgres with Django - Vagrant
I'm a newbie in Django/Python. I just setup Django successfully with vagrant on my computer. But I want to change the default database from sqlite to postgresql. To do so, I just changed the database part on the setting.py file to : # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.path.join(BASE_DIR, 'db.postgresql'), } } Now whenever I run the command python manage.py runserver 0.0.0.0:8080 (which used to work well), I get the following error : Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fb91ed95ea0> Traceback (most recent call last): File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/ubuntu/.virtualenvs/meshine_api/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module … -
How to upload files to database?
This is my models.py from django.db import models # Create your models here. class Houses(models.Model): owner = models.CharField(max_length=250) house_name = models.CharField(max_length=500) country = models.CharField(max_length=500) genre = models.CharField(max_length=100) thumb = models.ImageField(default="default.png") body = models.TextField(default=None) def __str__(self): return self.house_name class house(models.Model): houses = models.ForeignKey(Houses, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) house_name = models.CharField(max_length=250) this is my views.py from django.shortcuts import render from . models import Houses from django.http import HttpResponse from django.contrib.auth.decorators import login_required from . import forms def houses_list(request): house = Houses.objects.all().order_by('owner') return render(request,'Houses.html',{'houses':house}) def house_detail(request,house_name): #return HttpResponse(house_name) house = Houses.objects.get(house_name=house_name) return render(request, 'detail2.html',{'house':house}) @login_required(login_url = "/accounts/login/") def house_create(request): if request.method =='POST': form = forms.CreateHouses(request.POST,request.FILES) if form.is_valid(): #save house to db instance = form.save() return render(request, 'Houses.html',{'houses':house}) else: form = forms.CreateHouses() return render(request,"house_create.html",{'form':form}) This is my forms.py from django import forms from . import models class CreateHouses(forms.ModelForm): class Meta: model = models.Houses fields = ['owner','house_name','country','genre','thumb','body'] This is my house_create.html file {% extends 'detail.html' %} {% block content %} <div class="create-house"> <h2>Create an Awesome New Article</h2> <form class="site-form" action="{% url 'accounts:login' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <input type="submit" value="Create"> </form> </div> {% endblock %} I created a model that keeps houses list and it have variables like name owner etc.I tried to … -
Where is the generated token in DJANGO stored during password reset
I am trying to access the generated token(in the database table) when I request the "forgotten password" functionality, but I cannot seem to find it. I am using django 1.10, rest_framework, django-rest-auth. I have checked inside authtoken_token as well as inside account_emailconfirmation tables but was unsuccessfully. In github the source code refers to this in python as token_model I think https://github.com/Tivix/django-rest-auth/blob/master/rest_auth/utils.py -
javascript can't do parse dict
I use django and want get a dictionary like this "{'test1' : 1, 'test2' : 2, 'test3' : 3}" but can't do JSON.parse and eval("(" + str + ")") it return a object but i can't use it like dictionary. When i take to variable converted string code is work but the code braked when i try with django variable. Pleas help me how can in get a dictionary in javascript javascript $( document ).ready(function() { var companys = "{{ companysdict }}; var types = "{{ typesdict }}"; companys = eval("(" + companys + ")"); types = eval("(" + types + ")") var key_companys = Object.keys(companys); var key_types = Object.keys(types) companys = Object.values(companys); types = Object.values(types) var html = "" $(".d").append(Object.values(companys)[0]); for (var c = 0; c < key_companys.length; c++) { html += "<li><a href='#'>"+ key_companys[c] +"</a>" html += "<ul>" for (var t = 0; t < key_types.length; t++){ if (Object.values(types)[t] == Object.values(companys)[c]){ html += "<li><a href='#'>" + key_types[t] + "</a></li>" } }; html += "</ul></li>" }; $(".d").append(html); }); Django def main(request): companys = Companys.objects.all() types = Types.objects.all() companysdict = {} typesdict = {} for company in companys: companysdict[company.name] = company.pk for type in types: if type.company.pk == company.pk: typesdict[type.type] … -
able to check db connection host or name (not db name but the setting) ? django
I am not trying to check the db name to the connection, I have multiple database setup in django and also used the database route to create a failover but I am wondering if I can get the name of the connection host or the name given to the settings... for example DATABASES = { 'default': { # get this name 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'euser', 'PASSWORD': 'password', 'HOST': 'host', # get this host name 'PORT': 3306, }, } Is it possible to get those names I commented out above? For my failover, I am trying to send an email if another db is being used, but it would be great if I can get especially the host so it would be easier on me P.S. off topic, is it possible to change the name default to other names? I tried changing it and I would get errors. Seems like I must have at least one database setting name called default Thanks in advance for any help. -
auth_views LoginView does not show inactive user error message
I'm using Django 1.11 and the simple auth_views.LoginView - buildin form for my users to login. Login etc works fine except if the user is inactive it shows: Please enter a correct username and password. Note that both fields may be case-sensitive. even tho that's not the right error. Relevant code: urls.py from django.contrib.auth.views import LoginView app_name = 'accounts' urlpatterns=[ url(r'^login/$',auth_views.login,{'template_name': 'accounts/login.html'},name='login')] login.html <div class="container front_container"> <div class="jumbotron"> <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary">Submit</button> {% endbuttons %} </form> </div> I've read in a different thread that this might be an issue with the django backend recognizing the error, but not outputting it. But I don't know what I need to do to fix it. I've also seen this error been put out in other website using the same LoginView. Does that mean it's a matter of the django version I'm using or a another variable I can't think of? Cheers -
Django: view-less template refreshed through AJAX?
So I'm refreshing an HTML div with some data on background asynchronous jobs. I obviously want to keep this as DRY as possible so I want to generate the HTML server-side and only have the Javascript code call it whenever the socket gets a message from the server. I don't want to have to call a view for each time this template needs re-rendering, it seems very resource-heavy. How can I do it? Is there a way to hit that template's URL, each time passing it the relevant context? -
How do I call a certain Episodes in a Genre
I am new to django and I am getting confused over that, basically I want to iterate through all of the series and return the ones that are in certain genre. models.py class Series(models.Model): series_title = models.CharField(max_length=50) series_desc = models.TextField(max_length=500) series_date_published = models.DateTimeField() class Genres(models.Model): genre_name = models.CharField(max_length=50) genre_serie = models.ManyToManyField(Series) class Episodes(models.Model): episode_title = models.CharField(max_length=50) episode_desc = models.TextField(max_length=500) episode_date_published = models.DateTimeField() episode_number = models.IntegerField() episode_series = models.ForeignKey(Series, on_delete=models.CASCADE) views.py class IndexView(generic.ListView): model = Series template_name = 'videos/index.html' context_object_name = 'series' def get_queryset(self): return Series.objects.all() class ViewSeries(generic.ListView): model = Episodes template_name = 'videos/videos.html' context_object_name = 'episodes' def get_queryset(self): return Episodes.objects.filter(episode_series=self.kwargs['pk']) class ViewGenres(generic.ListView): model = Series template_name = 'videos/genres.html' context_object_name = 'series' def get_queryset(self): return Series.objects.filter(genres__genre_serie=self.kwargs['pk']) And I am trying that to display my series in a genre: {% for s in series %} <a href='(% url ?? %)'>{{ s.series_title }}</a></td> {% endfor %} urls.py app_namme = 'videos' urlpatterns = [ path('', IndexView.as_view(),name='index'), path('viewseries/<int:pk>', ViewSeries.as_view(),name='detail'), path('viewgenres/<int:pk>', ViewGenres.as_view(),name='genres'), ] I placed that url because from there I want to get the link to the series but when I type {% url 'detail' ser.id %} I got NoReverseMatch error. I am pretty sure that there is an easy solution to all of that … -
Is this a good case to deviate from Django's ORM and use raw SQL? (Unless models can be dynamically generated)
So I have been using Django's ORM for everything; however, I have gotten to a part of this application where I don't think it makes sense. That is unless, models can be dynamically generated and dropped into models.py so I don't have to update it every year. The company this application is for aggregates data from various industries. There is no overlap between them. Furthermore, the data collected from each industry can vary from year-to-year. Thus tables are broken up like: Industry_A_15 Industry_A_16 Industry_A_17 Industry_B_15 Industry_B_16 Industry_B_17 I don't see how the ORM could work unless I added them to models.py every year (there are over a hundred columns for each). The most efficient way, I can think of, for doing it would be to do something like ./manage.py inspectdb > models.py, but that tends to not work on tables with constraints. So would this be a good case to write in raw SQL? It sounds like I'd want to avoid the model layer altogether really: https://docs.djangoproject.com/en/2.0/topics/db/sql/#executing-custom-sql-directly Then I could dynamically refer to the tables and really not have to touch it in the future. Also, the queries would be pretty basic SELECT such that I would think it should … -
Is there any way to create an array of files in a model in django?
I am creating a web app for cloud storage where user can create folders and upload files. I want to create a model for files like: class upload(models.Model): files = # array of files which I don't know how to create title = models.CharField(max_length = 30) user = models.ForeignKey(User,on_delete=models.CASCADE) I will be thankful if anyone suggests me how to do so or tell me any other efficient way to upload files and use it. -
Django is not writing logs to a local file
I am trying to log the below requests to a local file. I am using a logging function in settings.py file. Django is creating an empty file but its not writing any thing. Can any one help me what is the wrong i am doing and is it the right logging code to use for logging the below format data? Thank you. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '/home/bluedata/mysite/info.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, 'mysite': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, }, } [![These are the requests i want to log.][1]][1] [05/Jan/2018 22:26:19] "GET /contact/ HTTP/1.1" 200 1833 [05/Jan/2018 22:26:20] "GET /static/personal/css/bootstrap.min.css HTTP/1.1" 304 0 [05/Jan/2018 22:26:20] "GET /static/personal/img/logo.jpg HTTP/1.1" 304 0 [05/Jan/2018 22:26:22] "GET / HTTP/1.1" 200 5533 [05/Jan/2018 22:26:22] "GET /blog/ HTTP/1.1" 200 1909 [05/Jan/2018 22:26:23] "GET /contact/ HTTP/1.1" 200 1833 [05/Jan/2018 22:26:23] "GET / HTTP/1.1" 200 5533 [1]: https://i.stack.imgur.com/KHh9j.png