Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot access Localhost in android emulator
i have a django server but the app crash in the android emulator, why? it is the code: final TextView t = findViewById(R.id.textView3); RequestQueue queue = Volley.newRequestQueue(this); String url = "http://10.0.2.2:8000/"; StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // Display the first 500 characters of the response string. t.setText("Response is: "+ response.substring(0,500)); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { t.setText("That didn't work!"); } }); -
How can I set Django `Debugger` time?
The Django debugger is import pdb; pdb.set_trace(). Sometimes we push the code on the server without remove debugger from the code. In this conditions when we request the view (that views contain debugger) then the page will not load and the browser will hang because of that debugger. So my Question is. Can I set a debugger time or How can I avoid debugger after few minutes Thanks in advance -
django diffrent table data merge
models.py ex) table1(models.Model): id = primarykey content = textfield registerdate = datetimefield table2(models.Model): id = primarykey content = textfield plus1 = charfield plus2 = charfield registerdate = datetimefield i tried tb2 = table2.objects.all().values("id","content","plus1","plus2","registerdate") tb1 = table1.objects.all().annotate(plus1=Value('plus1', output_field=CharField()),plus2=Value('plus2', output_field=CharField())).values("id","content","plus1","plus2","registerdate") merge = tb2.union(tb1) tb2 values is right but tb 1 fields is strange. some times plus1 = plus1 , plus2=plus2 some times plus1 = plus2 , plus2=plus1 i want merge.count() merge.order_by("-registerdate") can i get consistent aligned field if not i can get count and order without union? -
How can I check if two models equal each other in Django?
models.py: class office_list(models.Model): name = models.CharField(max_length= 100) num_of_pax = models.IntegerField() class tg_list(models.Model): name = models.CharField(max_length= 100) num_of_pax = models.IntegerField() How can I check that the office_list name equals to the tg_list name? -
Evaluate a readonly field upon creating a new object in Djano admin
Assuming a the following model # models.py class Person(models.Model): name = models.CharField(max_length=40) birthdate = models.DateField() age = models.CharField(max_length=3) # dont mind the type, this is just an example :) The desired behavior would be to have the age field hidden while the user creates a new Person object, and evaluate its value when the user submits the form. To achieve this, I created a ModelAdmin with a custom ModelForm as follows # admin.py from django.contrib import admin from django import forms from .models import Person from dateutil.relativedelta import relativedelta import datetime class PersonForm(forms.ModelForm): def clean(self): cleaned_data = super(PersonForm, self).clean() birthdate = cleaned_data.get('birthdate') cleaned_data['age'] = relativedelta(datetime.date.today(), birthdate).years return cleaned_data class PersonAdmin(admin.ModelAdmin): form = PersonForm exclude = ('age',) admin.site.register(Person, PersonAdmin) However, after submitting the form, the age field does not get populated, possibly because it is excluded. If I remove the exclude then it works, but the form displays the age field which is not the desired behavior. -
Custom template tag for enumerate function
I want to create custom django template for enumerate function. Can you please help me how to do that. -
django-ckeditor remove image from file browser
I'm using django-ckeditor. (also django-ckeditor-uploader) (django-ckeditor github) Everything works well. But when I upload photo in file browser, I can't delete it from the server. I'm currently using AWS S3, so it's possible to delete it in S3, but it's bit inefficient way. Is there any way to remove image from file browser? (I see django-ckedior file browse template, but I can't see any code related to delete imge. here is file browse template from django-ckeditor. Thanks in advanced! -
django cache error - site displays old version sometimes
I seem to have a weirdly unique issue I can not find anything about on the web. I have django 2.0 running on an AWS EC2 instance. Recently I deployed some new code that works fine on localhost. At first, everything seemed to work fine on the deployment server. But the server seems to randomly load an old version of the site. At one moment, the new code (including template tags, new HTML and JS updates) is loaded and displayed just fine, on the next page refresh, the page behaves as if the template tags and HTML were not uploaded. Oddly enough, the JS seems to always be the new version, as it throws errors in the console. Now, I have checked Nginx, disabled the cache, cleared the django cache, removed the whole project files from the server and reuploaded everything, but the error seems to persist. Of course I also have restarted the server multiple times. Also, I have tested it on multiple browsers on multiple systems, all resulting in the same behavior. Does anybody have any idea what could be the issue here? -
Best way to code multiple decisions in Python
I have the following practical problem (related to Django/Python). I'm trying to get the following in the most efficient piece of Python code -> There are 2 items to be checked: Is the user logged in? if not show a login page, else check if the request is a post request. Is the request a post request? If not show a form, else handle the form def upload(request): if request.user.is_authenticated: if request.method == 'POST': form = forms.DocumentForm() return HttpResponse('Handle POST and LoggedIn Prefix Form Validation') #return (request, 'upload.html', {'form': form}) else: return HttpResponse('Not Logged In Need to Make Error Landing Page') else: if request.method == 'POST': return HttpResponse('POST but not logged in') #return render(request, 'upload.html', {'form': form}) -
django orm get child data from other db
usging django 2.0.2 python3.4 drf details skip settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'main', 'USER': 'root', 'PASSWORD': 'root123', 'HOST': 'localhost', 'PORT': "3309", 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", 'charset': 'utf8mb4', 'use_unicode': True, } }, 'log': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'log', 'USER': 'root', 'PASSWORD': 'root123', 'HOST': 'localhost', 'PORT': "3309" } } models.py #used database main class Post(models.Model): PostUID = models.BigAutoField( db_column='PostUID', primary_key=True) logmodels.py #used database log class PostLog(models.Model): LogUID = models.BigAutoField( db_column='LogUID', primary_key=True) #top directory is main PostUID = models.ForeignKey( "main.Post", db_column='PostUID', on_delete=models.CASCADE) UserUID = models.ForeignKey ... skip i tried this code Post.objects.all().annotate(Log=Case(When(postlog__UserUID=request.get("UserUID"),then=1), output_field=IntegerField(), default=Value(0))) raise exception this django.db.utils.ProgrammingError: (1146, "Table 'main.Postlog' doe sn't exist") if create or get i use objects.using("log") worked how to use using in orm -
django - How to save info of the user which formits the form?
I am trying to put in a form the sex of the UserProfile who's logged in. This is the UserProfile's class: class UserProfile(models.Model): FEMALE = 'FEMALE' MALE = 'MALE' SEX = ( (MALE, 'Male'), (FEMALE, 'Female'), ) birth_date = models.DateField() sex = models.CharField(max_length=5, choices=SEX, default=MALE) def __str__(self): return self.user.username Here is the view: @login_required def add_post(request): form = PostForm() # A HTTP POST? if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.save() return index(request) else: print(form.errors) return render(request, 'rango/add_post.html', {'form': form}) Thanks for every answer! -
How to download file using django-storage sftp?
I'm using django storage module to store file in a location using sftp and now we need to download same file from sftp. Any suggestion? models.py from storages.backends.sftpstorage import SFTPStorage SFS = SFTPStorage() class Configurations(BaseModel): """Tool Custom Configurations""" name = models.CharField(max_length=150, unique=True) file = models.FileField(upload_to='configurations', storage=SFS) descriptions = models.TextField(null=True, blank=True) settings.py DEFAULT_FILE_STORAGE = 'storages.backends.sftpstorage.SFTPStorage' SFTP_STORAGE_HOST = '172.16.104.86' SFTP_STORAGE_ROOT = '/var/www/media/' SFTP_STORAGE_PARAMS = { 'username': 'root', 'password': 'password', 'allow_agent': False, 'look_for_keys': False, } # SFTP_KNOWN_HOST_FILE = '~/.ssh/known_hosts' SFTP_STORAGE_INTERACTIVE = False views.py from django.http import Http404 from rest_framework import viewsets from rest_framework.parsers import MultiPartParser, FormParser from tpms.models import (CustomConfigurations) from tpms.serializers import (CustomConfigurationsSerializers) class ToolCustomConfigurationsViewSet(viewsets.ModelViewSet): queryset = CustomConfigurations.objects.all() parser_classes = (FormParser, MultiPartParser,) serializer_class = CustomConfigurationsSerializers def get_queryset(self): queryset = self.queryset.all().order_by('-id') return queryset serializer.py class CustomConfigurationsSerializers(serializers.ModelSerializer): class Meta: model = CustomConfigurations fields = '__all__' -
django.db.utils.IntegrityError: UNIQUE constraint failed:employee_id
I tried to fix according to previous questions and their answers by making unique=False but i'm still getting the IntegritiyError, Please have a look at this and correct me where am i wrong. models.py from django.db import models from django.db.models.signals import post_save # Create your models here. class Person(models.Model): name = models.CharField(max_length=100) gender = models.CharField(max_length=10) def __str__(self): return (self.name) class Employee(models.Model): employee = models.OneToOneField(Person,on_delete=models.CASCADE) emp_no = models.CharField(max_length=100,unique=False) desgnation = models.CharField(max_length=100) def __str__(self): return str(self.employee) def create_profile(sender,**kwargs): if kwargs: employee_profile = Employee.objects.create(employee = kwargs['instance']) post_save.connect(create_profile,sender=Person) I'm accessing data in localhost:8000/admin! So when i save something it works fine,but when i edit those data it gives error. Errors IntegrityError at /admin/post/person/1/change/ UNIQUE constraint failed: post_employee.employee_id Request Method: POST Request URL: http://localhost:8000/admin/post/person/1/change/ Django Version: 2.0.5 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: post_employee.employee_id Exception Location: C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 303 Python Executable: C:\Users\HP\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.3 Python Path: ['C:\\Users\\HP\\Desktop\\DjangoStuff\\signals', 'C:\\Users\\HP\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\HP\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\HP\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\HP\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\HP\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages'] Server time: Thu, 31 May 2018 07:04:20 +0000 my migrations 0001.initial.py # Generated by Django 2.0.5 on 2018-05-31 06:58 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Employee', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('emp_no', models.CharField(max_length=100)), … -
NoReverseMatch at /music/ beginner to Django
Was trying to create model forms for updating and deleting instances of album- the DB element, by following the Bucky Roberts: Django Tutorial for Beginners. index.html is the following {% extends 'music/base.html' %} {% block title %}Playspa{% endblock %} {% block body %} <form id="form_uord" method="post" > <ol> {% for album in object_list %} <!-- object_list is the default where the data returned by the view is stored in the html script --> <li> <a href="{% url 'music:detail' album.id %}">{{ album.album_title}}</a> &nbsp &nbsp &nbsp &nbsp <!--<a href="{% url 'music:album-update' album.id %}" > update </a>--> <button id="update_button" type="button" value="update" class="btn btn-primary" onclick="upd()"> update</button> &nbsp &nbsp <!--<a href="{% url 'music:album-delete' album.id %}" >delete</a>--> <button id="delete_button" type="button" value="delete" class="btn btn-danger" onclick="del()">delete</button></br></br> </li> {% endfor %} </ol> </form> <script> function upd() { var f= document.getElementById("form_uord"); f.action="{% url 'music:album-update' album.id %}"; var but=document.getElementById("update_button"); but.type="submit"; but.submit(); } function del() { var f= document.getElementById("form_uord"); f.action="{% url 'music:album-delete' album.id %}"; var but=document.getElementById("update_button"); but.type="submit"; but.submit(); } </script> {% endblock %} following are the urls in the app urls.py file url(r'^$', views.IndexView.as_view(), name='index'), #music/register url(r'^register/$', views.UserFormView.as_view(), name='register'), # /music/71/ url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), #music/album/add/ url(r'album/add/$', views.AlbumCreate.as_view(), name='album-add'), #/music/album/2/ url(r'album/(?P<pk>[0-9]+)/$',views.AlbumUpdate.as_view(), name='album-update'), #/music/album/2/delete/ url(r'album/(?P<pk>[0-9]+)/delete/$',views.AlbumDelete.as_view(), name='album-delete'), The terminal meanwhile read the following . Internal … -
Showing error while saving object in databse using django
query- a=Album(artist="Taylor Swift" ,album_title="RED",genre="Country",album_logo="https://www.billboard.com/files/styles/1024x577/public/video/1125911414_5788272680001_5788263766001-vs.jpg") a.save() error Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 69, in handle self.run_shell(shell=options['interface']) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 61, in run_shell raise ImportError ImportError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: attempt to write a readonly database -
django.db.utils.OperationalError: (1052, "Column 'name' in field list is ambiguous")
In my Django project I get bellow error when I query my data: django.db.utils.OperationalError: (1052, "Column 'name' in field list is ambiguous") using: http://localhost:8000/api/physicalserver/list/?switches__bandwidth=10 or: http://localhost:8000/api/physicalserver/list/?bandwidth=10 but if I use: http://localhost:8000/api/physicalserver/list/?switches__id=xxx It works fine. my ListAPIView code: class PhysicalServerListAPIView(ListAPIView): serializer_class = PhysicalServerListSerializer permission_classes = [AllowAny] pagination_class = CommonPagination my serializer code: class PhysicalServerListSerializer(ModelSerializer): bandwidth = serializers.SerializerMethodField() class Meta: model = PhysicalServer fields = "__all__" depth = 1 def get_bandwidth(self, obj): return obj.switchesport.bandwidth my model of PhysicalServer: class PhysicalServer(models.Model): name = models.CharField(max_length=32) switches = models.ForeignKey(to=Switches, on_delete=models.DO_NOTHING) physical_server_model = models.ForeignKey(to=PhysicalServerModel, null=True, on_delete=models.DO_NOTHING) switchesport = models.OneToOneField(to=SwitchesPort, related_name="physical_server", on_delete=models.DO_NOTHING) ... -
validation error message are not rendered in Django form
I have a login form to login a user either by email or username. The user account is a custom model of (AbstractUser). so the authentication is done by Django. Here is the form: class MyUserLoginForm(forms.Form): query = forms.CharField(label=' : username or email ') password = forms.CharField(label=': password ', widget=forms.PasswordInput) def __init__(self, *args, **kwargs): kwargs.setdefault('label_suffix', '') super(MyUserLoginForm, self).__init__(*args, **kwargs) # changing error messages: # if you want to do it to all of them for field in self.fields.values(): field.error_messages = {'required':'required field'.format( fieldname=field.label)} def clean(self, *args, **kwargs): query = self.cleaned_data.get('query') password = self.cleaned_data.get('password') user_qs_final = MyUser.objects.filter( Q(username__iexact=query) | Q(email__iexact=query) ).distinct() if not user_qs_final.exists() and user_qs_final.count != 1: raise forms.ValidationError("Invalid credentials - user does note exist") user_obj = user_qs_final.first() if not user_obj.check_password(password): raise forms.ValidationError("credentials are not correct") self.cleaned_data["user_obj"] = user_obj return super(MyUserLoginForm, self).clean(*args, **kwargs) The view function: def login_view(request, *args, **kwargs): form = MyUserLoginForm(request.POST or None) if form.is_valid(): user_obj = form.cleaned_data.get('user_obj') login(request, user_obj) return redirect("some page") return render(request, "login.html", {"form": form}) I removed them from the code, then I could log the user in even though the username or password are wrong which means that they are functioning well. hence, can you please help me why the validation error is not … -
Celery chord not releasing redis pubsub channel after apply_async
I am starting a chord from celery inside my django app in response to a request. The chord executes correctly, but the pub-sub channel is never released by django. Killing the django server releases the channel and it then disappears from redis-cli pubsub channels. Celery 4.1.1 or 4.2.0rc4 Redis 4.0.9 Python 2.7.15 Running locally, 1 celery worker, 1 api server Results do not matter in this case (but docs say to not ignore them) After hitting /api/start/ and watching the tasks complete in the tab running celery, I see 2 channels remaining. Killing django removes the channels, killing the celery worker has no effect on them. redis-cli pubsub channels 1) "celery-task-meta-chunk-1" 2) "celery-task-meta-chunk-2" I see the channels persist when everything goes right, so no errors are thrown. Can anyone see something that I am doing wrong? I know there are a few issues reported in celery, but I am not sure if this follows from them: https://github.com/celery/celery/issues/3812 https://github.com/celery/celery/issues/4761 Code: # --- endpoint.py ------------------------------------------- from . import tasks def start_chord(pk): all_tasks = celery.chord( task_id="my-chord-%s" % workorder_id, # HEADER is the group of tasks that must be excecuted before the 'body' header=celery.group( tasks.small_chunk.subtask(args=(x,), task_id="chunk-%s" % x) for x in range(1,2) ), body=celery.chain( … -
Django Auth - Custom model backend with JWT payload
After few question and attempts I found a way how to create a url gateway for users and use jwt rest framework with my custom model backend. The workflow should be: use id from the payload retrieve user by it pass the user token to the url like so http://localhost/auth/login/token=jwt_token authenticate user and redirect him to xy page Custom UrlTokenBackend is: import logging from django.contrib.auth.backends import ModelBackend from rest_framework_jwt.settings import api_settings from business_accounts.models.my_user import MyUser logger = logging.getLogger(__name__) jwt_decode_handler = api_settings.JWT_DECODE_HANDLER class UrlTokenBackend(ModelBackend): """ Custom login backend that will accept token allow click url login """ def authenticate(self, token=None): try: payload = jwt_decode_handler(token) user = MyUser.objects.get(pk=payload.get('id')) except MyUser.DoesNotExist: return None if not user.is_active: logger.info("User is active=%s", user.is_active) return user def get_user(self, user_id): try: return MyUser.objects.get(pk=user_id) except MyUser.DoesNotExist: logger.warning('User with this id=%s does not exists', user_id) return None Register the ModelBackend: AUTHENTICATION_BACKENDS = [ 'business_accounts.backends.UrlTokenBackend', 'django.contrib.auth.backends.ModelBackend', ] Add JWT_DECODE_HANDLER to the JWT_AUTH: JWT_AUTH = { 'JWT_DECODE_HANDLER': 'rest_framework_jwt.utils.jwt_decode_handler', 'JWT_RESPONSE_PAYLOAD_HANDLER': 'bspotted1.utils.jwt_response_payload_handler', 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=3000), 'JWT_AUTH_HEADER_PREFIX': 'bspotted', 'JWT_ALLOW_REFRESH': True, } Create a View: import logging from django.contrib.auth import authenticate, login from django.core.urlresolvers import reverse from django.views.generic import View from django.http import HttpResponseRedirect, Http404 logger = logging.getLogger(__name__) class UrlGatewayLogin(View): def get(self, request, **kwargs): page_group = kwargs.get('page_group') … -
Django Error that does nothing?
My project in django 2.0, python 3.x and I think its when i go into django admin I get this series of tracebacks and red letters that I asume is some kind of error, i just have no idea whatsoever what it is. ERROR does nothing:ERROR does nothing: Traceback (most recent call last): File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Users\Andre\Anaconda3\lib\socketserver.py", line 775, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] Se ha anulado una conexión establecida por el software en su equipo host [30/May/2018 14:06:28] "GET /static/admin/css/changelists.css HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 61210) [30/May/2018 14:06:28] "GET /static/admin/js/jquery.init.js HTTP/1.1" 200 363 Traceback (most recent call last): File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "C:\Users\Andre\Anaconda3\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File … -
pip force reinstall in requirements.txt
I have a requirements.txt file in which I have some git+ references. I would like to always reinstall these as for some reason, even if I make changes and bump the version and push it to my github repo, pip says requirements already satisfied and doesn't install. Here is part of my requirements.txt file:- Django==1.10 git+https://github.com/myaccount/myrepo.git@master#egg=some_egg I don't want to reinstall everything in the requirements.txt file. Only the git+ requirements. I tried this:- git+https://github.com/myaccount/myrepo.git@master#egg=some_egg --install-option="--upgrade --ignore-installed --force-reinstall" But none of the above options worked. -
Checking if a string is a prefix of any URL pattern
Inadvisable or not, my Django site assigns each user a page at the root, e.g., /rgov. I use a character set whitelist, so creating index.html or something nefarious should be prevented. My URL configuration also routes user pages last, so it should not be possible to hijack /admin or anything else by registering the corresponding name. However, I'd like to prevent users from registering admin, since their page will be broken. Here is my attempt: def is_reserved(username): r = urls.resolvers.get_resolver('mysite.systemurls') hit = False for path in ('/{}', '/{}/'): try: r.resolve(path.format(username)) hit = True break except urls.exceptions.Resolver404: continue return hit Here, the mysite.systemurls module defines every URL pattern except for the user pages. This does prevent picking the username admin because there is a route defined for /admin/. But it does not prevent api, because while there is /api/foo/bar, there is no route for /api/. Is there a way to test if there is a route that is a suffix of /api/ (for example)? Since URL patterns are regular expressions, maybe it's not so easy, but in a theoretical sense it should be possible. -
HTML table not rendering properly
I have a Django view that sends a dictionary whose contents will be rendered in a html page. My dictionary looks like this, d ={ name : ['damon','stefan','elena'], age : [200,200,25], address : ['mystic falls','mystic falls','mystic falls'] supernatural : ['yes','yes','yes']} Now my html table template looks like this, <table class="table table-striped" border="1" class="dataframe"> <thead> <tr style="text-align: center;"> {% for i in d %} <th>{{ i }}</th> {% endfor %} </tr> </thead> <tbody> {% for i,j in d.items %} <tr style="text-align: center;"> {% for x in j %} <td>{{ x }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> problem: When the rendering completes the dictionaries last values i.e ['yes','yes','yes'] are coming as a row. So below is how the output looks, name age address supernatural damon 200 mystic falls stefan 200 mystic falls elena 25 mystic falls yes yes yes Basically the last columns values are coming as rows. Can you please help me why is this. Is there something wrong in my html table code above. -
how to add input placeholder django
i wrote this from class then tried to add a placeholder to it class ContactUs(forms.Form): your_email = forms.EmailField(help_text='Enter a valid email.') subject = forms.CharField(max_length=100, help_text='Enter your subject.') message = forms.CharField(widget=forms.Textarea(attrs={'placeholder':'test'}), help_text='Enter your message.') cc = forms.BooleanField(required=False) like this and got list of error class ContactUs(forms.Form): your_email = forms.EmailField(help_text='Enter a valid email.', attrs={'placeholder':'please enter a valid email'}) subject = forms.CharField(max_length=100, help_text='Enter your subject.') message = forms.CharField(widget=forms.Textarea(attrs={'placeholder':'test'}), help_text='Enter your message.') cc = forms.BooleanField(required=False) -
How to auto fill SlugField instead of overriding save()?
Hello Awesome People I wonder if there is a way to generate slug, rather than overriding the save() methods of my models. Here's how I used to do: def save(self, *args, **kwargs): if self.pk is None: self.slug = create_slug(self) super(ModelName, self).save(*args, **kwargs) create_slug is a function that generates the slug with slugify def create_slug(instance,new_slug=None,field="name"): ''' long stuff to ensure the slug is unique ''' return slug As django can do in Django Admin by automatically filling the slug field. Possible that we can simply add an additional argument models.SlugField(field='name'). by adding this argument, django will make sure to take the value of field = name before saving to generate the slug without always overriding the save() method by copy/paste a lot of code to generate a slug for each model that We have. I'm a little tired of copying this for all models, any hint will help! Thank you in advance!