Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ,View class,There are two put methods
environment: django==1.11.11, rest_framework Having methods with the same name handle different routes in the same view class or view set, using the decorator ? example: class Indexs(APIView): @decorator("detailed/") def get(self, request): pass @decorator("list/") def get(self, request): pass -
Slow setup time for pytest, how do I reduce?
I am new to pytest, I am running a very simple test to assert a model creation, but running the test seems to take a substantial amount of time. I have maybe 10 models tops, none of which are incredibly complicated. 4.67 setup 0.69s call 0.09s teardown This is with adding the arguments (without the arguments it's over 30 seconds!): pytest --nomigrations --reuse-db Am I doing something wrong? How do I decrease this setup time? Does setup time depend on number of models, something else? I can't imagine how long this will take once the app gets big. Any advise is welcome. -
Django and nginx and gunicorn and docker compose - configuring URLs
I'm building a practice app in Django 2, Docker Compose and Nginx. Spinning up the images is successful, however, any non Django/Python files do not load. For example, /static/bootstrap-3.2/dist/css/bootstrap.css (or any file in /static) does not load. I've seen a few other related questions on SO about this, but for some reason I think I'm still missing something for my config. There are console logs and terminal lines indicating 404 errors for the static or other directory resources. Appreciate any help, thanks! WorkDir Tree |- gunicorn/ |- nginx\ |-- nginx.conf |- static/ |-- ... |- django/ |-- __init__.py |-- templates/ |-- manage.py |-- settings.py |-- forms.py |-- views.py |-- urls.py |-- wsgi.py |- docker-compose.yml |- Dockerfile |- requirements.txt Dockerfile FROM python ENV PYTHONUNBUFFERED 1 ADD . /ljingo WORKDIR /ljingo RUN pip install -r requirements.txt RUN python -m nltk.downloader punkt RUN python -m nltk.downloader wordnet RUN python -m nltk.downloader averaged_perceptron_tagger requirements.txt Django==2.0 django-crispy-forms psycopg2 gunicorn nltk==3.3 nginx/nginx.conf server { root /; listen 80 default_server; listen [::]:80 default_server ipv6only=on; access_log /logs/access.log; error_log /logs/error.log; location /media { alias /ljingo/ljingo/media; } location ~ /static { alias /ljingo/ljingo/static; } location ~ /static/custom.css { alias /ljingo/ljingo/static/custom.css; } location ~ \.css { add_header Content-Type text/css; } location … -
How does a .env file relate to Python / Django?
I'm pretty new to Django / Python, and I'm trying to figure out how a .env file relates to a Django project. Example .env: DATABASE_URL=postgres://postgres_user@db:xxxx/postgres_db DJANGO_SETTINGS_MODULE=spare.settings.dev SECRET_KEY=example I did manage to find this Stack Overflow post, which gives some information, but was hoping for a bit more. Do all Django projects have a .env file? Do non-Django python projects have a .env file, or is it generally a Django-related thing? Where is the .env file typically being called from? In other words, how does the rest of the project know that the .env file exists? Thanks for any help. -
Django APIRequestFactory converting CamelCase JSON keys and values to underscore_formatting
This generates a request and passes it to my view factory = APIRequestFactory() body = {'satellite': 'sat', 'groundStation': 'groundA'} request = factory.post('/accesses', body) response = view(request) When the view function receives the request, request.data contains {'satellite': 'sat', 'ground_station': 'ground_a'} The keys and there values have been reformatted. I'm trying to keep app this consistent with an API some other services are familiar with. How do I turn off this reformatting? -
Django - AJAX - how to submit multiple forms?
Here are my two ajax codes for two forms. These two codes are exactly the same, except for button ID $("#form_1_submit").on('click', function (e) { e.preventDefault(); var form = $(this).closest("form"); var data = form.serializeArray(); $.ajax({ url: "", dataType:"json", type: "POST", data: data, success: function() { alert('ajax request') }, error: function() { alert("error") } }); console.log(form.html()) }); $("#form_1_submit").on('click', function (e) { e.preventDefault(); var form = $(this).closest("form"); var data = form.serializeArray(); $.ajax({ url: "", dataType:"json", type: "POST", data: data, success: function() { alert('ajax request') }, error: function() { alert("error") } }); console.log(form.html()) }); And here is my views.py: class BHA_UpdateView(UpdateView): model = Different_Model fields = '__all__' def post(self, request, **kwargs): if self.request.is_ajax(): print(self.request.POST) form_1 = Form_2(request.POST, instance=Model_1.objects.filter(#some_filtering...) form_2 = Form_1(request.POST, instance=Model_2.objects.filter(#some_filtering...) if form_1.is_valid(): form_1.save() return super().post(request, **kwargs) if form_2.is_valid(): form_1.save() return super().post(request, **kwargs) return super().post(request, **kwargs) There are two problems: First: $.axax({...}) gives error, instead of success, and I don't know why. But it still saves to DB. Second: Submitting one form results in the other form's values not saving to DB. This is my current page: Ideally, clicking one of the Save button should result in saving data to each respective tables in DB. But if I click Save for Overall BHA, … -
Django: Best way to create a multiple choice field
WHen creating a multiple choice option in Django, there seems to be two different ways to do it - option a or option b, see below. What advantages do each option have over the other. Is one generally better than another? Am I missing a better way to do it? option a TYPE_CHOICES=( ('teacher', ("Teacher")), ('student', ("Student")), ) user_type = models.CharField(max_length=20, default='student', choices=TYPE_CHOICES) option b TYPE_CHOICES=( (1, ("Teacher")), (2, ("Student")), ) user_type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES, default=1) -
Trying to draw a simple plot in django using pandas plot
Hi I am trying to draw a simple plot in django however on passing the data frame I get an AttributeError: 'AxesSubplot' object has no attribute 'to_html'.Please assist for I am new to django .Thanks [IMG]http://i64.tinypic.com/10fs7r6.png[/IMG] Link shows my code. -
Django ModelForm - Prevent save in View
I am trying to use a ModelForm to save a model. forms.py class PurchaseForm(forms.ModelForm): weight = forms.IntegerField() class Meta: model = Purchase fields = ["number", "pieces"] views.py if request.method == "POST": form = PurchaseForm(request.POST) if form.is_valid(): purchase = form.save(commit=False) purchase.contract = Contract.objects.get(number=slug) weight = form.cleaned_data.get('weight') if check_weight(weight, purchase.contract): weight_type = purchase.contract.supplier.market.weights purchase.lbs, purchase.kgs = generate_weights(weight, weight_type) purchase.save() In the view above, I need to prevent the model from saving if the check_weight function returns False. This function requires some data from the related object. I'm having some trouble figuring this out. What should I do? -
can some one help me on django with this ImportError: cannot import name 'product_detial_view' from 'products.views'
i'm a noob in django and i watched some tutorial but i ran into a error that i can't really fix, and just here to ask if anyone can help me out and i'm using mac with bash, python 3.7.0, sublime text, and the tutorial is in youtube, i really need someone who could solve this problem for me thanks Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10ed24378>Traceback (most recent call last): File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors=check(app_configs=app_configs) File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/urls/resolvers.py", line 399, in check for pattern in self.url_patterns: File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/utils/functional.py", line 36, in __get__ res=instance.__dict__[self.name]=self.func(instance) File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/urls/resolvers.py", line 540, in url_patterns patterns=getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/utils/functional.py", line 36, in __get__ res=instance.__dict__[self.name]=self.func(instance) File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/urls/resolvers.py", line 533, in urlconf_module return import_module(self.urlconf_name) File "/Users/evangui88/Dev/trydjango/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File " <frozen importlib._bootstrap>", line 983, in _find_and_load File " <frozen importlib._bootstrap>", … -
form fields a not showing up on html page django
This is my template which I am using in the login page but the problem is fields are not showing up .I want to use mdbootstrap on the page.i have searched it on many websites but did't got a solution and every one was using the same thing to use the form is the something I am missing in my code? <form action="{% url 'login' %}" method="POST"> {% csrf_token %} <div class="md-form"> <i class="fa fa-envelope prefix"></i> {{ form.username }} {{ form.username.label_tag }} </div> <div style="padding:5px"></div> <div class="md-form" > <i class="fa fa-lock prefix"></i> {{ form.password.label_tag }} {{ form.password }} </div> {% if requset.GET.next %} <input type="hidden" name="next" value="{{ request.GET.next }}"> {% endif %} <button type='submit' class="btn info-color ">log in</button> </form> and forms.py from django.contrib.auth.forms import AuthenticationForm from django import forms class LoginForm(AuthenticationForm): username = forms.CharField(label="Username", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'})) password = forms.CharField(label="Password", max_length=30, widget=forms.PasswordInput(attrs={'class': 'form-control', 'name': 'password'})) -
DocuSign Python SDK - API Exception 400 - 'Bad Request'
I have made a couple of posts regarding the issue of integrating Docusign's Python SDK with my web app for my company. Essentially what I'm doing, is I'm having the user fill out a form, which, after the user clicks the submit button, weasyprint generates a pdf from an html template I've created, with the customer's information placed in the correct spots. I then want DocuSign to send an email to the user with the newly generated PDF, and have them sign the form, and have it sent to an email account for my company. Here is the way I'm trying to integrate Python's SDK into my Django web app: def Signview(request): loa = LOA.objects.filter().order_by('-id')[0] # This is pulling the information about the user from a model in my database username = "myusername@docusign.com" integrator_key = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" base_url = "https://demo.docusign.net/restapi" oauth_base_url = "account-d.docusign.com" redirect_uri = "http://localhost:8000/path/to/redirecturi" private_key_filename = "path/to/pKey.txt" user_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" client_user_id = 'Your System ID' # This is the actual string I am using for this variable # Add a recipient to sign the document signer = docusign.Signer() signer.email = loa.email signer.name = loa.ainame signer.recipient_id = '1' signer.client_user_id = client_user_id sign_here = docusign.SignHere() sign_here.document_id = '1' sign_here.recipient_id = '1' … -
How to add a "unique_together" constraint to a core model in django?
I'm trying to extend the django Group model to make it friendlier for multi tenancy. Basically I want to remove the unique constraint on the name field, add a field called tenant, and make name and tenant unique together. So far I can do all of that but I can't create the unique_together constraint. Here's what I have so far: from django.contrib.auth.models import Group Group._meta.get_field('name')._unique = False Group.add_to_class('tenant', models.ForeignKey(blah blah blah)) Now how would I create the unique_together constraint? -
Using a composition pattern leads to infinite recursion with Django Factory Boy?
I have a model Profile which has a one-to-one field with a User: from django.db import models class Profile(models.Model): user = models.OneToOneField(User, related_name='user_profile', on_delete=models.CASCADE) I'm trying to update the User model with a __getattr__ method that delegates to the Profile model, similar to http://blog.thedigitalcatonline.com/blog/2014/08/20/python-3-oop-part-3-delegation-composition-and-inheritance/#enter-the-composition: from django.contrib.auth.models import User def user__getattr__(self, attr): return getattr(self.user_profile, attr) User.add_to_class('__getattr__', user__getattr__) This seems to work as expected. For example, one of the fields defined on the Profile model is a timezone, and now I can access it like In [4]: from lucy_web.models import * In [5]: User.objects.first().timezone Out[5]: 'America/Los_Angeles' The problem occurs when I try to generate users using factory_boy. I have a UserFactory with a RelatedFactory referring to the ProfileFactory: import factory from lucy_web.models import User from .profile_factory import ProfileFactory class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User user_profile = factory.RelatedFactory(ProfileFactory, 'user') @classmethod def _create(cls, model_class, *args, **kwargs): """Override the default ``_create`` with create_user.""" manager = cls._get_manager(model_class) # The default would use ``manager.create(*args, **kwargs)`` return manager.create_user(*args, **kwargs) The ProfileFactory is quite simple, similar to class ProfileFactory(factory.django.DjangoModelFactory): class Meta: model = Profile The problem is that if I now try to create a user using the UserFactory, I get an infinite recursion error: (lucy-web-CVxkrCFK) bash-3.2$ python … -
How to do left outer join in django that returns distinct foreign keys that exist in joined table
I know how to do this in SQL: SELECT DISTINCT(products.id), products.product_url FROM products LEFT OUTER JOIN recommendations ON products.id=recommendations.product_id WHERE recommendations.product_id IS NOT NULL; But I am not sure how to proceed with Django's ORM. I need to use the ORM rather than a raw query because Django Rest Framework uses the len method in its paginator and another method for queryset.order_by(...). I'm assuming that there is some combination of F() and Q() expressions that must be used, but I'm too new at this to know exactly what the translation is. -
'title' is an invalid keyword argument for this function [Python + Django + DRF]
After updating my models and serializers, I cannot save new articles to the Database. I keep getting "'title' is an invalid keyword argument for this function." I am working on Postgres10, Python3.6, Django2.0 and DRF 3.8.2. I have dropped my DB a couple of times but the error persists. Please, I need your help. Thanks in advance. Here's a copy of my old models class Article(models.Model): title = models.CharField(max_length=200, blank=False) slug = models.SlugField(max_length=250, unique_for_date='created') body = models.TextField() image_url = models.URLField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add = True) published = models.DateTimeField(auto_now=True) updated = models.DateTimeField(auto_now=True) country = models.ForeignKey(Country, on_delete=models.CASCADE) categories = models.ManyToManyField(Category, default=1) # categories = ArrayField(models.IntegerField(), blank=False) entities = models.ManyToManyField(Entity, default=1) # entities = ArrayField(models.CharField(max_length=200), blank=True) summary = models.TextField(blank=True) is_published = models.BooleanField(default=False) is_curated = models.BooleanField(default=False) class Meta: ordering = ('-created',) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Article, self).save(*args, **kwargs) My new (updated) models: class Article(models.Model): title = models.CharField(max_length=200, blank=False) slug = models.SlugField(max_length=250, unique_for_date='created') body = models.TextField() image_url = models.URLField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add = True) published = models.DateTimeField(auto_now=True) updated = models.DateTimeField(auto_now=True) country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name="posts") category = models.OneToOneField(Category, on_delete=models.CASCADE, default=1, related_name="posts") entities = models.ManyToManyField(Entity, default=1, related_name="posts") summary = models.TextField() keypoint1 … -
Django - running manage.py produces fatal error for version.py: Not a git repository
I have copied my Django 1.4.3 app from one server to another. It is running using mod_wsgi daemon on the other server. mod_python is installed, as verified by looking at php.info(). Python version is 2.7, and Apache version is 2.4. I get the following error whenever I run manage.py runserver 0.0.0.0:8000: Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 252, in fetch_command app_name = get_commands()[subcommand] File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 101, in get_commands apps = settings.INSTALLED_APPS File "/usr/lib/python2.7/site-packages/django/utils/functional.py", line 184, in inner self._setup() File "/usr/lib/python2.7/site-packages/django/conf/__init__.py", line 42, in _setup self._wrapped = Settings(settings_module) File "/usr/lib/python2.7/site-packages/django/conf/__init__.py", line 128, in __init__ logging_config_module = importlib.import_module(logging_config_path) File "/usr/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/lib/python2.7/site-packages/django/utils/log.py", line 6, in <module> from django.views.debug import ExceptionReporter, get_exception_reporter_filter File "/usr/lib/python2.7/site-packages/django/views/debug.py", line 9, in <module> from django.http import (HttpResponse, HttpResponseServerError, File "/usr/lib/python2.7/site-packages/django/http/__init__.py", line 19, in <module> from mod_python.util import parse_qsl File "/usr/lib64/python2.7/site-packages/mod_python/__init__.py", line 25, in <module> from . import version File "/usr/lib64/python2.7/site-packages/mod_python/version.py", line 3 version = "fatal: Not a git repository (or any of the parent directories): .git The version.py file has the following contents: # THIS FILE IS AUTO-GENERATED BY … -
Conditionally Filter Within Django Queryset
I'm wondering if there is a way to conditionally filter a queryset in Django based on if the value filtered against is None or not. I know that you can do something like this: some_name = 'Bob' qs = MyModel.objects.filter(gender='boy') if some_name: qs = qs.filter(name=some_name) where we conditionally filter on the variable some_name only if it exists. I'm curious if this logic can be replicated with a single query statement, instead of "chaining" on a filter to the end of a queryset. So this would look something like: qs = MyModel.objects.filter(gender='boy').filter(name=some_name if some_name else None) Obviously that example isn't valid, because it would filter on name=None instead of not filtering, but has anyone found a way to do what I'm intending? For longer, nested queries, it would be very helpful to have it all in one statement. -
Could not display image uploaded template
please help me! i'm in model author create a field for upload picture for my author! But when i wanna go inside template Do not show me! Why? my code in template <img src="{{ post.author.pic }}" /> and in model author : pic = models.ImageField(upload_to = func.upload_location, null = True, blank = True) -
Django ListView not working
I want to display list of notes on a per user basis. So that the user who has logged in can only see his/her notes. However the listview for displaying all the notes for the logged in user is not working.Is there anything I need to add? Please help! Views.py class NotesListView(LoginRequiredMixin,ListView): model=Notes models.py class Notes(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) title=models.CharField(max_length=255) subject=models.CharField(max_length=255) text=models.TextField() def get_absolute_url(self): return reverse('notes_detail',kwargs={'pk':self.pk}) forms.py class NotesCreateForm(forms.ModelForm): class Meta: model=Notes fields=('title','subject','text') notes_list.html {% extends 'base.html'%} {% block content %} <div class="jumbotron container" style="background-color:rgba(0, 0, 0, 0.1);margin-top:2em;"> <a href="{%url 'notes_create'%}">Add</a> <br> {%for note in notes_list %} <a href="{%url 'notes_detail' pk=note.pk%}">{{user.note.title}}</a><br> {% endfor %} </div> {% endblock %} -
Django : view calls an other template (Pagination )
I have this view: class DamageListCriteria(TemplateView): template_name = "damage/damagelist_criteria.html" def get(self, request): form = DamageListCriteriaForm() general = General.objects.get(pk=1) args = { 'form': form, 'general': general } return render(request, self.template_name, args) def post(self, request): general = General.objects.get(pk=1) form = DamageListCriteriaForm(request.POST) form.non_field_errors() if form.is_valid(): fromdate = request.POST.get('fromdate') fdate = datetime.strptime(fromdate, '%d/%m/%Y') fdate = datetime.combine(fdate, datetime.min.time(), tzinfo=pytz.UTC) print('fdate ', fdate) todate = form.cleaned_data['todate'] #tdate = datetime.strptime(todate, '%d/%m/%Y') + timedelta(days=1) tdate = datetime.strptime(todate, '%d/%m/%Y') tdate = datetime.combine(tdate, datetime.max.time(), tzinfo=pytz.UTC) print('tdate ', tdate) d_list = Damage.objects.filter(entry_date__range=(fdate, tdate)) paginator = Paginator(d_list, 1) page = request.GET.get('page') try: damage_list = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. damage_list = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. damage_list = paginator.page(paginator.num_pages) template = "damage/damagelist_table.html" form = DamageListForm() general = General.objects.get(pk=1) fromdatetext = fdate.strftime('%d/%m/%Y') todatetext = tdate.strftime('%d/%m/%Y') args = { 'form': form, 'damage_list': damage_list, 'general': general, 'fromdate': fromdatetext, 'todate': todatetext } return render(request, template, args) else: print('form is not valid') print(form.errors) # form = DamageEntryForm() args = {'form': form, 'general': general } return render(request, self.template_name, args) I want to get some criteria to make a filtering listing of my database. It worked this way , … -
key value template loop with equals
I am trying to hide div based on the 1 and 0. I wrote the below code but I am getting Exception Value:'int' object is not iterable error. I think I am doing wrong with {%if k.v == 1%} but don't know how to fix. hide_dict items --> {'hide0': 1, 'hide1': 0, 'hide2': 0, 'hide3': 1} {% for key, values in hide_dict.items %} {% for mydict in values %} {%for k,v in mydict.items %} {%if k.v == 1%} <div style="display:none"> {% elif k.v == 0 %} <div> {% endif %} {% endfor %}{% endfor %}{% endfor %} -
Django: Multiple forms on page to be submitted either individually or all at once
I am creating a survey app where users can fill out surveys on other users. As part of this, I want to allow users to fill out surveys for multiple users in one view. For this, there are 2 instance variables I want to set that are required for the model, but should not be set by the user for the form. These are reporter (request.user) and user (the subject of the survey). I am trying to figure out how to do this, but haven't used Formsets enough (i.e. at all) to quite figure this out. I've also found this a bit tricky because I have 2 different models in play here. 1st (Surveys) is where the survey results are stored, 2nd (SurveysQueue) is where the information regarding survey queues are stored (i.e. user with their list of users in a ManyToManyField for the queue). My code is below, but I essentially need to figure out 2 things. 1) How can I dynamically pass instance variables if I'm using a formset (I've tried without formsets for this reason because I couldn't figure it out) and 2) How can I allow forms to either be all submitted via 1 button or … -
'Specifying a namespace in include() without providing an app_name '. Html files not in the application, but in project directory.
I tries to do this tutorial, but I have one problem. It is caused another version Django. I have seen many similar topics on the forum but I was not able match them to my situation. When trying to start 'http://127.0.0.1:8000/accounts/login/' in files like those below, I can see the message 'NoReverseMatch at /accounts/login/'. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 2.0.7 Python Version: 3.7.0 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'reviews') Installed Middleware: [] Template error: In template C:\Users\tymot\Desktop\aktualny_projekt-Podejscie_2\env\my_app\winerama\templates\base.html, error at line 21 'auth' is not a registered namespace 11 : </div> 12 : <div id="navbar" class="navbar-collapse collapse"> 13 : <ul class="nav navbar-nav"> 14 : <li><a href="{% url 'reviews:wine_list' %}">Wine list</a></li> 15 : <li><a href="{% url 'reviews:review_list' %}">Home</a></li> 16 : </ul> 17 : <ul class="nav navbar-nav navbar-right"> 18 : {% if user.is_authenticated %} 19 : <li><a href="{% url 'auth:logout' %}">Logout</a></li> 20 : {% else %} 21 : <li><a href=" {% url 'auth:login' %} ">Login</a></li> 22 : {% endif %} 23 : </ul> 24 : </div> 25 : </nav> 26 : 27 : 28 : <h1>{% block title %}(no title){% endblock %}</h1> 29 : 30 : {% bootstrap_messages %} 31 : Traceback: File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\base.py" in … -
Pagination DRF not working well
I have a little problem with pagination when I put the default pagination in my project, somethings pages work in others pages not working for example: this is my file settings.py for all my project REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'apicolonybit.notification_clbt.NotificationPagination.PaginationList'} this is my Configuration app inside my project: myproject / Configuration class ConfigurationsList(generics.ListAPIView): """ list configuration with current user authenticated. """ queryset = Configuration.objects.all() serializer_class = ConfigurationSerializer when I run this part in my postman, working well, but when I try to run in another module like this: class TransactionListHistory(generics.ListAPIView): # queryset = TransactionHistory.objects.all() serializer_class = TransactionHistorySerializer pagination_class = PaginationList page_size = 2 page = 1 def get_object(self, current_user): # User.objects.get(id=pk) return TransactionHistory.objects.filter(agent_id=current_user.id).order_by('-id') @classmethod def get_object_client(cls, current_user, trans): # User.objects.get(id=pk) return TransactionHistory.objects.filter(user_id=current_user.id).order_by('-id') def get(self, request, format=None): current_user = request.user status_trans = 6 agent_user = 2 client_user = 1 trans = { 'status': status_trans } typeusers = Profile.objects.get(user_id=current_user.id) # actions agent user = show all transaction from all client users if typeusers.type_user == agent_user: list_trans_init = self.get_object(current_user) serializer = TransactionHistorySerializer(list_trans_init, many=True) get_data = serializer.data # actions normal user (client user) = just see transactions from self user if typeusers.type_user == client_user: list_trans_init = self.get_object_client(current_user, trans) serializer = TransactionHistorySerializer(list_trans_init, many=True) get_data = …