Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple Image Field in Django Model
I am using django-cms for a client project. I want to add a carousel of images that will display all those images in my template. How do I add this using a model and implement it into a form to use? class Show(models.Model): title = models.CharField(blank=True, max_length=300) header_image = models.ImageField(upload_to="", blank=True) starting_date = models.DateField(default=datetime.datetime.today, blank=True) poster = models.ImageField(upload_to="", blank=True) description = models.TextField(blank=True) is_TS_show = models.BooleanField(default=False, blank=True) show_slug = models.SlugField(max_length=100) def __str__(self): return self.title def save(self, *args, **kwargs): self.show_slug = slugify(self.title) super(Show, self).save(*args, **kwargs) def get_absolute_url(self): return "/show/%s/" % self.show_slug It's for a carousel so it will be maybe 4-5 pictures. -
Retrieve all objects related to a particular foreign key in django
i have the following models.py: //models.py(code snippet) class userresp(models.Model): uid=models.ForeignKey(settings.AUTH_USER_MODEL,blank=True,null=True) resp=models.CharField(max_length=20) datetime=models.DateTimeField(default=timezone.now) def __unicode__(self): return u"{} {}".format(self.uid,self.datetime) class Meta: db_table="userresp" I want to retrieve all "resp" pertaining to the value of a particular uid=3. there are two records in the table userresp with uid=3. How di i do that? -
How can I run Angular 2 application from Django's server?
I need to run angular2 application from django's developement server with google app engine deployment. -
Django MySQL database error passing database query
I am trying to query a MySQL database using Django. I pieced this code together using several sources. Can someone explain what is wrong with how I am passing the query? I would appreciate suggestions or links about how to improve my code as well since I'm new to Python and Django. The error I get is: TypeError: query() takes exactly 1 argument (2 given) My class: (does database connection and displays result in a view) from helloservice.models import Snippet from helloservice.serializers import SnippetSerializer from rest_framework import generics from django.contrib.auth.models import User from helloservice.serializers import UserSerializer from rest_framework import permissions from helloservice.permissions import IsOwnerOrReadOnly from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework import renderers from rest_framework.response import Response from rest_framework import viewsets from rest_framework.decorators import detail_route #sudo pip install MySQL-python class DbConn(): hostname = 'jdbc:mysql://xxxxxx.us-east-1.rds.amazonaws.com:3306' username = 'rrrr' password = 'xxxx' database = 'yyyy' def query(q): myConnection = MySQLdb.connect( host=hostname, user=username, passwd=password, db=database ) cur=conn.cursor() cur.execute(q) return cur class UserViewSet(viewsets.ReadOnlyModelViewSet): conn= DbConn() cur=conn.query('SELECT * FROM pulse.customer WHERE userId = 103') #return cur.objects.values_list('loginName') print(cur.objects.values_list('loginName')) -
Django dynamic form
Please consider the following two models: class Addresses(models.Model): address_id = models.AutoField(primary_key=True) postalcode = models.CharField("Postal Code", max_length=10) parish = models.CharField("Parish", max_length=50) locality = models.CharField("Locality", max_length=50) street = models.CharField("Street", max_length=200, blank=True) def __str__(self): return '%s %s' % (self.locality, self.street) class Meta: ordering = ['postalcode', 'parish', 'locality', 'street'] unique_together = ("locality", “street”) class Members(model.Model): name = models.CharField("Name", max_length=100) postalcode = models.CharField("Postal Code", max_length=10) parish = models.CharField("Parish", max_length=50) locality = models.CharField("Locality", max_length=50) street = models.CharField("Street", max_length=200) block = models.CharField("Number/Block/Apartment", max_length=30) … def __str__(self): return self.name class Meta: ordering = ["name"] I would like to build a Members form that: Limits the choices for postalcode, parish, locality and street to model Addresses distinct choices for each field Does this recursively, meaning that once the user selects the postalcode from the distinct postalcode choices in Addresses the choices for parish, locality and street would be further limited as per Addresses key. When the user makes the second choice the options in the other two would be further reduced and so on. Does this to the point when the user selects both locality and street (unique_together in Addresses), and the choices for postalcode and parish would be completed (if not yet selected). The street field should remain … -
How to use existing pure Python 3.6 project to implement as Django site?
I have a Python 3.6 project and it mostly does processing stuff. My program/script takes only one input in the terminal and that's it for a user-end. After all processing, it simply outputs a text file, which is again what I want. I want to know a proper styling to arrange my Django project, how to use existing project files and also strategy for user-input from Django web app. Again, let me be clear, in my project user inputs something from the terminal and program outputs a text file. I hope I am pretty clear. -
Filtering Geodjango Results using Function Based Views
Currently, the webpage displays a list of found results sorted by distance (similarly to the ListView). What I would like to do is to create a filter to further narrow down these results. Views.py def teacher_list(request, **kwargs): if request.method == 'GET': form = LocationForm(request.GET) if form.is_valid(): SearchPoint = Point(form.cleaned_data['Lng'], form.cleaned_data['Lat']) Radius = form.cleaned_data['SearchRadius'] Type = form.cleaned_data['Type'] else: form = LocationForm() SearchPoint = Point(0, 0) Radius = form.cleaned_data['SearchRadius'] else: form = LocationForm() SearchPoint = Point(0, 0) Radius = form.cleaned_data['SearchRadius'] results = Teacher.objects.filter(location__distance_lte= (SearchPoint, D(km=Radius)))\ .annotate(distance=Distance('location', SearchPoint))\ .order_by('distance') return render(request, "users/teacher_list.html", context={"form": form,"teacher_list":results,}) Currently filtering works, but not for categorical variables. For example, if I change the location or search radius, the form is updated and I see new results. However, I have a categorical variable called TYPE which can be either FREE or PAID. If a person selects a FREE filter, only show results which are free and vice versa. These are boolean fields in my model. class Teacher(models.Model): free = models.BooleanField() paid = models.BooleanField() What I tried adding is some sort of filter parameter that will work similarly to if Type == 'Free': filter_variable = 'free=True' elif Type == 'Paid': filter_variable = 'paid=True' else: filter_variable ='' new_result_set = results.filter(filter_variable) Is … -
How to create csv file and save to file filed in django model?
I'm using django csv (https://docs.djangoproject.com/en/1.11/howto/outputting-csv/) and i want to save generated csv file to file field in below model class CsvDoc(models.Model): csv_file = models.FileField( upload_to="path") -
Django - How to connect citrix sharefile to django server?
I'd like to connect citrix sharefile to django server. I am looking for a document but I can't find it. When the django server get a request, it should find a file from citrix sharefile and get it. At the end of the processing, the django server send a modified file to citrix sharefile and save it. Is it possible? -
Django update_or_create in bulk
Does Django have any bulk function to update_or_create? Let's say I want to update the 'last_emailed' time of 10,000 users, but LastEmailed may also not exist for a specific user so it is update_or_create. Or must I resort to raw SQL? My database is postgresql. -
Two breakpoints, but one reacted
views.py class StatisticsIndexView(StaffRestrictedMixin, TemplateView): model = Statistics() template_name = 'loanwolf/statistics/index.html' form = StatisticsBaseForm() def home(request, template_name): import ipdb; ipdb.set_trace() redirect_url = request.GET.get('period') def get_context_data(self, **kwargs): import ipdb; ipdb.set_trace() context = super(StatisticsIndexView, self).get_context_data(**kwargs) context.update({ 'applications_by_state': ApplicationsByState(), 'applications_calendar': ApplicationsCalendar(), 'new_customers_calendar': NewCustomersCalendar(), 'statistics': Statistics(), 'form': StatisticsBaseForm(), }) return context urls.py urlpatterns=[ url(r'^$', login_required( StatisticsIndexView.as_view()), name='index'), ] I put a breakpoint in the home() and get_context_data() method, but it stopped only in the get_context_data(). Why don't I have any results in home() method? -
django request param from urls into views not working
I m trying to request table_id from table_base.html and is not returning anything. This my table_base.html <div class="container"> <div class="jumbotron"> <h1> {{ table_name }} List</h1> {% if list_tables %} <table class="table table-bordered sortable"> <thead> <th>Id</th> <th>Name</a></th> <th>Date</a></th> <th>Search Button</th> </thead> {% for list in list_tables %} <tr> <td><a href="#" >{{ list.id }}</a></td> <td> <a href="{% url 'tables:addview' table_id=list.id %}" name="table_name">{{ list.name }}</a> </td> <td>{{ list.date }}</td> <td><a href="#">Search</a></td> </tr> {% endfor %} </table> {% else %} <p> No Records Found</p> {% endif %} </div> </div> This is my tables/urls.py urlpatterns = [ url(r'^$', views.table_base, name='tables'), url(r'^(?P<table_id>\d+)$', views.AboutDetail.as_view(), name='details'), url(r'^(?P<table_id>\d+)/details$', views.addview, name='addview') ] This is my tables/views.py def table_base(request): table_name = Crawledtables._meta.db_table list_tables = Crawledtables.objects.order_by('id') return render(request, 'tables/table_base.html', {'table_name': table_name, 'list_tables': list_tables}) class AboutDetail(DetailView): model = Crawledtables pk_url_kwarg = 'table_id' template_name = 'tables/table_list.html' def __init__(self, **kwargs): super(AboutDetail, self).__init__(**kwargs) def get_object(self, **kwargs): if 'table_id' not in self.kwargs: return Crawledtables.objects.get(id=1) else: return Crawledtables.objects.get(id=self.kwargs['table_id']) def addview(request, table_id): q = request.GET.get('table_id') print q table_name = Crawledtables.objects.get(id=q) print table_name AllTables._meta.db_table = table_name.name tbl_detail = AllTables.objects.order_by('id') return render(request, 'tables/table_list.html', {'details': tbl_detail}) It works 1 time. When I select the first table (table with id 1) it gives me all the info. When I try to select another … -
Django ModelAdmin's list_editable in the Wagtail ModelAdmin?
Django's ModelAdmin.list_editable class is super handy and I reeeeaally need it, but I'm not sure how to go about implementing in Wagtail's IndexView. Where do I begin? -
SQL database data into webpage using Django
Hi I have a very large dataset with 300,000 rows that I need to somehow insert into the webpage, unfortunately the webpage takes a long time to load with all of that information, is there a way using Django and python, that I can throw the data into some kind of list and then show it page by page? Thanks. -
Django: Querying Database
Here's my model, class Answer(models.Model): .... likes = models.ManyToManyField(User, related_name='answer_likes') timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) I wants to filter out the Answers which received maximum likes in last 24 hours. I got this solution, timing = datetime.now() - timedelta(hours=24) data = Answer.objects.filter(timestamp__gte=timing).annotate(final=Count('likes')).order_by('-final') But this is not what I want. I wants to filter out the answers which received the maximum likes in last 24 hour in the entire database not the ones asked in last 24 hours & received maximum likes. How can i do that? Thank You :) -
How to use a customized 404 page in Django CMS
Django allows to use customized error views, but I would like to take advantage of the CMS and use one of his pages for displaying the error. I have tried adding handler404 = 'hotels.views.page_not_found_view' to urls.py, and then rewrite the request in the view so it renders my error page: from cms.views import details def page_not_found_view(request): return details(request, 'page_not_found') But no luck so far, the app cannot find the path, Does somebody know an easy way to achieve this without using redirections? -
How to sort based on a choice field in django in template
Consider the following model: class Category(models.Model): name = models.CharField(max_length=100) description = models.TextField() POSITIONS = ( ('L', 'Left'), ('R', 'Right') ) position = models.CharField(max_length=1, choices=POSITIONS, default='R') class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name I want to sort the objects in a manner such that I can separate the left ones from the right ones and show them in separate parts of the html document. Something like: {% for category in categories|sort_by: "position" = "left" %} <ul class="collection with-header"> <li class="collection-header"> <h3>{{category.name}}</h3> <p><small>{{category.description}}</small></p> </li> {% for url in category.extra_link_set.all %} <li class="collection-item"><a href="{{url.url}}">{{url.url_text}}</a></li> {% endfor %} </ul> {% endfor %} I know this wont work. But I am just trying to give an idea as to what I want. Also would the process be similar for any other field type in django models? -
How should be done authentication using both Django Rest Framework and Django websockets in one project?
I use in project both Django channels with websockets and Django Rest Framework. I wonder whether there is any way to have one common Token for every user for authentication in Rest and websockets? Or maybe there should be two different tokens for every user, one in DRF and another for websockets? -
How to rename a field in a Django form?
I have a custom Django widget that renders some HTML that I cannot control, and by default the widget's HTML will has a fixed name attribute using a -, say name="field-name". My problem is that Django expects the name attribute in the HTML to be exactly the same as the variable name of the field in python. But of course in python I cannot name a variable using -. Is there any way to tell Django to decouple the variable name of the form field from the name in the HTML? In other words, when the user already introduced the data in the field and sends the POST request, can I tell Django that the field field_1 should be reading the value field-name from the requests.POST dictionary? -
Django apps not showing in admin when site is deployed to server
I have a test site which I am (trying) to get deployed to an Ubuntu 16.04 server. If I run the site using the Django server (python manage.py runserver 0.0.0.0:8000), I can see all of the apps when I visit the admin page as the superuser, and everything is fine. However, when I run the site normally, using wsgi, the only apps I can see (and interact with) in the admin are for the users and groups. None of the apps I have created are visible, and if I try and navigate to a change list page for one of them for example, I get a page not found. I believe my mod_wsgi set up is ok, in that I can view the admin and login, so I don't believe this is the problem. Perhaps it's a permissions issue? Any help much appreciated! -
Django Distinct and Foreign Key filtering Query
I found questions about this problem but no working answer, so any help is appreciated :) I want to display a list of the lastest Record made by each Client. Records is a model, which has Client as a field. Client is a ForeignKey for User. For example #Initially: Client3 --- Record6 Client2 --- Record5 Client2 --- Record4 Client1 --- Record3 Client1 --- Record2 Client1 --- Record1 #Wanted: we only keep one Record per Client, the lastest one. Client3 --- Record6 Client2 --- Record5 Client1 --- Record3 This is what I have tried: def LastRecordPerClient(request): id_list = Record.objects.order_by('-date').values_list('client__id').distinct() records = Record.objects.filter(id__in=id_list) return (request, 'records/record_list.html', {"records": records}) This is what I get in my shell: <QuerySet []> Any idea? -
Recursion Error - Maximum Recursion dept exceeded when ForeignKey('self') django
I am getting an error in admin console while trying to open a model (employees in my case). This is occurring after adding a field which is a ForeignKey('self'). I guess it is conflicting with str method. If I comment out the method, there is no error, but all the objects in the model are appearing as 'employee object'. Here is what my error looks like https://ibb.co/jHt84Q Here is my models.py: from django.db import models import calendar from datetime import datetime from datetime import timedelta class employees(models.Model): emp_id=models.PositiveIntegerField() emp_name = models.CharField(max_length = 100) emp_lname = models.CharField(max_length = 100) emp_loc = models.CharField(max_length = 100,null=True) manager_id=models.ForeignKey('self',null=True,blank=True) image=models.ImageField(upload_to='profile_image',default='/profile_image/profile-icon.png') email = models.EmailField(default='app-engine@gmail.com', blank=False) def __str__(self): return str(self.emp_id) + '-' + self.emp_name + '-' + self.emp_loc+'-'+str(self.manager_id) class leave(models.Model): employee = models.ForeignKey(employees, on_delete=models.CASCADE, default='1') start_date = models.DateField() end_date = models.DateField() status=models.CharField(max_length=1,default='P') ltype=models.CharField(max_length=2) message=models.CharField(max_length=500,blank=True) date_created = models.DateTimeField(auto_now_add=True) def leave_length(self): return self.end_date - self.start_date+timedelta(days=1); def __str__(self): return str(self.id) + '/' + str(self.employee.emp_name) +'/'+str(self.start_date) +'/'+str(self.end_date) +'/'+str(self.status)+'/'+str(self.date_created) -
Django - Get parent object with children's object
I'm new to Django so I might miss the answer for this one because of terminology. I am trying to get parent object with children objects, I've got: Product.objects.all().filter(sub_category__category_id=category_id).select_related() I am trying to get parent category object within the children objects I've already got. Thanks in advance :) -
Saving Post data to the database using django
I am trying to save post data for a custom user registration but I can't identify where I am going wrong. I am suspecting the problem is in mainapp/urls but I cannot figure out why. I have done some research on the subject read the following https://docs.djangoproject.com/en/1.11/topics/http/urls/ Django: Save Form Data to Database Django Forms: if not valid, show form with error message and many others but I cannot find the problem. Here are my models from django.db import models # Create your models here. class User(models.Model): first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 100) username = models.CharField(max_length=30) email = models.EmailField(unique = True) password1 = models.CharField(max_length=255) password2 = models.CharField(max_length=255) My custom form import re from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ObjectDoesNotExist class RegistrationForm(UserCreationForm): email = forms.EmailField(required = True) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) help_texts = { 'username': None, 'email': None, 'password': None, } def clean(self): cleaned_data = super(RegistrationForm, self).clean() password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if not password2: raise forms.ValidationError("You must confirm your password") if password1 != password2: self.add_error('password2', "Password does not match") return cleaned_data def save(self, commit=True): user = … -
django get value from html
I want to list all tables using my Crawledtables, and when i click table1 i need to pass in the table_id. With that table_id i need to get the table_name and list all the info inside that table. i m stuck at getting the table_id this is my views.py def table_base(request): table_name = Crawledtables._meta.db_table list_tables = Crawledtables.objects.order_by('id') return render(request, 'tables/table_base.html', {'table_name': table_name, 'list_tables': list_tables}) class AboutDetail(DetailView): model = Crawledtables pk_url_kwarg = 'table_id' template_name = 'tables/table_list.html' def __init__(self, **kwargs): super(AboutDetail, self).__init__(**kwargs) def get_object(self, **kwargs): if 'table_id' not in self.kwargs: return Crawledtables.objects.get(id=1) else: id_table = Crawledtables.objects.get(id=self.kwargs['table_id']) return id_table def addview(self, request, **kwargs): id_table = request.POST.get("table_name") if id_table is not None: print id_table # with this table_id i need to get the table_name # need to use the table_name to get the content using # Ex: test = AllTables.objects.all() pass # i need to return the the content of the table id else: pass this is my table_base.html <br> <div class="container"> <div class="jumbotron"> <h1> {{ table_name }} List</h1> {% if list_tables %} <table class="table table-bordered sortable"> <thead> <th>Id</th> <th>Name</a></th> <th>Date</a></th> <th>Search Button</th> </thead> {% for list in list_tables %} <tr> <td><pre><a href="#" >{{ list.id }}</a></pre></td> {# this is where i get the id …