Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Same username and email for django user?
I'm making a django website using the django-registration package. I'd like for users to register with their emails and have no username so that i can then have an interface with their actual names (like on facebook) and keep track of them through their email. I will need a user profile and plan to extend the user model with a oneToOne field later on but for now I'm not sure how to use their email as username. I figured i could simply ask the user for their email and also store it as a username and that would be a simple fix. However it will require me modifying all the forms and will create essentially duplicate column in the database (email = username). This question is really open ended, I'd like to know if there's an easy way of changing the user model mid project. I've read the docs about the User(AbstractUser) class but that seems to be good only if we just started the project. Thanks, any help will be appreciated. -
APNS_CERTIFICATE - Push Notification does not send in production
I've had this issue for about 2 weeks, when I suddenly stopped sending notifications in production. I am using the django-push-notifications library and by django admin I can send a test message, but it does not send messages through the system. On my local computer, everything works flawlessly. I discovered a command to test the certificate: openssl s_client -connect gateway.push.apple.com:2195 -cert apns-cert.pem With this one I had the return: Timeout: 7200 (sec) Verify return code: 20 (unable to get local issuer certificate) Extended master secret: yes So with a lot of research, I discovered that I needed to put the path of "CA": openssl s_client -CApath /etc/ssl/certs/ -connect gateway.push.apple.com:2195 -cert apns-cert.pem Who was taking me to: Verify return code: 0 (ok) However, for use in the library, I needed to put the full path of a .pem file. Then I found this command: ls /etc/ssl/certs/Entrust* I tested all the .pem files that were there, until I reached what appeared to have worked perfectly: openssl s_client -CAfile /etc/ssl/certs/Entrust.net_Premium_2048_Secure_Server_CA.pem -connect gateway.push.apple.com:2195 -cert apns-cert.pem Soon, I formatted my PUSH_NOTIFICATIONS_SETTINGS: PUSH_NOTIFICATIONS_SETTINGS = { "GCM_API_KEY": "xxxx", "APNS_CERTIFICATE": os.path.join(BASE_DIR, "apns-cert.pem"), "APNS_CA_CERTIFICATES": "/etc/ssl/certs/Entrust.net_Premium_2048_Secure_Server_CA.pem", "APNS_ERROR_TIMEOUT": 3, } IOS_VERIFY_RECEIPT_API = 'https://buy.itunes.apple.com/verifyReceipt' ANDROID_VERIFY_RECEIPT_API = 'https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/purchases/subscriptions/{subscriptionId}/tokens/{token}' Unfortunately it still does not … -
django login users and display their instance and items in the database
I have couple of models and one of them is a foreign key to the user model that's extending django admin. I want to display what belongs to a user in their session upon login. I have defined this authentication that will check whether a particular user exist within the database and redirect them to their session with their instances. def auth_view(request): username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HttpResponseRedirect('/studentloggedin/') Basically, Registration is the first model and a foreign key to Student model, while Student is also a foreign key to UserLog. UserLog is extending the default django admin. I've defined the loggedin session here to filter out details of the individual users upon login. def studentloggedin(request): registration = Registration.objects.all() students = Student.objects.filter(registration=registration) alluser = UserLog.objects.filter(student=students) context = { 'registration': registration, 'students': students, 'alluser': alluser, } return render(request, "studentloggedin.html", context) Here is the template rendering the information upon login. <img {% for student in students %} src="{{ student.student_photo.url }}"> <p>{{ student.previous_school }}</p> {% endfor %} But I'm getting the below error: ProgrammingError at /studentloggedin/ more than one row returned by a subquery used as an expression -
Django model design for tennis league
To learn web development, I'm developing a web app to help me manage our local tennis doubles league. We play once weekly, and it works like this: Based on their rank, players are assigned to a court each week. The four players on each court play three Sets, changing partners for each Set. A team wins a Set by winning 6 games: Set 1: Players 1 & 4 vs Players 2 & 3 Set 2: Players 1 & 3 vs Players 2 & 4 Set 3: Players 1 & 2 vs Players 3 & 4 After we finish, I evaluate the scores and recalculate each player's new rank. Here are my Django models: class Event(models.Model): event_date = models.DateField() class Player(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Set(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) team1_player1 = models.ForeignKey( Player, related_name='+', on_delete=models.CASCADE) team1_player2 = models.ForeignKey( Player, related_name='+', on_delete=models.CASCADE) team2_player1 = models.ForeignKey( Player, related_name='+', on_delete=models.CASCADE) team2_player2 = models.ForeignKey( Player, related_name='+', on_delete=models.CASCADE) team1_games_won = models.PositiveIntegerField(default=0) team2_games_won = models.PositiveIntegerField(default=0) At minimum, I have a couple of concerns: In the Set model, the Player ForeignKey attributes caused reverse accessor clashes, so I added related_name='+'. If later I decide to retrieve a player's Set history, it would be nice to do … -
DJANGO: Sort dictionary by value (and sent to a template)
I've run into the following problem: for my webapp I'm creating a page that shows how many reviews the top 10 posters users have posted on my website. (In the format Username - Number_of_reviews) The information is passed to the template as a dictionary, that is generated by the following function in view.py: def hall_of_game(request): (....) review_histogram = {} most_reviews = {} for x in Vote.objects.all(): review_histogram[x.voter] = review_histogram.get(x.voter, 0) + 1 sorted_list = [] for key, value in review_histogram.items(): sorted_list.append((value, key)) sorted_list.sort(reverse=True) return render(request, 'list/hall_of_fame.html', {(....), 'sorted': sorted_list}) The template then turns the dictionary into a ordered list <ol> {% for v, k in sorted|slice:":10" %} <li>{{ k }} - {{ v }}</li> {% endfor %} </ol> However, the moment 2 or more users have the same amount of reviews the function can no longer sort the list and it crashes, throwing a type error. TypeError unorderable types: User() < User() I tried fixing the problem by putting the moment the list is sorted in a 'try / except' loop, and though this prevents crashes this also prevents the list from being sorted. I feel like I'm ignoring the obvious but for the life of me I cannot figure … -
Django form with two submits, won't respond with the file I create
So I finally got two submit buttons working, and then I thought i could just copy the right code and put it in the right portion of the action. My views.py for this action looks like: def globe(request): if request.method == 'POST': form = EntityGlobeForm(request.POST) #two submit butotns #hidden_checkbox means they are interacting with the form if request.POST.get('hidden_checkbox'): #put items on the virtual globe if form.is_valid(): #you are going to have to make a panel and paginate footprints #object_list = ChangeDetectCSV.objects.filter(processing_level='RAW') #AND DATE sensor = form.cleaned_data.get('layer') #it is really sensor #if sensor is not object_list = CesiumEntity.objects.filter(sensor = sensor) jdata= serialize('geojson', object_list, geometry_field='mpoly', fields=('name','file_name', 'id', 'dzi_location', 'country_code', 'corner_coords', 'sensor', 'targetName', 'collection_date')) return HttpResponse(json.dumps({'data': jdata})) #the other means they clicked the download option instead else: # Create the HttpResponse object with the appropriate KML. print 'building kml' kml = simplekml.Kml() kml.newpoint(name="Kirstenbosch", coords=[(18.432314,-33.988862)]) # lon, lat, optional height response = HttpResponse(kml.kml()) response['Content-Disposition'] = 'attachment; filename="botanicalgarden.kml"' response['Content-Type'] = 'application/kml' print 'about to return response: ' + str(response) return response else: form = EntityGlobeForm return render_to_response('swsite/sw_nga_globe.html', {'form':form }, context_instance=RequestContext(request)) I did have some help here for the hacerking on that POST.get (template code here) <form action="/" method="post" id="form">{% csrf_token %} <!-- {{ form.as_table }} … -
Django - Pagination over form field
I am looking to separate a list of form fields with django. Here is what I want: Which is impossible with the usual iteration: {% for field in form %} <label> {{ field.label }} : </label> {{field}} {% endfor %} Is there any way to do what I want to do? -
GeoDjango Segmentation Fault
I have a Django App that was working greatly until I installed GeoDjango. I'm running MacOS Sierra 10.12.2 with Python 2.7.13 (installed via mac ports), Django 1.10.4 and followed GeoDjango's tutorial (homebrew). After installing the packages required for spatialite Django started having segmentation faults at random (sometimes as soon as I run python manage.py runserver, sometimes during the migrate command to update the database and sometimes after navigating a couple of pages. [29/Dec/2016 21:52:03] "GET /market/api/place/ HTTP/1.1" 200 26770 Segmentation fault: 11 Less frequently I'm getting a different error (never happened before GeoDjango): python(64613,0x7fffc85c93c0) malloc: *** error for object 0x7f84b1551608: incorrect checksum for freed object - object was probably modified after being freed. *** set a breakpoint in malloc_error_break to debug Abort trap: 6 I have no idea on how to get more informations about this problem, nor how to solve it. Any suggestions are welcome. I know this is a very broad error but how can I solve it? P.S. I've tried to reinstall XCode and all GeoDjango related packages and also tried with a new virtualenviroment with no success. -
Celery Task instanciation cache
I'm trying to cache a large resource file among tasks using Celery 4.0.2. Looking it in the documentation , I have reach with the task caching part. http://docs.celeryproject.org/en/latest/userguide/tasks.html#instantiation This can also be useful to cache resources, For example, a base Task class that caches a database connection: from celery import Task class DatabaseTask(Task): _db = None @property def db(self): if self._db is None: self._db = Database.connect() return self._db In my case I have done some changes to cache my big file resource, and the object its shared among the tasks, but the memory used by big file resource are cached in the task forever. from celery import Task class BigResourceTask(Task): _resource = None @property def resource(self): if self._resource is None: self._resource = load_big_resource() return self._resource How can I free that memory or make it expire after the execution of all the related tasks? -
graphite can't find auth_user.frm
I have graphite 0.10.0 running on CentOS 7. I had the screens populating, and data being imported from Icinga, however, when I went to add a new user, I got an error, and now graphite won't start in Apache. The error I get is long, but the key appears to be : OperationalError: (1017, "Can't find file: './graphite/auth_user.frm' (errno: 13)") The head of the traceback is: mod_wsgi (pid=7002): Target WSGI script '/usr/share/graphite/graphite-web.wsgi' cannot be loaded as Python module. [Thu Dec 29 21:30:48.254942 2016] [:error] [pid 7002] [client 172.72.77.141:52770] mod_wsgi (pid=7002): Exception occurred processing WSGI script '/usr/share/graphite/graphite-web.wsgi'. I know the file exists, in /var/lib/mysql/graphite/, and apache has permissions. I modified the STORAGE_DIR to /var/lib/mysql/graphite in the local_settings.py, but I am not sure if that was the right variable. Does anyone know the variable to fix, or what might be incorrect? -
Django not authenticating under mod_wsgi
i'm pulling my hair out for a while with this. i'm deploying my django application from the test server to an apache with mod_wsgi machine. everything seems to work except the django user authentication system it seems to write session to table django_session and somehow it does some sort of validation because when i provide wrong credentials custom error message is returned. the this is that @login_required() in views always returns false. and access to app admin page is denied. in the research i've done it may be by the lack of parameter WSGIPassAuthorization On in the apache2.conf file but it didn't work. my virtualhost file: <VirtualHost *:80> ServerName myapp.cl ServerAlias *.myapp.cl myapp.cl Alias /static /home/ubuntu/django_projects/myapp/static <Directory /home/ubuntu/django_projects/myapp/static> Require all granted </Directory> <Directory /home/ubuntu/django_projects/myapp/myapp> <Files wsgi.py> Require all granted </Files> </Directory> WSGIProcessGroup myapp WSGIDaemonProcess myapp python-path=/home/ubuntu/django_projects/myapp WSGIScriptAlias / /home/ubuntu/django_projects/myapp/myapp/wsgi.py process-group=myapp application-group=%{GLOBAL} </VirtualHost> and my url_file: rom django.conf.urls import url, include from django.contrib import admin from . import views as views_ini from django.contrib.auth.views import login, logout, password_change, password_change_done from myapp.views import aviso_sistema, inicio, LoginForm urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/$', login, {'template_name': 'loginrex.html', 'authentication_form': LoginForm, }, name='django.contrib.auth.views.login'), url(r'^logout/$', logout, {'next_page': '/login'}, name='logout'), # ....Avisos del sistema url(r'^aviso_sistema/(?P<titulo>[\w\ ]+)/(?P<detalle>[\w\ ]+)/(?P<tipo>[\w\ ]+)$', aviso_sistema, … -
Django Test set attribute and access it in different methods
I have a django test that looks like this: class APITests(APITestCase): # APITestCase is a django rest framework wrapper for a regular django test def setUp(self): self.token = "" self.fixtures = ['tests/testdata.json'] def test_client_register(self): .... self.token = response.json()["token"] # at this point, self.token is not "" def test_auth_token_verify(self): body = { "token": self.token # <-- At this point, self.token is "", why?? } response = self.client.post(reverse("misuper:api_token_verify"), body, format="json") How can I solve this? I need to set an attribute on the test class ("token") that should be populated one test and could be used in the subsequent tests. -
Creating thumbnail from a PIL video frame using Python
I have a function that i'm trying to use to save a image to S3, save_to_image, which expects a base64 encoded image (upload). Now i'm trying to re-use the same function to upload an image taken from a video.How do you convert a PIL `Image` to a Django `File`? The problem is that i'm unable to pass the image data properly, (see the function and log output below. def save_video_thumbnail (video_file): container = av.open(video_file) for i, frame in enumerate(container.decode(video=0)): if i is 5: print 'image' thumb = frame # Create a file-like object to write thumb data (thumb data previously created # using PIL, and stored in variable 'thumb') thumb_io = StringIO.StringIO() #thumb.save(thumb_io, format='JPEG') thumb_img = thumb.to_image() thumb_img.save(thumb_io, format='JPEG') print 'thumb_img' print thumb_img # Create a new Django file-like object to be used in models as ImageField using # InMemoryUploadedFile. If you look at the source in Django, a # SimpleUploadedFile is essentially instantiated similarly to what is shown here #thumb_file = ContentFile(thumb_io.getvalue()) thumb_file = InMemoryUploadedFile(thumb_io, None, 'foo.jpg', 'image/jpeg', thumb_io.len, None) print 'thumb_file.read()' print Image.open(thumb_file) image_data, image, image_thumb, si_compatible = save_to_image(thumb_file.read()) break Log Output image thumb_img <PIL.Image.Image image mode=RGB size=406x720 at 0x10B6082D8> thumb_file.read() Error uploading video(s): cannot identify image file … -
uWSGI works directly from command line but not with .ini file
For this project, I'm using Python with Django, NGinX and uWSGI. When running the server configuring the parameters directly in the command line as follows, it works fine, but it does not work when using the .ini file. Also in my NGinX configuration, I do have a uwsgi_pass (below) command: uwsgi --socket ifbAMPdatabase/ifbAMPdatabase.sock --module ifbAMPdatabase.wsgi --chmod-socket=666 .ini file: [uwsgi] project = ifbAMPdatabase base = /home/ampdbvenv/ifbAMPdb home = %(base)/pyVenvIFBAMPDB/ chdir = %(base)/%(project)/ #module = %(base)/%(project).wsgi module = %(project).wsgi:application wsgi-file = %(base)/%(project)/wsgi.py master = true processes = 4 socket = %(base)/%(project)/%(project).sock chmod-socket = 666 vacuum = true ; plugins=python enable-threads = true uid = www-data gid = www-data log-date = true OBS: Some of this parameters I added just for testing, but they didn't change a thing (it wasnt working with a simple .ini file like in the documentaton). nginx site file: location / { uwsgi_pass django; include /etc/nginx/uwsgi_params; } -
ajax - Ajax code not executing
I am learning Ajax and I ran into a little problem. I'm trying to submit a POST request to a django backend with ajax. EVEN the alert won't show up on the screen. And as I see in the test django server shell, it doesn't even submit the POST request. The code: <script type="text/javascript"> $('#btnLike').on('click', function(event) { alert('ok'); $.ajax({ type: 'POST', url: 'http://127.0.0.1:8000/backend/website/like', /* for testig */ data: { csrfmiddlewaretoken: {% csrf_token %}, post_id = $('#post_id').val(), }, }); }); </script> The HTML form: <form onsubmit="return false"> {% csrf_token %} <input type="text" name="post_id" value= {{post.pk}} hidden="hidden"> <button type="submit" name="btnLike" class="btn btn-info">Like</button> </form> I know i'm doing something horribly wrong but I don't know what. -
Django relative import of project settings causing errors in moved manage.py file
Following the directory structure in the answer here: Best practice for Django project working directory structure Reviewed the code on GitHub here to troubleshoot: django-start-template I moved the manage.py into a scripts directory. I modified the manage.py and wsgi.py to have these lines: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings") Instead of the default: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj_dir.settings") Which I think is basically equivalent. Anyway, this is the error I get when I run python manage.py runserver: File "C:\Users\ISH~1\DJANGO~1\lib\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 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named '{{ project_name }}' I have tried using relative imports, but really not getting anywhere to resolve the issue. Being a newb, I am sure the answer is pretty obvious, but I have spent a few hours reading … -
Bokeh with Django can't seen in website
In views.py from django.shortcuts import render from django.template.loader import get_template from django.http import HttpResponse from bokeh.plotting import figure, output_file, show from bokeh.embed import components # Create your views here. def homepage(request): template = get_template('index.html') plot = figure() plot.line([1,2,3,4,5],[5,4,3,2,1]) script, div = components(plot) html = template.render(locals()) return HttpResponse(html) In the templates/index.html i use the bokeh to generate the following code: <div class="bk-root"> <div class="plotdiv" id="a3a4c265-dec8-4057-b9ed-d39afda33e2d"></div> </div> And when i use the {{div | safe}} But the result show nothing how should i do to make the graphic show? -
Python class constructor not working, too many arguments given
I didn't write "Django" in the test cause I don't think it is relevant. I have a Django Test that starts like this: class APITests(APITestCase): def __init__(self): self.token = "" self.fixtures = ['tests/testdata.json'] super(APITests, self).__init__() It doesn't work, it gives me the error: TypeError: init() takes exactly 1 argument (2 given) Could anyone explain me why? how can I solve this? -
Django Shell in Eclipse not starting
I am getting this error message when I try to run the shell from Eclipse Neon while I can successfully run the Django shell from command window. I am using Python 3.4 and Django 1.10. Any idea where the problem is? -
How to mimize number of url defintiions in Django?
In Django you create a URL for a link/end point in your website. My question if you are creating something with a lot of links say a blog app you can literally have hundreds or thousands. Assuming the links have no parameters that is the url does not capture input then such Django apps will need to device a way to utilize a database to minimize url definition. Does anybody can think a more efficient solution? -
Cannot get multiple submit buttons to work in django form
I saw this here: How can I build multiple submit buttons django form? Which I tried to mimic in my own code (I think I am not understanding the request.POST object very well) Snippet from views.py: def globe(request): if request.method == 'POST': #for key, value in request.POST: # print (key,value) if 'LoadLayer' in request.POST: print 'LOADED LAYER' elif 'notloadlayer' in request.POST: print 'not loaded layer' else: print 'BLARG' #hits this all the time... Then the html: <form action="/" method="post" id="form">{% csrf_token %} <!-- {{ form.as_table }} --> <table> {% for field in form %} <tr><td><font color="white">{{field}}</font></td></tr> {% endfor %} </table> <input type="submit" name="submit" value="Load Entities" /> <input type="submit" name="submit" value="Export KML" /> </form> So yah none of that stuff is ever in the request.POST object (I have in comments where I tried to print out the items in the dictionary and it never printed too many things it said or some such error). Not sure what part i'm missing or doing wrong? -
How can I get a random value of a list of objects using custom filters?
I'm trying to get a single random object in a list of objects directly on my template. Here is an example of what I am trying to do : views.py goes like this : Font.objects.all() template file : {% for f in Fo.checkbox.all %} #f|random_choice doesn't work here. <p>{{ f.font_name|random_choice }}</p> #gives me a single random character of each object. {% endfor %} the example above gives me a single random character of each object in list, but I'm trying to get a random object in the list of object. here is the templatetag file : @register.filter(name='random_choice') def random_choice(l): return random.choice(list(l)) How can I do it ? -
Registering with Django not working
I have to create a website for a project and I encountered a problem with registering a simple user with Django : It seems that the data from the register form are not saved in the database. It would be nice if someone knew what I did wrong (I am a beginner with Django) because I can't seem to find where the problem is from. Here are my files : models.py : from django.db import models # Create your models here. class Utilisateur(models.Model): pseudo = models.CharField(primary_key=True, max_length=100) password = models.CharField(max_length=50) nom = models.CharField(max_length=200) prenom = models.CharField(max_length=200) ACCOUNT_CHOICES = ( ("U", "Utilisateur"), ("H", "Historien"), ("F", "Famille"), ) compte = models.CharField( max_length=1, choices=ACCOUNT_CHOICES, default="U" ) dateNaissance = models.DateField(null=True, blank=True) SEXE_CHOICES = ( ("M", "Masculin"), ("F", "Féminin"), ) sexe = models.CharField( max_length=1, choices=SEXE_CHOICES, default="?" ) email = models.EmailField(max_length=254) views.py : from django.shortcuts import (render, render_to_response, redirect) from .forms import UtilisateurInscriptionForm from django.core.context_processors import csrf from django.contrib.auth import (authenticate, login) def inscription_view(request): title = "Inscription" form = UtilisateurInscriptionForm(request.POST or None) if form.is_valid(): new_user = form.save() new_user = Utilisateur( pseudo = form.cleaned_data['pseudo'], password = form.cleaned_data['password'], compte = form.cleaned_data['compte'], email = form.cleaned_data['email'] ) new_user.set_password(password) #we save the user in the database new_user.save() #We check is the … -
django-forms not rendering errors
I'm having issues rendering errors in my form, when the form is invalid, it just reloads the page and the errors don't show. I want to show the errors, like showing a text saying that the email is invalid, or that the phone number contain invalid characters Here's my code: views.py def contact(request): form_class = ContactForm if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): contact_name = request.POST.get( 'contact_name' , '') contact_email = request.POST.get( 'contact_email' , '') contact_phone = request.POST.get( 'contact_phone' , '') form_content = request.POST.get( 'content' , '') # Email the profile with the # contact information template = get_template('contact_form.txt') context = Context({ 'contact_name': contact_name, 'contact_email': contact_email, 'contact_phone': contact_phone, 'form_content': form_content, }) content = template.render(context) email = EmailMessage( "Novo contato pelo site", content, "email@gmail.com", ['myemail@hotmail.com'], headers={'Reply-To': contact_email} ) email.send() print(form.cleaned_data) else: print(form) forms.py class ContactForm(forms.Form): contact_name = forms.CharField(max_length=150, label="Nome", required=True,) contact_email = forms.EmailField(max_length=150, label="Email", required=True,) contact_phone = forms.RegexField(max_length=12, label="Fone", required=False, regex=r'[0-9]+',) content = forms.CharField(max_length=10000, required=True, widget=forms.Textarea,) def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'id-form' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_action = '' self.helper.add_input(Submit('submit', 'Submit')) self.fields['contact_name'].label = "Name:" self.fields['contact_email'].label = "Email:" self.fields['contact_phone'].label = "Phone:" self.fields['content'].label = "Message:" def clean(self): cleaned_data = super(ContactForm, self).clean() contact_name … -
Django-tables2 renders same first and last row
I have a weird problem with Django-tables2. I've created a simple table with two columns - timestamp and description. The problem is that the first object from QuerySet is not being rendered in the table. Instead of first object, there is last object copied in this row. Now I'm populating this table with Action objects. MODEL class Action(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='actions') description = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __unicode__(self): return u"{} - {} {}".format(self.user, self.timestamp, self.description) VIEW @decorators.is_authenticated_or_homepage def dashboard(request): print Action.objects.filter(user=request.user) recent_actions_table = RecentActionsTable(Action.objects.filter(user=request.user)) context = {'user': request.user, 'recent_actions_table':recent_actions_table} return render(request, 'main_app/dashboard/index.html', context=context) TABLE class RecentActionsTable(tables.Table): class Meta: model = Action fields = ('id','timestamp','description') attrs = {'id': 'id_recent_actions_table', 'class': 'table', } As you can see, I've printed the queryset before creating a table: <QuerySet [<Action: futilestudio - 2016-12-29 16:15:33.299000 New product created (6)>, <Action: futilestudio - 2016-12-29 16:53:29.534000 Manual scan of product>, <Action: futilestudio - 2016-12-29 17:05:38.215000 Manual scan of product>, <Action: futilestudio - 2016-12-29 17:27:05.462000 New product created (7)>]> The first object is not in the table. Instead, there is duplicated object with ID 5. Do you have any ideas what's wrong?