Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
javascript array object doesn't work with Hicharts when defined through jinja (Django 2.0)
I want to use data passed through a django (2.0) view to my html template - but in JavaScript. I need it to plot an area chart with Highcharts. This is the code context = { 'values': butler.serve(progress) #this works fine } return render_to_response('appfolder/charts.html', context) #this works fine too And this is the charts.html file <script> var values_data = "{{ values }}"; console.log(values_data); //output works </script> <script src="https://code.highcharts.com/highcharts.js"></script> <script src="https://code.highcharts.com/modules/exporting.js"></script> <script src="{% static 'appfolder/js/charts/icam/progress.js%}"</script> and this is my progress.js file Highcharts.chart('container', { chart: { type: 'area' }, title: { text: 'Progress' }, subtitle: { text: 'Source: <a href="http://example.com">' + 'empty for now</a>' }, xAxis: { allowDecimals: false, labels: { formatter: function () { return this.value; // clean, unformatted number for year } } }, yAxis: { title: { text: 'Nuclear weapon states' }, labels: { formatter: function () { return this.value / 1000000 + 'mn'; } } }, tooltip: { pointFormat: '{series.name} churned out USD <b>{point.y:,.0f}</b><br/>million in revenue in {point.x}' }, plotOptions: { area: { pointStart: 2015, marker: { enabled: false, symbol: 'circle', radius: 2, states: { hover: { enabled: true } } } } }, series: [{ name: 'Company', data: values_data }] }); console.log(values_data); //output also works But when … -
How to make Django validators dynamic?
I am new to Django. I am taking over a Django project developed by someone else. They took the basic form validators from here: https://docs.djangoproject.com/en/2.0/topics/auth/passwords/ So if I open settings/common.py I see: AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 9, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] My project manager is telling me that she wants these validators to happen while a person is typing, rather than when the form is submit. So I need to somehow make these validators trigger onBlur as the cursor leaves each field. How is this done in Django? -
django - key error in serializer with foreign key models
I checked out all related questions but still curious to know if there exist an updated answer . django serialize foreign key objects So , I have a model which has three foreign keys , next when I am trying to GET a response using that model , they keys in List is appended with "_id" - so whenever I am serializing , I am getting the "KeyError at" error. Error : KeyError at /api/v1/user/skill/upvotes/1 'skill' Model : class UserSkillUpvotes(models.Model): unique_together = (('user_skill', 'upvote_by'),) skill = models.ForeignKey('Skill',on_delete=models.CASCADE , related_name='all_upvote_for_user_skill') upvote_by = models.ForeignKey('auth.User',on_delete=models.CASCADE , related_name='all_upvote_by_user') upvote_for = models.ForeignKey('auth.User',on_delete=models.CASCADE , related_name='all_upvote_for_user') Serializer : class UserSkillUpvotesSerializer(serializers.ModelSerializer): class Meta: model=UserSkillUpvotes fields='__all__' View : if request.method == 'GET': try: user_skill_upvotes = list(UserSkillUpvotes.objects.filter(upvote_for=pk).all().values()) # get all upvotes on skills of the requested user except (UserSkillUpvotes.DoesNotExist,User.DoesNotExist) as e: return HttpResponse(status=404) serializer = UserSkillUpvotesSerializer(user_skill_upvotes,many=True) return Response(serializer.data) Console error - File "C:\code\django\wantedly\src\wantedly_webapp\views\AllViews.py", line 75, in user_skill_upvotes return Response(serializer.data) -
How to transfer logs from centOS to Hadoop Server usign flume without repeating?
I need some help with flume configuration. I have a CentOS server where Django logs are generated over there. I want to read those logs and transfer it to another server. I have 2 configurations available one with one server and another with another server. The issue i am getting is i have used exec command tail -f in config. It is successfully transferring logs from CentOSto Hadoop server.The issue i am facing is the log generating in CentOS is single but when its been transferred to Hadoop Sever its copying twice in it. Can any one help me in this issue. What is the wrong i am doing. Thank you Config in CentOS Server: # configure the agent agent.sources = r1 agent.channels = k1 agent.sinks = c1 # using memory channel to hold upto 1000 events agent.channels.k1.type = memory agent.channels.k1.capacity = 1000 agent.channels.k1.transactionCapacity = 100 # connect source, channel, sink agent.sources.r1.channels = k1 agent.sinks.c1.channel = k1 # cat the file agent.sources.r1.type = exec agent.sources.r1.command = tail -f /home/bluedata/mysite/log/debug.log # connect to another box using AVRO and send the data agent.sinks.c1.type = avro agent.sinks.c1.hostname = x.x.x.x #NOTE: use your server 2s ip address here agent.sinks.c1.port = 9049 #NOTE: This port … -
Django form forms.ModelChoiceField()
I am using forms with the following: class InvoiceModelForm ( forms.ModelForm ): u = forms.ModelChoiceField ( queryset = User.objects.all () ) But in the form field it is displaying the username. I would like to change that to use the first and last names. I do not want to change the def __str__(self): return self.username How can I change what values are displayed in the form field? Thanks. -
User input associates to photo
Working on a blog, where users can create new posts and input a keyword to have a picture associated with that keyword provide a photo for the post. For example: 1) User inputs keyword: 'Pizza' 2) The form page that the user is on either: a) uses that keyword to provide an image associated with it or b) uses that keyword to provide a couple images that the user can then choose from for the image for the post 3) The selected image is then associated with that post Does anyone have suggestions on how to implement this? I'm keen to work on it, but can't even think where to start. Is there a google images plugin that i could use? Or any sample codes? -
forms select2 POST is empty
I'm seeking guidance to get me going in the right direction. My professor is at a loss. I'm having issues with the POST in my form for the select2 multiple fields. I have a Yes/No flag, that determines which select 2 select option to show. The javascript below works great for the show/hide. $(document).ready(function () { $('#option').change(function () { $this = $(this) $('.select_box').each(function () { $select = $('select', this); if ($select.data('id') == $this.val()) { $(this).show(); $select.show().select2(); } else { $(this).hide(); $('select', this).hide(); } }); }); }); My form has a Yes/No/NA option, which dictates what select 2 box to show using the javascript above. <select name ="option" class="form-control " id="option"> <option value="1"> Yes</option> <option value="0"> No</option> <option value="2"> N/A</option> </select> My form POST is handled with the general POST option as shown below: <form action = "{% url 'final' %}" form method = "POST"> Inside my form I have the .select_box div class. The select 2 option gives the correct fields and populates the multi-select correctly. <div id = "div_yesselect" class="select_box"> <script src= "{% static '/accounts/option_select2.js' %}" type="text/javascript"></script> <select data-placeholder="Please select your course(s)?" data-id="1" class="js-example-basic-multiple" multiple="multiple" id = "id_courseselect" value = "{{course.id}}" style="width: 1110px" > {% for course in courses%} … -
Django URL keeps being longer
I am new to django and I am working on url redirects. On my views I am using HttpResponseRedirect and render functions to switch views. The problem is after couple of switching around between views, the URL keeps getting longer. Here is the URL on the chrome after I switched between addcostumer and delete costumer views http://127.0.0.1:8000/interface/addcostumer/deletecostumer/addcostumer/deletecostumer/preview/preview/addcostumer/deletecostumer/ How do I make the URL just http://127.0.0.1:8000/interface/addcostumer/ when I am in addcostumer view and http://127.0.0.1:8000/interface/deletecostumer/ when I am in deletecostumer view insted of them being appended one after another whenever I switch between views. class AddCostumerView(FirstPageView): def __init__(self): super() self.main_template = "addcostumer.html" def get(self, request): form = CostumerForm() return render(request, template_name=self.base_template, context={"company_list": list(database.get_companies()), "sister_page": self.main_template, "form": form}) @method_decorator(csrf_protect) def post(self, request): print("this line is running now") form = CostumerForm(request.POST) if request.FILES["myfile"]: myfile = request.FILES["myfile"] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) if form.is_valid(): data = form.cleaned_data #database.add_costumer(**data) #preview the data and preview the file #Add for final submission #messages.success(request, filename) return HttpResponseRedirect("preview/") # TODO change to proper page return HttpResponseRedirect("firstpage.html") class DeleteCostumerView(FirstPageView): def __int__(self): super() self.main_template = "deletecostumer.html" def get(self, request): companies = database.get_companies() print("delete get request") return render(request, template_name= self.base_template, context={ "company_list": companies, "sister_page" : "deletecostumer.html", "form": DeleteForm(), }) def post(self, … -
DRF - How to Authentify an application with Oauth Toolkit?
In my application, I use a modified User model with 3 more field that I need. from django.contrib.auth.models import AbstractUser from django.db import models import ldapdb.models class User(AbstractUser): cotisant = models.BooleanField(default=False) nbSessions = models.IntegerField(default=0) tel = models.CharField(max_length=20, default="") I want people to be able to change their accounts settings, (like their password, email, tel,...). To do so I have a serializer like this : from rest_framework import serializers from django.contrib.auth.hashers import make_password from coreapp.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password', 'cotisant', 'tel') extra_kwargs = { # Allow to set pwd, but disallow getting the hash from BDD 'password': {'write_only': True} } def validate_password(self, value: str): return make_password(value) And a view like this : class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer permission_classes = (IsSelfOrStaffPermission, TokenHasReadWriteScopeOrCreate,) lookup_field = 'username' def get_queryset(self): current_user = self.request.user if current_user.is_staff: user_set = User.objects.all() else: user_set = User.objects.filter(username=current_user.username) query = self.request.query_params.get('q', None) if not query: return user_set return user_set.filter( Q(username__icontains=query) | Q(first_name__icontains=query) | Q(last_name__icontains=query) ) (This allow access to a user only to himself, unless he is staff) The problem is, to update nbSessions parameter, the user have to pay something on one of my apps. How can I … -
Django 2.0 URL regular expressions
I'm trying set an offset but I want to limit it to a maximum of 99 hours by only allowing either one- or two-digit numbers but I'm not sure of the syntax to use with Django 2.0. I've tried to look for updated documentation but I can't find it, maybe I missed it but I did look before posting here. Here is the code in my views.py file: # Creating a view for showing current datetime + and offset of x amount of hrs def hours_ahead(request, offset): try: offset = int(offset) except ValueError: # Throws an error if the offset contains anything other than an integer raise Http404() dt = datetime.datetime.now() + datetime.timedelta(hours=offset) html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt) return HttpResponse(html) Here is the code from my urls.py file, this allows me to pass an integer but I want to limit this to 1- or 2- digit numbers only: path('date_and_time/plus/<int:offset>/', hours_ahead), I've tried path(r'^date_and_time/plus/\d{1,2}/$', hours_ahead), but I get the Page not found (404) error. Thanks in advance! -
Restricting all the views to authenticated users in Django
I'm new to Django and I'm working on a project which has a login page as its index and a signup page. The rest of the pages all must be restricted to logged in users and if an unauthenticated user attempts to reach them, he/she must be redirected to the login page. I see that @login_required decorator would make a single view restricted to logged in users but is there a better way to make all the views restricted and only a few available to unauthenticated users? -
How to access one to many relationship after bulk_create in Django
I have a problem with accessing bulk inserted one-to-many relationship objects using bulk_create. Here is my code: My models: class Person(models.Model): # ... other fields class Post(models.Model): person = models.ForeignKey(to=Person, related_name="posts") text = models.CharField(max_length=100) # ... other fields Now I want to insert thousands of posts for a person. I'm doing it as follows: person = Person(foo="bar") person.save() posts = [Post(person=person, text="post1"), Post(person=person, text="post2")] person.posts.bulk_create(posts) # Now I want to have an access to the person.posts and pass it to a serializer return PostSerializer(person.posts.all(), many=True).data When I execute, it doesn't populate the relationship => it's empty. I want to perform this without additional query to the database. Is that possible? -
Django: Using Template Tags with ckeditor
I'm using RichTextUploadingField from the ckeditor package for django for my flat pages. I need to insert some urls but I don't want to hardcode them as I'd like to be able to change the urls in the future. If I could do this by using django template language in ckeditor it would be great but I'd be happy just to soft code the urls into the field. -
Django foreign key and one-to-many relationship
I'm trying to build a basic ecommerce website, as a mean to learning django. I'm trying to build my models, so that there is a Category, a Product and Product Image class to store my data in. This is my models.py: class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name', ) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('products:product_list_by_category', args=[self.slug]) class Product(models.Model): category = models.ForeignKey(Category, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ('name', ) index_together = (('id', 'slug'), ) def __str__(self): return self.name def get_absolute_url(self): return reverse('products:product_detail', args=[self.id, self.slug]) class ProductImage(models.Model): property = models.ForeignKey('Product', related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to='products') And this is my views.py: def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) product_img = Product.images.all() if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'products/list.html', {'category': category, 'categories': categories, 'products': products, 'product_img': product_img}) I've seen similar post here on stack overflow, and have tried to do the same thing, but I still get the following error: AttributeError: 'ReverseManyToOneDescriptor' object … -
Create model admin page without create table python
I'm new to Django and Python and am starting to develop a CMS with this technology with Django CMS. I need to create a model admin page to manage my lots entity, but i will not have this entity in my database. Basically i will display all entities of lots in the index list consuming an other service like a request. And this is the idea for the other CRUD's. When create, update, delete i will consume a service to make this operations with the respective entity. For this i will override the CRUD methods of admin.ModelAdmin. There is a why to do that? I looked everywhere but without answers. This is what i already have. In my admin.py from django.contrib import admin from cms.extensions import PageExtensionAdmin from .models import LoteDestaque from .models import LoteDestaqueTest # from myproject.admin_site import custom_admin_site @admin.register(LoteDestaqueTest) Here is my models.py from .servicos.lotes import * from django import forms from django.db import models from django.utils.translation import ugettext_lazy as _ from datetime import datetime from cms.models import CMSPlugin from djangocms_text_ckeditor.fields import HTMLField class LoteDestaqueTest(): lotes = lotes.buscaLotes() lote_id = forms.ChoiceField(choices=(lotes)) nome = models.CharField(max_length=150, verbose_name = _('Nome')) imagem = models.CharField(max_length=200, verbose_name = _('Imagem'), blank=True, null=True) observacoes = models.CharField(max_length=200, … -
embed video object in html using django
I am having trouble to embed a video content file from my cloud to my webpage. I am developing using Django framework Here is my code: def getfile(request): file = object.fetch() // this return the file content of video file that's stored in cloud return render(request,'index.html',{'file':file}) my HTML {% if file%} <video height='320' width='320' controls> <source src='file:'{{file}} type='video/mp4'> </video> {% endif %} with the above code i am getting an error No video with supported format and MIME type found Can anyone help me with this, Thanks in advance -
Does not display form.errors when not valid
I use UserCreationForm to render registration form in Django. class RegisterForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fields = UserCreationForm.Meta.fields The registration view is defined as follows: def register(request): form = RegisterForm() if request.method == 'POST': form = RegisterForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) return redirect('/') else: context = {'form': form} return render(request, 'registration/register.html', context) And the template for this: {% if form.errors %} <p>Some Errors occured</p> {% endif %} <form action="{% url 'register' %}" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Register"> </form> When I submit invalid data, it does not show <p>Some Errors occured</p>, but throws Exception Type: ValueError Exception Value: The view myapp.views.register didn't return an HttpResponse object. It returned None instead. which means I have to return HttpResponsein the 2nd if/else statement. The other forms work fine and show form.error messages, except this one. What is the problem? Thanks. -
Django ORM equivalent for 'or'?
I need to do this in django orm. SELECT * FROM offer WHERE country_id = 1 OR mundial = 1; How do I do the 'OR' in django like: list = offer.objects.filter(country_id=1, #HOW DO I PUT 'OR' HERE?) -
ImageField variable in Django Template
So I have looped over an object variable in the respective template in Django, every item loops over well except the image variable. I am not sure what I am doing wrong. But here are my codes: MODEL: See where I have routed the uploaded image files. class Car(models.Model): def fileLocation(instance, filename): return 'media/cars/{0}/{1}'.format(instance.agent.username, os.path.basename(filename)) make = models.CharField(max_length=100) model = models.CharField(max_length=100) year = models.IntegerField() car_registration = models.CharField(max_length=100, unique=True) insurance_exp = models.DateField(max_length=100) cost_per_day = models.IntegerField() description = models.TextField(max_length=1000) agent = models.ForeignKey(Agent, on_delete=models.CASCADE) image1 = models.ImageField(upload_to=fileLocation) image2 = models.ImageField(upload_to=fileLocation) image3 = models.ImageField(upload_to=fileLocation) image4 = models.ImageField(upload_to=fileLocation) image5 = models.ImageField(upload_to=fileLocation) available = models.BooleanField() added_date = models.DateField(default = timezone.now()) def __str__(self): return self.model VIEW: from django.shortcuts import render from .models import Car, Agent # Create your views here. def index(request): all_cars = Car.objects.all() context = {'all_cars':all_cars} return render(request, "home.html", context) TEMPLATE (home.html): {% extends 'basic.html' %} {% block content %} <div class="container"> <div class="row "> {% for car in all_cars %} <div class="col-md-8 col-md-offset-2 list-cars"> <div class="media"> <div class="media-left media-top"> <a href="#"> <img src="{{car.image1.url}}"> </a> </div> <div class="media-body"> <h4 class="media-heading">{{car.make}} {{car.model}}</h4> <p>{{car.description}} </p> <p class="price">Kshs {{car.cost_per_day}} Per Day</p> {% if car.available == True %} <button class="btn btn-success">Available</button> {% else %} <button class="btn btn-danger">Not Available</button> <button … -
How can't my django admin got no css attached?
I have followed my first django app video series on youtube and i have created admin but i am unable to get css.enter image description here What i want is thisenter image description here -
ValueError: Unable to configure handler 'file': [Errno 13] Permission denied:
Using Django 1.11 and Python 2.7. I am unable to configure handler 'file' dues to permissions. Traceback is as follows: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python2.7/site-packages/django/utils/log.py", line 75, in configure_logging logging_config_func(logging_settings) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/config.py", line 794, in dictConfig dictConfigClass(config).configure() File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/config.py", line 576, in configure '%r: %s' % (name, e)) ValueError: Unable to configure handler 'file': [Errno 13] Permission denied: '/var/log/welnity/debug.log' -
Django forms - field as plain text, CharField has no attribute 'is_hidden'
I want to have a field shown as plain text only using forms.py and have found a snippet on here to use from django.utils.safestring import mark_safe class PlainTextWidget(forms.Widget): def render(self, _name, value, _attrs=None): return mark_safe(value) if value is not None else '-' then in my forms.py I have used it as such class DeleteSiteForm(forms.ModelForm): class Meta: model = SiteData fields = ['location'] widgets = { 'location' : forms.CharField(widget=PlainTextWidget), } when I load the page I get the error: Traceback: File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/itapp/itapp/sites/views.py" in delete_site 875. from sites.forms import DeleteSiteForm File "/itapp/itapp/sites/forms.py" in <module> 136. class DeleteSiteForm(forms.ModelForm): File "/usr/local/lib/python3.6/site-packages/django/forms/models.py" in __new__ 266. apply_limit_choices_to=False, File "/usr/local/lib/python3.6/site-packages/django/forms/models.py" in fields_for_model 182. formfield = f.formfield(**kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py" in formfield 1110. return super(CharField, self).formfield(**defaults) File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py" in formfield 891. return form_class(**defaults) File "/usr/local/lib/python3.6/site-packages/django/forms/fields.py" in __init__ 228. super(CharField, self).__init__(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/forms/fields.py" in __init__ 109. extra_attrs = self.widget_attrs(widget) File "/usr/local/lib/python3.6/site-packages/django/forms/fields.py" in widget_attrs 246. if self.max_length … -
django admin for multiple user types
I've an app that deals with multiple user types. I need a way for differentiating them in the admin site. Some code to illustrate. First I created a User model class that inherits from AbstractUser class User(AbstractUser): is_partner = models.BooleanField(default=False) is_client = models.BooleanField(default=False) email = models.EmailField(unique=True) Partners and Clients users has different data: class ClientProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... class PartnerProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... Client profile is created through SignUp form I provide, after that, users can update their own profile. In the other hand, Partner profile is created by myself as admin, and I need to do it through django admin site. So, how do I register two version of the same model? and provide different names for showing in the admin index? What I did was to change just the queryset in the ModelAdmin class, and register it twice, one for Client and another for Partner but it raises me django.contrib.admin.sites.AlreadyRegistered class ClientProfileInline(admin.StackedInline): model = ClientProfile can_delete = False verbose_name_plural = 'Client Profile' fk_name = 'user' class ClientUserAdmin(UserAdmin): inlines = (ClientProfileInline, ) def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(is_client=True)#HERE it is the flag for differentiating between Client and Partner def get_inline_instances(self, request, obj=None): if … -
Pagination on results doesn't work 'afte the first page' other papes repeats the first
I have an issue with pagination in Django search.html page. After search result, the results on first page of the table is repeated on the next pages continously. For reference, this is the bit of the template that displays results: ```{% for result in page_obj.object_list %} {{ result.object.title }} {% empty %} No results found. {% endfor %} {% if page_obj.has_previous or page_obj.has_next %} {% if page_obj.has_previous %}{% endif %}« Previous{% if page_obj.has_previous %}{% endif %} | {% if page_obj.has_next %}{% endif %}Next »{% if page_obj.has_next %}{% endif %} {% endif %}``` -
Get data in model methods from multiple models - Django
I'm quite new to Django (Python too) and learning it by doing. I'm playing with Django admin site. I've created two models and successfully registered in admin. The data is nicely displayed for the fields given in list_display. I want an another table in admin, which displays data from both the tables by processing with some logic. To get the another table based on the previous two models data, I can create a new model with only methods as mentioned in this question. Now the problem is that, how can I get data from other model tables and how to return, so that it can be displayed in table in admin. Here is my models.py: from django.db import models class GoodsItem(models.Model): name = models.CharField(max_length=255) size = models.DecimalField(max_digits=4, decimal_places=2) INCHES = 'IN' NUMBER = 'NUM' GOODS_ITEM_SIZE_UNITS = ( (INCHES, 'Inches'), (NUMBER, '#'), ) size_unit = models.CharField( max_length=4, choices=GOODS_ITEM_SIZE_UNITS, default=INCHES, ) def __str__(self): if(self.size_unit == self.NUMBER): return "%s #%s" % (self.name, (self.size).normalize()) else: return "%s %s\"" % (self.name, (self.size).normalize()) class FinishedGoodsItem(models.Model): date = models.DateField() goods_item = models.ForeignKey(GoodsItem, on_delete=models.CASCADE, related_name="finished_name") weight = models.DecimalField(max_digits=6, decimal_places=3) def __str__(self): return str(self.goods_item) class SoldGoodsItem(models.Model): goods_item = models.ForeignKey(GoodsItem, on_delete=models.CASCADE, related_name="sold_name") date = models.DateField() weight = models.DecimalField(max_digits=6, decimal_places=3) def …