Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Finding the Cross-Section of two List views in one Django template
I have two models that feed one view. models.py class Item(models.Model): item_name = models.CharField(max_length=100) item_type = models.ForeignKey(Item_type, on_delete=models.SET_NULL, null=True) owned_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)**** added_at = models.DateTimeField('date item added') updated_at = models.DateTimeField('last update') def __str__(self): return self.item_name class Item_status(models.Model): item = models.ForeignKey(Item, on_delete=models.SET_NULL, null=True) borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) loaned_at = models.DateTimeField(default=None, blank=True, null=True) due_back = models.DateTimeField(default=None, blank=True, null=True) def __time__(self): return self.loaned_at def itemname(self): return (self.item.item_name) I have the following view views.py class LoanedItemsByUserListView(LoginRequiredMixin,generic.ListView): model = Item_status template_name ='catalog/item_status_list_borrowed_user.html' paginate_by = 10 def get_queryset(self): return Item_status.objects.filter(borrower=self.request.user).order_by('due_back') def get_context_data(self, **kwargs): context = super(LoanedItemsByUserListView, self).get_context_data(**kwargs) context['Owned_list'] = Item.objects.filter(owned_by=self.request.user, item_type = 1) context['Loaned_list'] = Item_status.objects.exclude(borrower=self.request.user).exclude(borrower__isnull=True) return context I would like to find the cross section of the 'Owned_list' and the 'Loaned_list' in a single template Something like <h2>Loaned Books</h2> {% if Owned_list %} <ul> {% for thing in Owned_list.item_name and in Loned_list.item.item_name %} <li> {{thing}} </li> {% endfor %} </ul {% else %} <p>There are no books in the library.</p> {% endif %} I have take a look at the django documentation here https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-display/, and around SO but not found exactly what I am looking for. Thanks! -
How to authenticate a user in websocket connection in django channels when using token authentication
I am using a frontend framework (Vuejs) and django-rest-framework for the REST API in my project. Also, for JSON web token authentication I am using django-rest-framework-jwt. After a successful login, the user is provided with a token. This token is passed into every request to fetch any API related stuff. Now I would like to integrate django channels into my project. So, after successful login, when the token is received in the client side, I would like to initiate a websocket connection. Then on the server (consumer), I would like to check if the requested user is not anonymous. If the requested user is anonymous, I would like to close the connenction or else accept it. This is how I have till now: client side: const socket = new WebSocket("ws://" + "dev.site.com"+ "/chat/"); routing.py: channel_routing = [ route("websocket.connect", ws_connect), ... ... ] consumers: def ws_connect(message): # if the user is no anonymous message.reply_channel.send({ "accept": True }) # else message.reply_channel.send({ "close": True }) In the documentation there's a decorator @channel_session_user_from_http which will provide a message.user. But I am using a token instead of a session. How can I check a user on connection when using token authentication, so that I can … -
Django .raw query fails (error 1064) -- but works in SQL
(using django 1.11.2, python 2.7.10, mysql 5.7.18) The following SQL query: SELECT transaction_transaction.id, sec_to_time(avg(time_to_sec(extract(HOUR_SECOND from transaction_transaction.transaction_datetime)))) AS average_time_of_day FROM transaction_transaction INNER JOIN store_store ON (transaction_transaction.store_id=store_store.id) INNER JOIN payment_method_card ON (transaction_transaction.card_id=payment_method_card.id) WHERE ( transaction_transaction.transaction_datetime BETWEEN '2017-08-31 00:00:00' AND '2017-08-31 23:59:59' AND store_store.company_id=2 AND payment_method_card.profile_id=8 ); Runs and returns the following result (as expected): +== id ==+== average_time_of_day ==+ |= 9422 =|===== 20:42:22.8695 =====| (This is run from HeidiSQL) Doing something similar (I think! but something is obviously wrong) via Django: average_time_of_day = Transaction.objects.raw( ''' SELECT transaction_transaction.id, sec_to_time(avg(time_to_sec(extract(HOUR_SECOND from transaction_transaction.transaction_datetime)))) AS average_time_of_day FROM transaction_transaction INNER JOIN store_store ON (transaction_transaction.store_id=store_store.id) %s WHERE ( transaction_transaction.transaction_datetime BETWEEN %s AND %s AND store_store.company_id=%s %s ); ''', [ 'INNER JOIN payment_method_card ON (transaction_transaction.card_id=payment_method_card.id) ' if profile_pk else '', start_datetime, end_datetime, company_pk, 'AND payment_method_card.profile_id=' + str(profile_pk) if profile_pk else '', ] ) Doing print average_time_of_day.query Outputs: SELECT transaction_transaction.id, sec_to_time(avg(time_to_sec(extract(HOUR_SECOND from transaction_transaction.transaction_datetime)))) AS average_time_of_day FROM transaction_transaction INNER JOIN store_store ON (transaction_transaction.store_id=store_store.id) INNER JOIN payment_method_card ON (transaction_transaction.card_id=payment_method_card.id) WHERE ( transaction_transaction.transaction_datetime BETWEEN 2017-08-31 00:00:00 AND 2017-08-31 00:00:00 AND store_store.company_id=2 AND payment_method_card.profile_id=8 ); And Django returns with the following error: ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the … -
Django Models Relationship Confusions
I have the following models: class UserPost(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) class User(AbstractUser): MALE = 'M' FEMALE = 'F' GENDER_CHOICES = ( (MALE, 'Male'), (FEMALE, 'Female') ) posts = models.ManyToManyField(Post, through='UserPost') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField() status = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) When I run python manage.py makemigrations, it raises the following error: users.User.posts: (fields.E303) Reverse query name for 'User.posts' clashes with field name 'Post.user'. HINT: Rename field 'Post.user', or add/change a related_name argument to the definition for field 'User.posts'. There is a many-to-many relationship between User and Post models. Each user can like many posts and each post can be liked by many users. There is also a many-to-one relationship between User and Post models. Each user can write many posts and each post can be written by only one user. Shouldn't reverse query name for 'User.posts' be user_set by default. If so, why is this name clashing with field name 'Post.user'? Can someone explain the meaning of this error? Thanks. -
django - how to make clickable html text that sends data to model?
I want to display users around 10 clickable html "tags" (just text with some css that changes when clicked) on my form page. I want them to be able to select a maximum of 3 tags but no minimum requirement. I then want to take the sum of all clicks for each individual tag and do some calculations with them as a model method, like return the 3 most clicked tags. It's important that my tags are on the form page and are submitted at the same time as the form. So I guess they have to be part of my form. How would I go about doing this? An actual example would be tremendously helpful as I'm still very new to django and find the documentation (which I've looked at) somewhat hard to understand. -
Django template Module Import Error
Using Django version 1.9.5 and Python 3. Upon navigation to the url, I am getting the following error: ImportError at /music/ No module named 'django.templates' Request Method: GET Request URL: http://localhost:8000/music/ Django Version: 1.9.5 Exception Type: ImportError Exception Value: No module named 'django.templates' Exception Location: D:\Program Files (x86)\Python\lib\importlib\__init__.py in import_module, line 126 Python Executable: D:\Program Files (x86)\Python\python.exe Python Version: 3.5.0 Python Path: ['C:\\Users\\ang\\Desktop\\website', 'D:\\Program Files (x86)\\Python\\lib\\site-packages\\django-1.9.5-py3.5.egg', 'D:\\Program Files (x86)\\Python\\python35.zip', 'D:\\Program Files (x86)\\Python\\DLLs', 'D:\\Program Files (x86)\\Python\\lib', 'D:\\Program Files (x86)\\Python', 'D:\\Program Files (x86)\\Python\\lib\\site-packages'] The error seems to be coming from the import line. Checked syntax and tried to explicitly provided the path under TEMPLATES at DIRS but same result. Anyone encountered a similar issue? Found some similar issues raised but in different languages. Folder Structure for template: name_of_app/templates/inner_folder/html_file music/templates/music/index.html views.py from django.http import HttpResponse from django.template import loader # error gone if i remove this line from .models import Album def index(request): all_albums = Album.objects.all() template = loader.get_template('music/index.html') context = { 'all_albums': all_albums } return HttpResponse('test test') settings.py TEMPLATES = [ { 'BACKEND': 'django.templates.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.templates.context_processors.debug', 'django.templates.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
cache busting in django using CachedStaticFilesStorage
Using django 1.8, when I put STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.CachedStaticFilesStorage' in my settings.py, all the static files are no longer accessible. The app tries to look for https://hostname/static/jquery-ui-1.11.4/jquery-ui.d3260250e777.css instead of https://hostname/static/jquery-ui-1.11.4/jquery-ui.css I'm using nginx with memcached. Any ideas what I'm doing wrong? -
PayPal Authorize code not accepted - Django
I am trying to integrate PayPal into a django project that I am working on and I am getting an issue related to the Authorize code which is not giving me access to the api within my project when i try to run my server. Here is the code that I have inside of my views.py file. import paypalrestsdk from paypalrestsdk.openid_connect import Tokeninfo, Userinfo CLIENT_ID_PAYPAL = "...Y2tf" CLIENT_SECRET_PAYPAL = "...9PIej" paypalrestsdk.configure({ "mode":"sandbox", "client_id":CLIENT_ID_PAYPAL, "client_secret":CLIENT_SECRET_PAYPAL, "opentid_redirect_uri":"http://127.0.0.1", }) # the following is going open the connection for the paypal openid connection login_url = Tokeninfo.authorize_url({"scope":"openid profile"}) tokeninfo = Tokeninfo.create("access_token$sandbox$...72373be5e") tokeninfo = tokeninfo.refresh() tokeninfo = Tokeninfo.create_with_refresh_token(tokeninfo) userinfo = tokeninfo.userinfo() userinfo = Userinfo.get("access_token$sandbox$...172373be5e") logout_url = tokeninfo.logout_url() I am getting an access denied message within my terminal. paypalrestsdk.exceptions.BadRequest: Failed. Response status: 400. Response message: Bad Request. Error message: {"error_description":"Invalid authorization code","error":"access_denied","correlation_id":"...52866","information_link":"https://developer.paypal.com/docs/api/#errors"} Does anyone know how to where to get my authorization code because I have looked through the entire paypal developer site and I couldn't find it. -
Django - access class-based view's instance from middleware
I would like to do some stuff with views before actually processing them. I learned that process_view method of class-based middlewares might be helpful here. But the problem is that the only thing I managed to get from here is the actual class, but not its instance, which I would like to have. Code approach is as follows: class SomeView(View): class_attribute = "..." def __init__(self, *args, **kwargs): self.instance_attribute = "..." # ... class Middleware: # ... def process_view(request, view_func, view_args, view_kwargs): # access class_attribute print(view_func.view_class.class_attribute) # access instance_attribute print("I don't know, please help, thank you.") -
Django python contact email form error post not allowed 405
I dont know why i get this error in the bash: Method Not Allowed (POST): /curriculum/ [14/Sep/2017 20:47:24] "POST /curriculum/ HTTP/1.1" 405 0 views.py: from django.views.generic import TemplateView from Profile.forms import ContactForm from django.core.mail import send_mail, BadHeaderError, EmailMessage from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from django.template import Context from django.template.loader import get_template Create your views here. class HomePageView(TemplateView): def get(self, request, **kwargs): return render(request, 'index.html', context=None) class ProjectsPageView(TemplateView): template_name = 'projects.html' class TutorialsPageView(TemplateView): template_name = 'tutorials.html' class ArticlesPageView(TemplateView): template_name = 'articles.html' class LanguagesPageView(TemplateView): template_name = 'languages.html' class VideosPageView(TemplateView): template_name = 'videos.html' class CurriculumPageView(TemplateView): template_name = 'curriculum.html' def post(self, request, **kwargs): form_class = ContactForm # new logic! if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): contact_name = request.POST.get( 'contact' , '') contact_email = request.POST.get( 'email' , '') form_content = request.POST.get('message', '') # Email the profile with the # contact information template = get_template('templates/contact_template.txt') context = Context({ 'contact_name': contact_name, 'contact_email': contact_email, 'form_content': form_content, }) content = template.render(context) email = EmailMessage( "New contact form submission", content, "Your website" +'', ['juanmacedoal@gmail.com'], headers = {'Reply-To': contact_email } ) email.send() return redirect('curriculum') return render(request, 'PageJMMA/Profile/templates/index.html', { 'form': form_class, }) url.py: from django.conf.urls import url from Profile import views urlpatterns = [ … -
djangoCMS with Aldryn NewsBlog missing "New news/blog article"
I am currently setting up a django CMS website on my server. I want to add a blog and tried to follow this Divio Blog Guide, which works with the aldryn-newsblog plugin. As I am not using the divio servers I had to install aldryn-newsblog. I followed the Aldryn Newsblog Setup: pip install aldryn-newsblog and added the following to my settings 'aldryn_apphooks_config', 'aldryn_categories', 'aldryn_common', 'aldryn_newsblog', 'aldryn_people', 'aldryn_reversion', 'aldryn_translation_tools', 'parler', 'sortedm2m', 'taggit', I followed these last to steps from the Aldryn setup 1. Create a django CMS page in the normal way. 2. In Advanced settings... > Application settings, select NewsBlog. When I select NewsBlog and try to "Create" a new News/Blog article I end up with this menu where i miss the corresponding button "New news/blog article". Did i forget or oversee something here? -
Reverse for 'user_posts' with keyword arguments '{'username': ''}' not found. 1 pattern(s) tried: ['posts/by/(?P<username>[-\\w]+)/$']?
i keep getting this error in django "NoReverseMatch", an di cant solve the problem. please help!! my models.py from django.conf import settings from django.core.urlresolvers import reverse from django.db import models import misaka from groups.models import Group from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, related_name="posts") created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name="posts",null=True, blank=True) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = misaka.html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse( "posts:single", kwargs={ "username": self.user.username, "pk": self.pk } ) class Meta: ordering = ["-created_at"] unique_together = ["user", "message"] and my views.py is this: from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.core.urlresolvers import reverse_lazy from django.http import Http404 from django.views import generic from braces.views import SelectRelatedMixin from . import forms from . import models from django.contrib.auth import get_user_model User = get_user_model() class PostList(SelectRelatedMixin, generic.ListView): model = models.Post select_related = ("user", "group") class UserPosts(generic.ListView): model = models.Post template_name = "posts/user_post_list.html" def get_queryset(self): try: self.post_user = User.objects.prefetch_related("posts").get( username__iexact=self.kwargs.get("username") ) except User.DoesNotExist: raise Http404 else: return self.post_user.posts.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["post_user"] = self.post_user return context class PostDetail(SelectRelatedMixin, generic.DetailView): model = models.Post select_related = ("user", "group") def get_queryset(self): queryset = super().get_queryset() … -
Django update view won't save
I have this update view but it will not save upon form submission. 5 minutes ago everything was working fine and then I added the edit feature for user posts and all of a sudden nothing will save when trying to edit things. users app views: class UserEditProfileView(LoginRequiredMixin,UpdateView): login_url = '/login/' model = UserProfile fields = [ 'first_name', 'profile_pic', 'location', 'title', 'user_type', 'website', 'about', 'twitter', 'dribbble', 'github' ] template_name_suffix = '_edit_form' def get_success_url(self): userid = self.kwargs['pk'] return reverse_lazy('users:user_profile',kwargs={'pk': userid}) users app models: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50,default='User') join_date = models.DateTimeField(default=timezone.now) profile_pic = models.ImageField(upload_to='profile_pics',null=True,blank=True) location = models.CharField(max_length=150) title = models.CharField(max_length=250) user_type = models.IntegerField(choices=USER_TYPE_CHOICES,default=1) website = models.URLField(max_length=100,blank=True) about = models.TextField(max_length=500,default='about') twitter = models.CharField(max_length=50,blank=True) dribbble = models.CharField(max_length=50,blank=True) github = models.CharField(max_length=50,blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.userprofile.save() def __str__(self): return self.user.username user profile_edit_form.html: {% extends "users/base.html" %} {% block content %} <div class="form-title"> <h2 class="form-title-text">Edit Profile</h2> </div> <div class="user-forms-base"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save" /> </form> </div> {% endblock %} I am having the same issue with updating posts on the home page, however I am assuming the issues are the same and … -
Mongoengine with django: DuplicateKeyError
I'm using mongoengine (http://mongoengine.org/) in a Django project. I don't know if this is such a good idea, but I thought I'd just try to get it work since there seems to be no up to date MongoDB implementation for Django. When running my server and trying to access localhost:8000/workoutcal/ I get this error: Traceback (most recent call last): File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/workoutcal/views.py", line 18, in calendar workouts_in_month = Workout.objects(Q(date__gte=datetime(year=today_year, month=today_month, day=today_day)) & Q(date__lt=datetime(year=today_year, month=today_month+1, day=1))) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/mongoengine/queryset/manager.py", line 37, in __get__ queryset = queryset_class(owner, owner._get_collection()) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/mongoengine/document.py", line 204, in _get_collection cls.ensure_indexes() File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/mongoengine/document.py", line 834, in ensure_indexes collection.create_index(fields, background=background, **opts) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/pymongo/collection.py", line 1571, in create_index self.__create_index(keys, kwargs) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/pymongo/collection.py", line 1472, in __create_index parse_write_concern_error=True) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/pymongo/collection.py", line 232, in _command collation=collation) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/pymongo/pool.py", line 477, in command collation=collation) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/pymongo/network.py", line 116, in command parse_write_concern_error=parse_write_concern_error) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/pymongo/helpers.py", line 203, in _check_command_response raise DuplicateKeyError(errmsg, code, response) pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: db.workout index: id_1 dup key: { : null } I have trouble understanding this error. Does it mean … -
django-screamshot "Html Render IMG TAG Image is not coming while generating PDF"
Using django-screamshot plug to generating PDF. Below is the URL of plugin https://github.com/makinacorpus/django-screamshot I am rending an HTML with Django-ScreamShot (CasperJs Option) to generate PDF. Imaging are not coming after generating PDF. It is showing ? at the center. Is it problem to rendering is fast so we need to wait ? -
Django Aggregate Query Values for Multiple Objects
In my project I have a model called Organization that can have multiple Campaign's. Each campaign can then have multiple donor's. Hopefully to clarify here is what my models look like: class Campaign(models.Model): name = models.CharField() organization = models.ForeignKey('org.Organization') class Donor(models.Model): lead = models.ForeignKey('org.Lead') amount = models.DecimalField() campaign = models.ForeignKey(Campaign) What I would like to do is show a campaign, then display the sum of all amounts made by donors (donor.amount). So for example, if "Campaign1" has three donors, each of whom donated $5, in my template it will show: "Campaign1: $15." Any idea on how I can accomplish this? I was thinking about using a backward relationship in my template but you can not create Aggregates this way. Thanks for any help. -
Django RestFramework method filter with multiple lookups
I have two models defined like this: class House(models.Model): # all the fields here def capacity(self): capacity = 0 for room in self.rooms.all(): capacity += room.capacity return capacity class Room(models.Model): house = models.ForeignKey( House, on_delete=models.CASCADE, related_name='rooms' ) capacity = models.PositiveIntegerField( default=1 ) What i need is to filter the houses by its capacity using all number lookups(lt, lte, gt, gte, range, exact) in restframework, i did this: import rest_framework_filters as filters def capacity_filter(qs, name, value): # filter implementation here class HouseFilter(filters.FilterSet): capacity = filters.NumberFilter( method=capacity_filter ) class Meta: fields = ('capacity',) class HouseViewSet(viewsets.ModelViewSet): filter_class = HouseFilter # other attrs here And it works but only for exact value, i cant filter using __gt, or __lt, i try with lookup_expr parametter in NumberFilter but not work. -
Let me know how to import columns that match other tables in django
this is my code def get_question_keyword(question_id): connection = connect(host=MYSQL_CONNECTION_INFO['HOST'], port=MYSQL_CONNECTION_INFO['PORT'], user=MYSQL_CONNECTION_INFO['USER'], password=MYSQL_CONNECTION_INFO['PASSWORD'], db=MYSQL_CONNECTION_INFO['DB'], charset=MYSQL_CONNECTION_INFO['CHARSET'], cursorclass=cursors.DictCursor) keyword_list = [] try: with connection.cursor() as cursor: query = ("SELECT keyword FROM question WHERE id=" + str(question_id)) cursor.execute(query) keyword = "" for item in cursor: keyword = item["keyword"] keyword_list = keyword.strip().split(",") finally: connection.close() return keyword_list That's one of those codes. query = ("SELECT keyword FROM question WHERE id=" + str(question_id)) -
django query aggregate function is slow?
I am working with Django to see how to handle large databases. I use a database with fields name and age and height. The database has about 500000 entries. The aggregate function in querying table takes about 10s. Is it usual or am I missing something. age = [i for i in Data.objects.values_list('age').distinct()] ht = [] for each in age: aggr = Data.objects.filter(age=each).aggregate(ag_ht=Avg('height') ht.append(aggr) -
Installing misago
I want to build a forum using misago but I cannot install it. Everytime I use pip install misago i get the following error. Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\HP\AppData\Local\Temp\pip-build-_sg0mt_y\misago\setup.py", line 11, in <module> README = open(os.path.join(SETUP_DIR, 'README.rst')).read() File "c:\users\hp\appdata\local\programs\python\python35-32\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 716: character maps to <undefined> Command "python setup.py egg_info" failed with error code 1 in C:\Users\HP\AppData\Local\Temp\pip-build-_sg0mt_y\misago\ I searched if they are compatible with python 3.X and they are. I've also installed ez-setup and setuptools to help but to no avail. I'm using windows 10, python 3.5. -
froala django doesn't work in template
i'm trying to use froala WYSIWYG in my django project i installed and prepared everything as it is mention in the docs but the content field still displayed as text field so any solution ?? my code forms.py from django import forms from .models import BlogPost from froala_editor.widgets import FroalaEditor class PostForm(forms.ModelForm): content = forms.CharField(widget=FroalaEditor()) class Meta: model = BlogPost fields = ('title','body','thumb','tags') template <html> <head> <title></title> <link rel="stylesheet" type="text/css" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="/static/font-awesome/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="/static/font-awesome/css/font-awesome.css"> <link href="{{STATIC_URL}}froala_editor/css/font-awesome.min.css" type="text/css" media="all" rel="stylesheet" /> <link href="{{STATIC_URL}}froala_editor/css/froala_editor.min.css" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="{{STATIC_URL}}froala_editor/js/froala_editor.min.js"></script </head> <body> </body> </html> note that editor = PostForm(request.POST, request.FILES ) in my views and i'm having trouble with jquery cookies error: Uncaught ReferenceError: getCookie is not defined at HTMLDocument.<anonymous> ((index):72) at i (jquery.min.js:2) at Object.fireWith [as resolveWith] (jquery.min.js:2) at Function.ready (jquery.min.js:2) at HTMLDocument.K (jquery.min.js:2) -
Django formset in javascript
I have a django formset with unknown number of forms. Each form has product name, price, quantity, and total. I want to calculate the simple product such as quantity x price = total. I loop forms in the formset and get the value of the price from each form. <input type="number" name="price" value="{{forms.price}}"> I can pass the number of quantity to javascript and do the calculation. var $price = $("input[name='price']"), $quantity = $("input[name='percentage']").on("input", calculatePrice), function calculatePrice() { var quantity = $(this).val(); var price = $price.val(); var calcPrice = price; $total.val( calcPrice ); } but how do I do it with unknown number of forms? Each form will have the same name. I assume i need to assingn different name to each form and then assign the same name to javascript but I have no idea how to do that. -
HttpResponseRedirect not working as expected
In my views.py I have: return HttpResponseRedirect('/account/forecast/') The problem I'm running into is that the response url is being appended. e.g. from: mysite.com/account the redirect goes to: mysite.com/account/account/forecast instead of: mysite.com/account/forecast. I'm using Django 1.11, gunicorn and nginx with SSL. -
Django can't lookup datetime field. int() argument must be a string, a bytes-like object or a number, not datetime.datetime
I'm trying to group objects 'Event' by their 'due' field, and finally return a dict of day names with a list of events on that day. {'Monday': [SomeEvent, SomeOther]} - that's the idea. However while looking up event's due__day I get: int() argument must be a string, a bytes-like object or a number, not datetime.datetime. Here's manager's code: # models.py class EventManager(models.Manager): def get_week(self, group_object): if datetime.datetime.now().time() > datetime.time(16, 0, 0): day = datetime.date.today() + datetime.timedelta(1) else: day = datetime.date.today() friday = day + datetime.timedelta((4 - day.weekday()) % 7) events = {} while day != friday + datetime.timedelta(1): events[str(day.strftime("%A"))] = self.get_queryset().filter(group=group_object, due__day=day) # ^^^ That's where the error happens, from what I understood it tries to convert this datetime to int() to be displayed by template day += datetime.timedelta(1) return events Here is the model: # models.py class Event(models.Model): title = models.CharField(max_length=30) slug = models.SlugField(blank=True) description = models.TextField() subject = models.CharField(max_length=20, choices=SUBJECTS) event_type = models.CharField(max_length=8, choices=EVENT_TYPES) due = models.DateTimeField() author = models.ForeignKey(User, blank=True) group = models.ForeignKey(Group, related_name='events') objects = EventManager() I created a template filter to call this method: @register.filter def get_week(group_object): return Event.objects.get_week(group_object=group_object) And I called it in event_list.html (Using an index because it's a list view, also this … -
How to update database using the form value & calculation in Django?
Currently using sqlite that comes with Django. In a CreateView of creating a project I want to search for tools that are in the tools database. Upon selecting one, it will display information in a row within the CreateView. Upon submitting my project I want to -1 from the quantity of that tool in the tools database. In reference to my title I am just looking to subtract the value of in the quantity input from the tools database and how to do that.