Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch for SlugField?
I 'slugified' the team_name field for model Team so that spaces would display more beautifully in the URL. However when I try to switch the pk variable that you pass into the URL, I get a NoReverseMatch for the slug. It is working fine for with team_name. models class Team(models.Model): team_name = models.CharField(max_length=25, unique=True) team_name_slug = models.SlugField(max_length=25, unique=True) views + template URL (this doesn't work) def team_public_profile(request, pk): team = get_object_or_404(Team, team_name_slug=pk) ... other code --- <form action="{% url 'team_public_profile' pk=team_name_slug %}"> this works def team_public_profile(request, pk): team = get_object_or_404(Team, team_name=pk) ... other code --- <form action="{% url 'team_public_profile' pk=team_name %}"> -
Expire token generator return InvalidToken
I'm trying to create a expire token generator. However when i for instance use generate_token and then use the token in get_token_value i keep getting cryptography.fernet.InvalidToken i guess this is a issue with the encoding in the two functions, but i'm not quite sure what im missing? generator from datetime import datetime, timedelta import cryptography from cryptography.fernet import Fernet from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.utils.encoding import force_bytes, force_text class ExpiringTokenGenerator(object): FERNET_KEY = Fernet.generate_key() fernet = Fernet(FERNET_KEY) DATE_FORMAT = '%Y-%m-%d %H-%M-%S' EXPIRATION_DAYS = 1 def _get_time(self): """Returns a string with the current UTC time""" return datetime.utcnow().strftime(self.DATE_FORMAT) def _parse_time(self, d): """Parses a string produced by _get_time and returns a datetime object""" return datetime.strptime(d, self.DATE_FORMAT) def generate_token(self, text): """Generates an encrypted token""" full_text = str(text) + '|' + self._get_time() token = self.fernet.encrypt(bytes(full_text, 'utf-8')) return token def get_token_value(self, token): """Gets a value from an encrypted token. Returns None if the token is invalid or has expired. """ try: value = self.fernet.decrypt(bytes(token, 'utf-8')) separator_pos = value.rfind('|') text = value[: separator_pos] token_time = self._parse_time(value[separator_pos + 1: ]) print(token_time) if token_time + timedelta(self.EXPIRATION_DAYS) < datetime.utcnow(): return None except cryptography.fernet.InvalidToken: return None return text def is_valid_token(self, token): return self.get_token_value(token) != None invoice_activation_token = ExpiringTokenGenerator() -
Django ImageField changes some characters in the file name unexpectedly
I am using ImageField field in my model with a custom function for the upload path as following: featured_image = models.ImageField( upload_to=custom_path, blank=True, null=True) where custom_path is defined as following: def custom_path(instance, filename): return 'post_images/{0}/{1}/{2}/{3}'.format(instance.publication_datetime.strftime('%Y'), instance.publication_datetime.strftime('%b'), instance.slug, filename) The problem is that when I upload a file with a name of "سائل-أن" (which is in Arabic), the name gets converted to "سايل-ان" which has two different characters from the original name ("ئـ" is converted to "يـ", and "أ" is converted to "ا"). I think that the problem is with how Django gets the filename parameter that is sent to custom_path because slug won't be modified if it has the same "problematic" name ("سائل-أن"). The letters that get converted are normal Arabic letters that are used millions of times on the internet. I've searched in Django documentation and source code, but I couldn't know the cause of the problem. -
urls.pyc and views.pyc files do not auto update
I'm new to django and have been going through tutorials on udemy and on the django website. I'm using a virtual environment and Bash on Ubuntu Windows. My issue is that when I update code in any views.py / urls.py files for my project it doesn't "compile" in the .pyc files. So say I add a home page to my urls list I get an error that the page was not found. Once I go back and delete the .pyc files though I can access a home page (or what ever page) I've added. My work around at the moment is that I wrote a python script to delete the .pyc files. -
JSON data not coming through from Django REST API
I have a Django REST API with an Angular Front-end. I am getting no errors on the front-end, but no json data is logging to the console. I have a service like so: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class WeatherstatsService { constructor(private http:Http) { console.log("Hello World"); this.getWeatherData(); // this.getWeatherDataRecords(); } weatherdata: any = {}; private _WeatherStatsUrl = 'http://127.0.0.1:8000/weatherstats/weatherdata'; getWeatherData() { return this.http.get(this._WeatherStatsUrl) .map((res:Response) => res.json()); } getWeatherDataRecords() { this.getWeatherData().subscribe(weatherdata => { console.log(weatherdata) }) } } feeding a component like so: import { Component, OnInit } from '@angular/core'; import { WeatherstatsService } from '../weatherstats.service'; @Component({ selector: 'weather-stats', templateUrl: './weather-stats.component.html', styleUrls: ['./weather-stats.component.css'] }) export class WeatherStatsComponent implements OnInit { data: any; constructor(private weatherstatsservice: WeatherstatsService) { } ngOnInit() { console.log(this.weatherstatsservice.getWeatherData().subscribe(data => this.data = data)); } } I am new to both Django and Angular, when I test the API in the browser I get the data I want. What could be happening that means I can't see my json data? (With apologies to people who tried to help on similar issue just now - My brain is exploding with all this new stuff!) -
Django staticfiles images not showing
I worked out how to link my CSS files to my HTML with Django but I can't figure out how to get my images to show in my base.html file. These are my files, and this is how I added images, maybe I'm doing something wrong? pic with all the files and directories first, I made a static directory and then I made two sub-directories, CSS and Images. I put my css files in the css directory and then I put my images where my images directory is. Then I used this piece of code to try to add uptown.jpg as my background in css. header { background-image:linear-gradient(rgba(0, 0, 0, 0.5),rgba(0, 0, 0, 0.5)), url({% static 'static/images/uptown.jpg' %}); height: 65vh; background-size: cover; background-position: center; } But the image never appeared, on my website. I also tried to link it just how I would normally do it in a css file without Django tags but still didn't work. I have everything set up in my settings.py in terms of the staticfiles_dir and all. so I'm not sure what the problem is, so please help. best, thanks! -
python spyne with django to make a rpc api service:Requested resource not found
I recently learned how to use python spyne to build a rpc webservice. I used the examples in the package as a start. But I stuck on always getting a "resource not found " response and can't figure why. Here are the codes simplified from the spyne/example/django the view.py class HelloWorldService(Service): @rpc(Unicode, Integer, _returns=Iterable(Unicode)) def say_hello(ctx, name, times): for i in range(times): yield 'Hello, %s' % name app = Application([HelloWorldService], 'spyne.examples.django.core', in_protocol=HttpRpc(validator='soft'), out_protocol=Soap11()) hello_world_service = DjangoApplication(app) the urls.py urlpatterns = [ url(r'^hello_world/', hello_world_service) ] I use the url http://localhost:8000/hello_world?name=World&times=4&quot to see the rpc result.But I always got a response which said: ``` <?xml version='1.0' encoding='UTF-8'?> <soap11env:Envelope xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/"> <soap11env:Body> <soap11env:Fault> <faultcode>soap11env:Client.ResourceNotFound</faultcode> <faultstring>Requested resource u'{spyne.examples.django.core}' not found</faultstring> <faultactor></faultactor> </soap11env:Fault> </soap11env:Body> </soap11env:Envelope> ``` environment python: 2.7.12 Django:1.11.7 spyne: 2.13.1 -
about: Django, python's super() on multiple inheritance accessing from parent 1 to parent 2 method when parent 2 isnt on parent's 1 MRO?
Problem regarding using of super() to support cooperative multiple inheritance in a dynamic execution environment. I have attached the jpgs to specify. jpg scanned pages, doubt on django unleashed super method jpg super() MRO chain, doubt on django unleashed super method part 2 main doubt: -- how does super() get to call the version of the method (get_context_data()) found in ListView if the Mixin has no relation whatsoever with ListView itself on its Method Resolution Order? I also have this other question. -- How so it says GCBV (ListView) will have created the Page instance at this point if the mixin is passed as first argument and GCBV listview comes after? references used: code, first snippet https://dju.link/be588e9505/organizer/utils code, second snippet https://dju.link/81321265be/organizer/views.py super() http://www.artima.com/weblogs/viewpost.jsp?thread=236275 https://docs.python.org/3/library/functions.html#super -
Django configuring different databases
I have 2 databases of interest, the basic one and the development one: mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | projectsdb | | projectsdb_dev | +--------------------+ 3 rows in set (0.00 sec) In my django file mysite/mysite/settings.py, my databases are declared this way: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'projectsdb', 'USER': 'projectsdb', 'PASSWORD': 'notsecure', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } } The allowed hosts is: ALLOWED_HOSTS = ['xxx.xx.xxx.xx'] # I replaced it for the example I start the server on the port 8006 which I use for developing: $ python ./manage.py runserver xxx.xx.xxx.xx:8006 And here I modify the production database. I can switch to the dev database replacing the default database name: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'projectsdb_dev', 'USER': 'projectsdb', 'PASSWORD': 'notsecure', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } } And it works fine, the server is interacting with the projectsdb_dev database. However I would like to keep both databases available in the settings file and I saw tutorials setting it up this way: DATABASES = { 'default': {}, 'prod': { … -
400 Bad Request getting data from DJango API with Angular 4
I have a Django RESTAPI with a urls.py like this: from django.contrib import admin from django.conf.urls import url, include urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^weatherstats/', include('weatherstats.urls')), ] The API has an app with urls.py like this: from django.conf.urls import url from django.contrib import admin from rest_framework.urlpatterns import format_suffix_patterns from weatherstats import views urlpatterns = [ url(r'^$', views.WeatherData.download_weather_stats_uk), url(r'^england$', views.WeatherData.download_weather_stats_england), url(r'^wales$', views.WeatherData.download_weather_stats_wales), url(r'^scotland$', views.WeatherData.download_weather_stats_scotland), url(r'^weatherdata/', views.WeatherData.as_view()) ] urlpatterns = format_suffix_patterns(urlpatterns) And a serializers.py like this to convert output to json: from rest_framework import serializers from .models import WeatherStatistics class WeatherStatisticsSerializer(serializers.ModelSerializer): class Meta: model = WeatherStatistics fields = '__all__' My Angular4 front-end has a service like this: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class WeatherstatsService { constructor(private http:Http) { console.log("Hello World"); this.getWeatherData(); // this.getWeatherDataRecords(); } weatherdata: any = {}; private _WeatherStatsUrl = 'http://127.0.0.1:8000/weatherstats/weatherdata'; getWeatherData() { return this.http.get(this._WeatherStatsUrl) .map((res:Response) => res.json()); } getWeatherDataRecords() { this.getWeatherData().subscribe(weatherdata => { console.log(weatherdata) }) } } which feeds a component like this: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class WeatherstatsService { constructor(private http:Http) { console.log("Hello World"); this.getWeatherData(); // this.getWeatherDataRecords(); } weatherdata: any = {}; private _WeatherStatsUrl … -
Integrating pinax-badges in django with a points system
I am having trouble getting pinax-badges to work in my project. I followed the minimal usage example provided by creating a badges.py file in my app: #badges.py from pinax.badges.base import Badge, BadgeAwarded from pinax.badges.registry import badges class PointsBadge(Badge): slug = "points" levels = [ "Bronze", "Silver", "Gold", ] events = ["points_awarded",] multiple = False def award(self, **state): user = state["user"] points = user.get_profile().points if points > 10000: return BadgeAwarded(level=3) elif points > 7500: return BadgeAwarded(level=2) elif points > 5000: return BadgeAwarded(level=1) badges.register(PointsBadge) and a pretty bad points function that in my users model that calls a takes a parameter of amount and adds it to the points field in my user model. #User Model class User(AbstractUser): .... points = models.IntegerField(default=0) def award_points(self,amount): self.amount = amount self.points+=amount self.save() Now the function i am calling in a signal that checks when a user logs in and awards them some points.Like so #signal.py from django.contrib.auth.signals import user_logged_in,user_logged_out from django.dispatch import receiver from django.conf import settings from pinax.badges.registry import badges @receiver(user_logged_in) def award(sender,request ,user, **kwargs): user = request.user.award_points(5000) badges.possibly_award_badge("points_awarded", user=user) I registered the signal as well just to make sure. I am still not getting the desire result, which is, as soon as a … -
Should Whitenoise auto-compress static files? How?
I recently enabled Whitenoise for my Django project that will run on Heroku. I want Whitenoise to compress my static files automatically, as would seem to be possible from this part of the docs: http://whitenoise.evans.io/en/stable/django.html#add-compression-and-caching-support However, after adding the following to my settings: STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' I find that my files are not compressed! curl -H "Accept-Encoding: gzip" -I http://localhost:8080/static/app/js/auth.min.js HTTP/1.0 200 OK Date: Thu, 30 Nov 2017 17:14:27 GMT Server: WSGIServer/0.2 CPython/3.5.2 Last-Modified: Thu, 30 Nov 2017 01:45:33 GMT Content-Length: 103648 Content-Type: application/javascript; charset="utf-8" Cache-Control: max-age=0, public Access-Control-Allow-Origin: * However, if I manually gzip one of my files, everything works just peachy $ gzip ../app/static/app/js/auth.min.js $ curl -H "Accept-Encoding: gzip" -I http://localhost:8080/static/app/js/auth.min.js HTTP/1.0 200 OK Date: Thu, 30 Nov 2017 17:21:47 GMT Server: WSGIServer/0.2 CPython/3.5.2 Last-Modified: Thu, 30 Nov 2017 17:14:53 GMT Content-Type: application/javascript; charset="utf-8" Cache-Control: max-age=0, public Access-Control-Allow-Origin: * Vary: Accept-Encoding Content-Encoding: gzip Content-Length: 21870 Do I just have to add some script to my build process to gzip everything, or does Whitenoise include this? If it does, does anyone have any idea what I might be missing or doing wrong? I would really like the ability (as advertised in the docs above) to keep everything cached forever -
Python-socketio with Django and https
I'm trying create a system of calls with WebRTC, so I developed a Python code using Django and socketio In localhost my app works fine, but in AWS EC2 doesn't. I see this error on my browser console: POST https://mydomain.com.br/socket.io/?EIO=3&transport=polling&t=M0DrIuC&sid=a3f1d452bbb044a3ac7809e0e2a4e7fd 400 () My socketio-cliente: socket = io.connect('https://' + document.domain + ':' + location.port + namespace, verify=false); My NGINX: upstream gunicorn_webapp { # for a TCP configuration server 127.0.0.1:9000 fail_timeout=0; } server { listen 80; listen 443 ssl; ssl_certificate /etc/letsencrypt/live/mydomain.com.br/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/mydomain.com.br/privkey.pem; # managed by Certbot client_max_body_size 4G; # set the correct host(s) for your site server_name mydomain.com.br; keepalive_timeout 5; # path for static files root /deploy/sites/webapp; location / { # checks for static file, if not found proxy to app try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #enable this if and only if you use HTTPS #proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; # we don't want nginx trying to do something clever with # redirects, we set the Host: header above already. proxy_redirect off; proxy_pass http://gunicorn_webapp; } } Where is my mistake? Thank you so much. -
How much should I learn Python to learn Django? [on hold]
I want to learn Django. For work professionally. How much python language need to know or learn to learn Django? -
Django REST API returning No 'Access-Control-Allow-Origin' header is present with Angular 4
I set up a Django REST API with the Django REST framework, and I'm trying to access it via an Angular 4 front-end. I keep getting an error saying "No 'Access-Control-Allow-Origin' header is present on the requested resource." I tried installing django-cors-headers, but it doesn't seem to do anything. I'm thinking I may have my REST API set up wrong. settings.py """ Django settings for weather project. Generated by 'django-admin startproject' using Django 1.9. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'not_telling' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1:4200'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'weatherstats', ] MIDDLEWARE_CLASSES = [ 'django.middleware.common.BrokenLinkEmailsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'localhost:4200', ) ROOT_URLCONF = 'weather.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': … -
Create a Zip Archive from a cloned GitHub repo in Python
I'm working on a project using python(3.6) in which I need to create a zip archive which includes all files from a GitHub repo. The user will provide the git repo URL then I will need to clone this repo and create a zip archive which includes all files from GitHub repo. Here's what I have tried: ARCHIVE_NAME = func_obj.fname + '.zip' zip_archive = zipfile.ZipFile(ARCHIVE_NAME, "w") # Write files to the archive zip_archive.write(git.Repo.clone_from(func_obj.sc_github, to_path=os.path.join(ARCHIVE_NAME))) zip_archive.close() file_path = os.path.join(IGui.settings.BASE_DIR, ARCHIVE_NAME) Help me, please! Thanks in advance! -
Django: Using multiple slugs in a url
I want to keep my urls dynamic as well as clean. Therefore I'm using slugs. My problem right now is, that I get the following error: redefinition of group name 'slug' as group 2; was group 1 at position 42 I think I get that error, because I have to slugs in my chain. For reference I have a ListView into ListView into an UpdateView, alls importet from django.views.generic. The first list view gives me the first slug and the update view the second. Here is the url pattern (spread across the apps): First list view: urlpatterns = [ url(r'^$', RestaurantListView.as_view(), name='restaurant-list'), url(r'^(?P<slug>[\w-]+)/menus/', include('menu.urls', namespace='menu')), ] Second list view: urlpatterns = [ url(r'^$', MenuListView.as_view(), name='menu-list'), url(r'^(?P<slug>[\w-]+)/', MenuUpdateView.as_view(), name='menu-detail'), ] In the templates I get the objects via: <li><a href='{{obj.get_absolute_url}}'> {{obj}} </a></li> Which I have defined in the respective models: def get_absolute_url(self): return reverse('restaurants:menu:menu-detail', kwargs={'slug': self.slug}) and def get_absolute_url(self): return reverse('restaurants:menu:menu-list', kwargs={'slug': self.slug}) So the resulting pattern at the end is: restaurants/(?P<slug>[\w-]+)/menus/(?P<slug>[\w-]+)/ How can I fix it so that I don't get the error anymore? -
Django Model Form Set POSTs But Does Not Save
I have a Django site built on a model formset (forms.py). The model formset is picked up by my view (views.py). The view is rendered in my template (alerts.html). The user sees a list of alerts with entity and logic populated. They must enter a comment on one or more forms in the formset and then click the submit button to post the one or more forms to the DB. When the submit button is clicked currently, the page refreshes, but the data is not submitted to the DB. No error appears, and the data (i.e. text typed into the comment field) remains. How should I alter my project to allow the model formset to be saved appropriately? forms.py class AlertForm(ModelForm): class Meta: model = Alert fields = [ 'entity', 'logic', 'comment' ] AlertFormSet = modelformset_factory(Alert, extra=0, exclude=(), form=AlertForm) views.py def alerts(request): newAlerts = Alert.objects.filter(disposition='') formset = AlertFormSet(request.POST or None, queryset=newAlerts) context = {'formset':formset} if request.method == 'POST': formset = formset if formset.is_valid(): formset.save() else: formset = formset return render(request, 'alerts/alerts.html', context) alerts.html <form method='POST' action=''> {{ formset.management_form }} {% csrf_token %} <input name="submit" value="Submit" id="submit-id-submit" type="submit"> {% for form in formset %} {% for hidden_field in form.hidden_fields %} {{ … -
Django isnull query with mysql datefield not working
I have model class similar to this: class Manager(models.Model): employee = models.ForeignKey(Employee) manager_id = models.ForeignKey(db_index=True,max_length=20) start_date = models.DateField(blank=True, null=True) end_date= models.DateField(blank=True, null=True) The records are being stored in mysql db. When i use the query to fetch manager records whose end time is not yet set: Manager.objects.filter(end_time__isnull=True) it return zero records. However, Manager.objects.all()[0].end_time==None returns True in Django shell The entries in the database are also stored as '0000-00-00' How can i query to get Manager records whose end time is not yet set.? -
Show management commands in admin site
Maybe I am just naïve in my expectations, but I cannot find any simple configuration or app that would allow running a Django project's management commands from the admin interface. Surely allowing commands to be executed remotely without having to shell to the machine is a pretty common thing? Do you always have to implement it yourself? If so, how do you add to the existing admin site without replacing it entirely? -
Parse Django REST API response with Angular 4
I've built a Django REST API using the Django Restapiframework, and it uses a serializer to return a json response: from rest_framework import serializers from .models import WeatherStatistics class WeatherStatisticsSerializer(serializers.ModelSerializer): class Meta: model = WeatherStatistics fields = '__all__' In my Angular 4 front-end project I have a service: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class WeatherstatsService { constructor(private http:Http) { console.log("Hello World"); this.getWeatherData(); // this.getWeatherDataRecords(); } weatherdata: any = {}; private _WeatherStatsUrl = 'http://127.0.0.1:8000/weatherstats/weatherdata'; getWeatherData() { return this.http.get(this._WeatherStatsUrl) .map((res:Response) => res.json); } getWeatherDataRecords() { this.getWeatherData().subscribe(weatherdata => { console.log(weatherdata) }) } } And I also have a component that uses that service: import { Component, OnInit } from '@angular/core'; import { WeatherstatsService } from '../weatherstats.service'; @Component({ selector: 'weather-stats', templateUrl: './weather-stats.component.html', styleUrls: ['./weather-stats.component.css'] }) export class WeatherStatsComponent implements OnInit { data: any; constructor(private weatherstatsservice: WeatherstatsService) { } ngOnInit() { this.data = this.weatherstatsservice.getWeatherData(); } } At the moment all I want it to do is log the json data from my api to the console oninit. So far tho, it does nothing. How do I get the json from Django into Angular? -
Django ListView with paginator: That page contains no results
I'm getting this error: That page contains no results I use CBV ListView with django-filter and simple pagination. I don't understand why I'm getting this error and, moreover, there is one item in QuerySet. I tried also append page=1 query param which raises the same error. This is my view: class UserFilterView(LoginRequiredMixin,ListView): template_name = 'frontend/userprofile_filter.html' model = UserProfile paginate_by = 5 # ordering = True # allow_empty = True def get(self,*args,**kwargs): self.filter = UserProfileFilter(self.request.GET, queryset=UserProfile.objects.all()) return super(UserFilterView,self).get(*args,**kwargs) def get_queryset(self): return self.filter.qs def get_context_data(self, **kwargs): context = super(UserFilterView,self).get_context_data(**kwargs) context['filter_form'] = self.filter.form return context I know that there is something wrong with paginator but I don't know what. Do you know? -
Using TaggableManager for m2m relationship in django
I am trying to use TaggableManager() to add tags in my form in django application but this does not seem to work. class UserBookmark(models.Model): user = models.ForeignKey(User) bookmark = models.URLField() tag = TaggableManager() def __str__(self): return '%i %s %s'%(self.id,self.user,self.bookmark) my html template: <div class="modal-body"> <form name = "form2" id = "form2" method = "post" action = "{% url 'savetag' %}" class = "form-inline"> {% csrf_token %} <div class = "form-group"> <input name = "tag" id = "tag" required> <input type="hidden" id = "field1" name="bookmark" value=""> <button type = "submit" class = "btn btn-danger">Save</button> </div> </form> </div> when i hit this query UserBookmark.objects.filter(tag__name__in = ['java']) i get empty set, while i do have records with this tag java. earlier my UserBookmark model was like this: class UserBookmark(models.Model): user = models.ForeignKey(User) bookmark = models.URLField() tag = models.CharField(max_length = 100) but this did not work because tag had a many to many relationship as a bookmark can have many tags, so CharField did not work. Can someone tell me what needs to be corrected here? -
Why we need <input> tag with object primary key and action_checkbox_name in django admin template?
Here is HTML page, which is Django admin template. It has a hidden input tag with value equals to subject primary key (pk). Why it is not working without that input? {% extends "admin/base_site.html" %} {% load i18n l10n %} {% block content %} <form action="" method="post">{% csrf_token %} <p>Choose tutor Subject:</p> <select title="selected_subject" name="selected_subject"> {% for sub in subjects %} <option type="hidden" name="subject" value="{{ sub }}">{{ sub.name }}</option> {% endfor %} </select> <p> {% for obj in queryset %} <input type="hidden" name="{{ action_checkbox_name }}" value="{{ obj.pk }}" /> {% endfor %} </p> <p> <input type="hidden" name="action" value="{{ return_method }}" /> <input type="hidden" name="send" value="yes"/> <input type="submit" value="Select subject" /> </p> </form> {% endblock %} -
How to keep track of price changes and different prices for different customers in Django
In my Django project, I need to have products, prices and customers. One product can belong to many customers and have a different price for each of them. The price also needs to be updated over time. How can I keep track of price changes? Inside the view 'product history' I need to be able to see what was the original price and all the following changes to the price (with their related date of change). How should I model the entire customer - product relationship? Considering that the same product can belong to different customers and have a different price for each. models.py class Product(models.Model): sku = models.CharField(max_length=20) name = models.CharField(max_length=50) description = models.CharField(max_length=200) class Price(models.Model): product = (this links with a ManytoMany to Product) price = (most recent price) date = (date most recent price was entered on) class Customer(models.Model): product = (this links with a ForeignKey to Product) price = (this links with a ForeignKey to Price) How would you model it? Thank you in advance for your insights!