Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Divide Django base.html template into header, content and footer.html
Hi I have extended Django Admin templates into my app/templates/admin directory.. in that directory I have base.html which contaions <header> header content<header> <body> body Content </body> <footer> Footer Content</footer> so I have created header.html which contains {% extends "admin/base_site.html" %} <!-- I also tried to include base.html here--> {% block header %} Header Html here... {% endblock %} and replaced base.html to below content {% block header %} {% endblock %} <body> body content </body> <footer> Footer Content </footer> but when header content is not getting loaded.. so please suggest. -
Django year validation returns "Ensure this value is less than or equal to 2016" in year 2017
In my database, I have a record where the year field is 2016 but I need to change it to 2017. When I use Django admin to change it 2017, I get "Ensure this value is less than or equal to 2016.". What is wrong w/ my model? class Track (models.Model): artist = models.ForeignKey(Artist, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Artist") title = models.CharField(max_length=100, verbose_name="Title") year = models.PositiveSmallIntegerField(null=True, blank=True, validators=[MinValueValidator(1900), MaxValueValidator(datetime.datetime.now().year)], verbose_name="Year") timestamp = models.DateTimeField(default=timezone.now) -
access all packets from Pcap file
I am trying to access some information from pcap file. I am able to do for a single packet, and pcap file have multiple packet. I coded this into Django. What should I add into this code by which it return all packet information testcap = open("Test_1.pcap") capfile = savefile.load_savefile(testcap, verbose=True) ip_packet = ip.IP(binascii.unhexlify(ethernet.Ethernet(capfile.packets[0].raw()).payload)); mac_packet = ethernet.Ethernet(capfile.packets[0].raw()); packet = capfile.packets[0]; def index(request): answer = [ str(packet.timestamp), str(packet.packet_len), str(mac_packet.src), str(mac_packet.dst), str(ip_packet.src), str(ip_packet.dst), ] return HttpResponse("<br>" . join(answer)) I tried for looping also still its not working. -
How to get the SQL structure of specific table using Django?
class Table1(models.Model): name = models.CharField(max_length=10) class Table2(models.Model): name = models.CharField(max_length=10) table1 = models.ManyToManyField(Table1) Ex: python manage.py sqlall app The above command will give the SQL structure of all the tables in a specific application. So, my question is, How do I get the SQL structure of a specific table in the application? Suppose, if the table has Many To Many Field then How the SQL structure will be? -
How to separate authentication logic for two different admin panel in Django?
I have been implementing two admin panels. One for the superuser and another one for the let's say seller admin.I can separate logic via Django's in-built groups and permission modules, but i need different wordings and custom designs for that two different admin panels. Structure of my 2 admin panels are below. This is the usual way of django, urls.py url(r'^admin/', admin.site.urls), admin.py admin.site.register(modelname) So,admin panel logic is completely fine. Issue is to separate the seller and admin with each other. So, i created different seller panel with this, admin.py Custom admin panel from django.contrib.admin.sites import AdminSite class MyAdminSite(AdminSite): pass myadmin = MyAdminSite(name="myadmin") myadmin.register(User) So,here we have two different urls for the two different admin panel.By this i achieved different admin looks and urls. Main problem is to differentiate the login between this two admin panels. Only Problem is "Admin can login into seller admin panel and seller can login into superuser admin panel" Can we implement this logic by two custom admin logins ? or Groups and permission via is_staff option is the only way? -
Where are the instances of the models?
I thought that blog entries are stored in the db.sqlite3, copied that to the clone of my site, but the posts are not moved. I need make a clone of site with identical content. How i can do that? -
Query intermediate through fields in django
I have a simple Relation model, where a user can follow a tag just like stackoverflow. class Relation(models.Model): user = AutoOneToOneField(User) follows_tag = models.ManyToManyField(Tag, blank=True, null=True, through='TagRelation') class TagRelation(models.Model): user = models.ForeignKey(Relation, on_delete=models.CASCADE) following_tag = models.ForeignKey(Tag, on_delete=models.CASCADE) pub_date = models.DateTimeField(default=timezone.now) class Meta: unique_together = ['user', 'following_tag'] Now, to get the results of all the tags a user is following: kakar = CustomUser.objects.get(email="kakar@gmail.com") tags_following = kakar.relation.follows_tag.all() This is fine. But, to access intermediate fields I have to go through a big list of other queries. Suppose I want to display when the user started following a tag, I will have to do something like this: kakar = CustomUser.objects.get(email="kakar@gmail.com") kakar_relation = Relation.objects.get(user=kakar) t1 = kakar.relation.follows_tag.all()[0] kakar_t1_relation = TagRelation.objects.get(user=kakar_relation, following_tag=t1) kakar_t1_relation.pub_date As you can see, just to get the date I have to go through so much query. Is this the only way to get intermediate values, or this can be optimized? Also, I am not sure if this model design is the way to go, so if you have any recomendation or advice I would be very grateful. Thank you. -
Django project to desktop application
I have created executable exe of django project. That exe run fine, But pyinstaller is not able to wrap html,jss and css files into exe. Anyone know how we can do this? -
How to display text fles in web application?
I want to view uploaded files in my web application. I designed it using Django framework. I am able to upload any file to my application but don't know which API is best suit for viewing files. How dropbox and google drive implemented file viewer? Can we use HttpResponse for viewing all types of files? I am using python. -
i had install pillow but i can't use makemigrations command and it tell me pillow is not installed "please help me"
this is my problem: PS C:\Users\mydesktop\trydjango19> py -2 manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: posts.Post.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow". PS C:\Users\mydesktop\trydjango19> pip install pillow Collecting pillow Using cached Pillow-3.4.2-cp35-cp35m-win_amd64.whl Installing collected packages: pillow Successfully installed pillow-3.4.2 PS C:\Users\mydesktop\trydjango19> py -2 manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: posts.Post.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow". PS C:\Users\Rich Family\trydjango19> -
tranfer docker-compose django project to remote system
I did setup a docker compose for my django project.I need to transfer and deploy this project on a remote system without exposing the django source code.How to do it with docker compose. -
Django showing the result of a query with decimal()
Hello I have a question about the result of a query. suma = Contrato.objects.aggregate(Sum('lote__Costo')) The result is the sum of all the records in a column of the database. What I can not understand exactly is the way in which I get the result of the query which is shown as follows {'lote__Costo__sum': Decimal('142000.00')} Is equal in the shell as in the template I wonder if there is a way to display only the result of the query. Thanks. -
Exceptions in send_mail when fail_silently=True
I was going to use send_mail function to send email, and I was hoping that using fail_silently=True will prevent this function from raising exceptions. It turns out it does work if SMTPException is raised; however I noticed it doesn't intercept socket.error exception - so if STMP server is down, an exception will be raised even with fail_silently=True I'm now wondering how to get the complete list of exceptions raised by send_mail so I can catch them in try/except loop. Any suggestions? -
Calculating percentile from django queryset
Let's say I have a django queryset of objects User. Each User has an average_score. How can I determine the user's percentile (top 10%, top 20%, etc) based on the average_score? If I were able to sort the queryset, I could theoretically take the index divided by the total count (eg 5th place out of 100 total is top 5%) but since we can't sort querysets– what can I do here? -
Django - clean() with hidden form
I'm having an issue here, my def clean() is not working with my hidden form. I have three forms where I'm using jquery to hidde it with a select so if for example I want form1 just I have to pick form1 and it will hide the others 2. Now I'm trying to use clean() but when I get my raise ValidationError I can't see it because my form is hidden. So I need to click on form1 and after that I can see my error Is there a possible way to see my error even if its hidden? Because sometimes I don't know why I'm getting an error until I click on form1.. I have been looking for a possible solution and found nothing. template <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script> {{ titulo }} <hr/> <br/> {% if messages %} <div class="row"> <div class="col-sm-6 col-sm-offset-3"> {% for message in messages %} {% if message.tags %}<div class="alert alert-{{ message.tags }}">{{ message }}</div>{% endif %} {% endfor %} </div> {% endif %} <center><label for="protocolo">Protocolo de Activos</label> <select id="protocolo" name="protocolo"> {% for x,y in form.fields.protocolo.choices %} <option value="{{ x }}"{% if form.fields.protocolo.value == x %} selected{% endif %}>{{ y }}</option> {% endfor %} </select></center> <br> <div … -
Django: sorl-thumbnail image not updated right away because of cache
I have a ModelA which has sorl-thumbnail ImageField. I load this model's images using sorl thumbnail in templates. Problem is that whenever I change the image of this model, its new image doesn't show up right away because of brower cache (I think...) How can I make it shown up right away after change the image? Thanks -
Save additional data to Django database
I am using Django Channels and I want to be able to save additional fields to the database along with the json data of the post. I have a foreign key in my Postmie model that points to email field in my user model. Postmie is the model responsible for saving posts to the database. The Foreign key creates a field called email_id. While I am saving posts to the database I want to also grab the email of the user making the post and save it in the database as well. How can I go about doing this? I am not using Django forms. My Postmie model is the same as the one in the Django Channels tutorial Post found here, the only difference is that my model has an extra foreign key pointing to the email field in my user model. email=request.user.email does not work. I was thinking about putting the email in a hidden field, but that does not seem safe to me. The method I am using is practically the same method in the Django Channels tutorial found here consumers.py. Everything works but I am not able to enter other fields in the database for posts. … -
Django admin - Extended User model
My requirement is to create 2 types of user in Django. 1. Student 2. Faculty I have extended the Django user model by creating a MyProfile model: class MyProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #Profile Information photo = FilerImageField( blank = True, help_text = 'Profile Pic', null = True, on_delete = models.SET_NULL ) #Student Information enrollment = models.CharField('Enrollment', blank = True, default = '', help_text = 'Student Enrollment Number', max_length = 20, ) admission_date = models.DateField('Admission Date', blank = True, default = None, null = True, help_text = 'Date when student joined the college', ) def __unicode__(self): return unicode(self.user.username) Now if I create a user then For Student:- Fields likes 'enrollment', 'admission_date' are mandatory BUT For Faculty:- these fields are not required. Now in the admin.py file, I did below: class ProfileInline(admin.StackedInline): model = MyProfile fieldsets = ( ('Profile Information', { 'classes': ('collapse',), 'fields': ('photo') }), ('Student Information', { 'classes': ('collapse',), 'fields': ( ('enrollment', 'admission_date'), }). ) @admin.register(User) class MyUserAdmin(admin.ModelAdmin): list_display = ('username', 'first_name', 'last_name', 'email', 'is_staff', 'is_active',) search_fields = ('username', 'first_name', 'last_name', 'email',) list_filter = ('is_staff', 'is_active',) inlines = [ ProfileInline, ] fieldsets = ( ('User Information', { 'fields': ('username', ('first_name', 'last_name'), 'password', 'groups', 'is_active') }), ) I have created … -
Entry point for a Django app which is simply a redis subscribe loop that needs access to models - no urls/views
I currently have an external non-Django python process which is a simple redis subscribe loop that simply munges the messages it receives and inserts the result in a user mailbox (redis list), which my main app accesses on requests. My listener now needs access to models, so it makes sense (to me) to make this a Django app. Being a loop, however, I imagine it's probably best to run this as a separate gunicorn process with a different settings.py than my main site. As I'm neither using redis as a cache nor using web sockets, my search for solutions has run a bit dry. What I'm doing is pretty simple, but I'm a bit confused as to where the entry point for this app should be. AppConfig.ready() seemed like a good place, but now I'm concerned, since it needs access to other apps models, that I should probably wait for apps.ready to be true prior to starting my listener. Unfortunately this is a simple boolean value (no signal). Would calling (from AppConfig.ready()) some function which simply loops until apps.ready is True prior to starting my listener be inadvisable? Are there some less ad-hoc methods for doing something like this? Any … -
Django Tutorial: circular import
I am working through the Django tutorial. I have created the polls application and added/modified the respective url files. However, when running the server, I get the following message: "If you see valid patterns in the file then the issue is probably caused by a circular import." ~/mysite/polls.py from django.conf.urls import url from . import views urlpattrns = [ url(r'^$', views.index, name='index'), ] ~/mysite/mysite/urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] ~/mysite/polls/views.py #from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResposne("Hello, world. You're at the polls index.") The "from Django.shortcuts import render" was commented out because it was not in the tutorial on their website. I am not sure why I am getting this error. I am running Python 2.7. Thanks. -
Sending a lockfile to django-post_office send_queued_mail
This doesn't seem like it should be hard, but I'm stumped. I've gotten django-post_office integrated with my codebase, and now I'm trying to test that I can set up cron jobs for queued email as described in the docs: https://github.com/ui/django-post_office Whether I run on the command line or in crontab, I get the same problem: python manage.py send_queued_mail lockfile='/home/gbeadmin/tmp/post_office.lock' Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/gbeadmin/webapps/gbe2016test/lib/python2.7/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/home/gbeadmin/webapps/gbe2016test/lib/python2.7/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/gbeadmin/webapps/gbe2016test/lib/python2.7/django/core/management/base.py", line 242, in run_from_argv self.execute(*args, **options.__dict__) File "/home/gbeadmin/webapps/gbe2016test/lib/python2.7/django/core/management/base.py", line 285, in execute output = self.handle(*args, **options) File "/home/gbeadmin/.local/lib/python2.7/site-packages/post_office/management/commands/send_queued_mail.py", line 33, in handle options['lockfile']) KeyError: 'lockfile' Digging around, I see that I should be able to specify the lockfile, so I've tried: python manage.py send_queued_mail --lockfile='<path to lock file>' Which then gives me the error: Usage: manage.py send_queued_mail [options] manage.py: error: no such option: --lockfile I've also tried the '-L' option listed in the docs, with the same basic result. I'm lost - I don't see a bug in my syntax, I don't see any other way to set the lock file... Other notes: I'm running in WebFactional I'm running django 1.6 (yes, I … -
Django 1.10 Migration django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
I looked at the similar questions on SO and could not find any relevant solution for my problem. I'm coming from 1.6 world and migration is a new concept to me. My app has the following models: class Company(models.Model): company_name = models.CharField(max_length = 30) company_type = models.CharField(max_length = 50, choices = COMPANY_TYPES, blank = True) website = models.CharField(max_length = 30, blank = True) title = models.CharField(max_length = 50, choices = TITLES) address = models.CharField(max_length = 50, blank = True) company_email = models.EmailField(max_length = 70, blank = True) def get_companies_by_title(title): ''' Given a company title (e.g. consultant, builder, etc.), this function returns all the companies with the given title ''' the_companies = Company.objects.filter(title__iexact = title) return the_companies class Employee(models.Model): first_name = models.CharField(max_length = 20) last_name = models.CharField(max_length = 20) employer = models.ForeignKey(Company, related_name = 'employees') driver_license_num = models.CharField(max_length = 30) title = models.CharField(max_length = 40) # Ex/ project manager, receptionist, principal, journeyman carpenter, foreman, etc. birth_year = models.IntegerField(blank=True) # Birth year is optional GENDERS = ( ('female', 'Female'), ('male', 'Male')) gender = models.CharField(choices = GENDERS, max_length=10) email = models.EmailField(max_length = 70) phone_number = models.CharField(max_length=10) start_date = models.DateField() address = models.CharField(max_length = 100) address_city = models.CharField(max_length = 30) def get_employees_by_title(title): ''' Given … -
Implementing user referrals in Django
I'm working on a project and I need to implement user referrals and link referees to their referers exposing some referee profile details to the referrer -
use dropdownjs in django form for upload one image in image field
i want use dropdownjs instead of default brows bottom in djngo form for upload one image for my post here is my models.py class Post(models.Model): """docstring for Post""" user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1 ) slug = models.SlugField(unique=True) post_title = models.CharField(max_length=50) color=models.ForeignKey(Color) size=models.ForeignKey(Size) type_goods=models.ForeignKey(Type) kind=models.ForeignKey(Kind) nationality=models.ForeignKey(Nationality) gender=models.ForeignKey(Gender) image = models.ImageField(upload_to = 'user/',null=True, blank=True, height_field="height_field", width_field="width_field",) and forms.py class PostForm (forms.ModelForm): class Meta: model = Post fields=[ 'post_title', 'state', 'color', 'size', 'kind', 'image', ] post.html {% if request.user.is_authenticated %} <form method="POST" id="mydropzone" class="dropzone" name="PostForm" action="/post/createpost/" enctype="multipart/form-data"> {% csrf_token %} {{form|as_bootstrap_inline}} <input type="hidden" name="user_id" value="{{ user.id }}" /> <button type="submit" class="btn btn-primary" style="right;font-family: yekan;" id="submit">ایجاد آگهی</button> {% else %} {% endif %} </form> </div> but show me the image field too like this -
Django 1.10 Form Fields Using Foundation 6 Not Showing In Template
I am trying to build a simple landing page in Django that will allow users to sign up for an email newsletter. I am using this cookie cutter template - https://github.com/Parbhat/cookiecutter-django-foundation - because it integrates Foundation 6 from the jump. The challenge is that the form fields are not showing in the template. Any help would be appreciated. My models.py is: class Subscribe(models.Model): email = models.EmailField() subscription_status = models.BooleanField(default=True) create_date = models.DateTimeField(auto_now_add = True, auto_now = False) update_date = models.DateTimeField(auto_now_add = False, auto_now = True) def __unicode__(self): return self.email My forms.py is: from django import forms from .models import Subscribe class SubscribeForm(forms.ModelForm): class Meta: model = Subscribe fields = ('email',) My views.py is: from django.shortcuts import render from subscribers.forms import EmailForm, SubscribeForm from .models import Subscribe def home(request): form = SubscribeForm(request.POST or None) if form.is_valid(): new_join = form.save(commit=False) #we might need to do something here. email = form.cleaned_data['email'] new_join_old, created = Subscribe.objects.get_or_create(email=email) #new_join.save() context = {"form": form} template = "pages/home.html" return render(request, template, context) And my template is: {% extends "base.html" %} {% load foundation_formtags %} {% block content %} <section class="hero"> <!-- HERO SECTION --> <div class="homebox"> <div class="wrap"> <p>Lorem Ipsum</p> <form class="form" method="post" action=""> {% csrf_token %} {{ …