Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Forms API - Forms Returning Blank
I am not getting any data back through the form. I'm obviously missing something but I don't know what. I'm following this documentation. forms.py class EventRegistrationForm(forms.Form): tags = forms.TextInput() class Meta: model = Event fields = [ 'name', 'description', 'type', 'map_pin', 'location_id', 'location_name', 'address1', 'address2', 'city', 'state', 'zip', 'country', 'admission_fee', 'free_admission', 'online_ticket_url', 'available_parking', 'nearby_transit', 'stream', 'kid_friendly', 'no_underage', 'website_url', 'opportunities' ] views.py def save_event(request): if request.is_ajax() and request.method == "POST": main_form_data = json.loads(request.POST.get('mainForm')) print(main_form_data) main_form = EventRegistrationForm(main_form_data) if main_form.is_valid(): print(main_form.cleaned_data) output: {'online_ticket_url': '', 'state': '', 'city': '', 'stream': '', 'name': 'Test Subject', 'description': '', 'type': None, 'no_underage': 'on', 'map_pin': '', 'available_parking': '', 'opportunities': '', 'address': '', 'free_admission': 'on', 'kid_friendly': 'on', 'nearby_transit': '', 'tags': '', 'location_name': '', 'admission_fee': '', 'website_url': '', 'zip': '', 'location_id': '', 'country': ''} {} Would appreciate some help if anyone can tell where I'm getting tripped up. -
What is the correct way to compare a Django queryset with a JSON dataset?
I have a Django unit test that creates a temporary database and applies some changes to it. I also have a separate JSON file with a version of the data that represents how the data should look after the changes. What is the most recommended way to compare the results of the functions on the test data to the JSON dataset? I have tried using assertQuerysetEqual() but it doesn't seem to be working. When I do self.assertQuerysetEqual( Api.objects.all(), [repr(record) for record in delete_check_data if record['model'] == 'fim_app.api'], ordered=False ) the outcome is Traceback (most recent call last): File "/Users/davidmaness/development/fim_db/fim_app/tests/delete_test.py", line 49, in test_delete ordered=False File "/Users/davidmaness/development/fim_db/env/lib/python3.6/site-packages/django/test/testcases.py", line 965, in assertQuerysetEqual return self.assertEqual(Counter(items), Counter(values), msg=msg) AssertionError: Counter({'<Api: 2>': 1, '<Api: 3>': 1, '<Api: 4>': 1}) != Counter({"{'model': 'fim_app.api', 'pk': 1, 'field[474 chars]: 1}) What am I missing? -
Not Found: /accounts/register/accounts/register
Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/accounts/register/accounts/register views.py : from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from custom_user.forms import CustomUserCreationForm from django.contrib import auth from django.http import HttpResponseRedirect #Create your views here def home(request): return render(request, "home.html") def login(request): c = {} c.update(csrf(request)) return render(request, "login.html", c) def about(request): context = locals() template = 'about.html' return render(request,template,context) @login_required def userProfile(request): user = request.user context = {'user': user} template = 'profile.html' return render(request,template,context) def auth_view(request): username = request.POST.get['username', ''] password = request.POST.get['password', ''] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HTTpResponseRedirect('account/login') else: return HTTpResponseRedirect('account/login') def register(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() return redirect ('accounts/register_success.html') else: form = CustomUserCreationForm() args = {'form': form} return render(request, 'accounts/register.html', args) def register_success(request): return render(request, 'accounts/register_success.html') def logout(request): auth.logout(request) return render(request, 'logout.html') when i try to register a new user this error is raised . i manage to create my own custom registration form. i still cannot register any new user . is this error means that my registration form is not authenticate ? can someone explain why i get this error please ? im confused . help me please :( … -
How to override static.serve in Django 1.11?
I upgraded a Django project to 1.11, and now no static media is loading. Every request returns a 404 error, with the explanation that it was Raised by: django.views.static.serve. I've tried adding debug points into this view, but oddly enough, they're never shown. I'm using django-pipeline, which I suspect is causing the problem, possibly by monkeypatching static.serve, but I have it disabled with settings.PIPELINE['PIPELINE_ENABLED'] = False. I've also tried adding the same debug points in pipeline's views.serve_static(), but that also shows nothing. Why would Django be saying django.views.static.serve is throwing an exception when it's not? How do I find the source file for the function that corresponds to django.views.static.serve? I thought it would be .env/local/lib/python2.7/site-packages/django/views/static.py but changing that has no effect. It's almost like Django is either caching the response or using some other function. I discovered that if I set DEBUG = False, then everything works. Static media loads, and I also see my debug points in the real static.serve view. So it appears Django in debugging mode uses some "fake" serve view that not only can't find static media but also doesn't use the view that can. Why is this? -
send logged in user information to html page
I have a login function in my views.py file that works correctly: def login(request): username = request.POST.get("USER", False) password = request.POST.get("PASS", False) message = "" success = True response = {} try: user = User.objects.get(_username=username) offset = user._offset last_pass = user._password if decrypt(offset, last_pass) == str(password): response['username'] = user._username response['password'] = user._password response['email'] = user._email response['is_verified'] = user._is_verified response['name'] = user._name response['family_name'] = user._family_name response['address'] = user._address response['phone_number'] = user._phone_number else: message = "PassWord Is Incorrect" success = False except: message = "UserName Doesn't Exists" success = False response['message'] = message response['success'] = success return HttpResponse( "DCD:" + decrypt(offset, last_pass) + " PASS:" + str(password) + " OST:" + str(offset) + " MSG:" + str( response)) And I have a login form in my login.html file that actions to my last function: <form action="http://WEBSITE/login/" method="post"> <div> <label><b>username:</b></label> <input type="text" placeholder="enter username" name="USER" required> <label><b>password:</b></label> <input type="password" placeholder="enter password" name="PASS" required> <button type="submit">login</button> </div> </form> This form will send values of USER and PASS to my login function. Now I want to redirect user to another html page (user_profile.html) and show its information in that page. How can I use django response and json of user information of my login function … -
CKeditor is still parsing CSS Clasess after removing stylesheetparser plugin in Django
I was trying to install Ckeditor in my Django Admin Interface. I want to write myself in html code. But allow other users to use Ckeditor to write the html code. If i open a post from admin. Ckeditor removes the classes of all the tags. According the Ckeditor documentation available on: https://django-ckeditor.readthedocs.io/en/latest/#installation I should remove the plugin stylesheetparser by configuring the Ckeditor. I did that but still the Ckeditor the removing the Classes from the tags. -
Access the second element of a tuple?
Here is what I have when I print Meta.REQUEST_DOCUMENT_TYPE_CHOICES ((u'void_cheque', <django.utils.functional.__proxy__ at 0x7fbc6951a4d0>), (u'pay_stub', <django.utils.functional.__proxy__ at 0x7fbc6951a510>), (u'bank_statement', <django.utils.functional.__proxy__ at 0x7fbc6951a550>), (u'bank_statement_60', <django.utils.functional.__proxy__ at 0x7fbc6951a5d0>), (u'csst_statement', <django.utils.functional.__proxy__ at 0x7fbc6951a650>), (u'saaq_statement', <django.utils.functional.__proxy__ at 0x7fbc6951a6d0>), (u'cara_statement', <django.utils.functional.__proxy__ at 0x7fbc6951a750>), (u'insurance_letter', <django.utils.functional.__proxy__ at 0x7fbc6951a7d0>), (u't4', <django.utils.functional.__proxy__ at 0x7fbc6951a850>), (u'welfare_chart', <django.utils.functional.__proxy__ at 0x7fbc6951a8d0>), (u'raqp_chart', <django.utils.functional.__proxy__ at 0x7fbc6951a950>), (u'customer_id', <django.utils.functional.__proxy__ at 0x7fbc6951a9d0>), (u'proof_of_residence', <django.utils.functional.__proxy__ at 0x7fbc6951aa50>), (u'bankruptcy_proof', <django.utils.functional.__proxy__ at 0x7fbc6951aad0>), (u'consumer_proposal', <django.utils.functional.__proxy__ at 0x7fbc6951ab50>), (u'signed_contract', <django.utils.functional.__proxy__ at 0x7fbc6951abd0>)) I have this kind of data structure, and I will like to access the second element <django.utils.functional.__proxy__ at 0x7fbc6951a4d0> in there using only void_cheque. How could I do such thing? Update REQUEST_DOCUMENT_TYPE_CHOICES = ( ('void_cheque', _('Void Cheque')), ('pay_stub', _('Pay Stub')), ('bank_statement', _('Bank Statement (31 days)')), ('bank_statement_60', _('Bank Statement (60 days)')), ('csst_statement', _('CSST Statement')), ('saaq_statement', _('SAAQ Statement')), ('cara_statement', _('CARA Statement')), ('insurance_letter', _('Insurance Letter')), ('t4', _('T4')), ('welfare_chart', _('Welfare Chart')), ('raqp_chart', _('RAQP Chart')), ('customer_id', _('Customer ID')), ('proof_of_residence', _('Proof Of Residence')), ('bankruptcy_proof', _('Bankruptcy Proof')), ('consumer_proposal', _('Consumer Proposal')), ('signed_contract', _('Signed Contract')), ) -
Django + IIS - Multi User
I'm a newbie in webapp development so this question might be trivial. I've developed this app in a localhost and it works just fine. But I have an issue on the IIS published version. There's a piece of Python code that takes about 20 seconds to run, but if I run it from different PCs, everything fails. One of them throws an error and the other receives the results that should be for the first one. I'm sure I'm missing something really important about user management, but I just don't know what it is. Any help here, please? Many thanks in advance! -
How it's possible to block access to Python's .so modules? Python3, Django 1.11
I need to block access(or don't let import it) to Python's module if app served on "not allowed" server/domain. I have list of allowed domains and I've got server ip/domain using soket library. My idea is to create a module which will be imported in other modules to prohibe use them. It will check if domain in allowed list and let(or not) use the module. How it possible to do? I'm new to python so probably it's impossible at all. Please help. Thx -
remove restriction under certain circumstances Django
What my code doing now is totally restrict users from submitting the same studentID and startDate again. I would like to remove the restriction when supervisor.status='denied' In the normal circumstances, for example studentID is 12345 and startDate is 4/5/17. User submit this details. If the user submit the same studentID and the same date as the previous submitted one, there will be error saying "studentID with the startDate already submitted before". The details will then be passed to another template to be approved or denied. What i am trying to do is remove the restriction above for the particular studentID when the submission is denied which is supervisor.status='denied'. I am using model form for this. views.py def edit(request, id, status): query_results = Timesheet.objects.all() supervisor = get_object_or_404(Timesheet, pk=id) if status == 'a': supervisor.status = "approved" supervisor.save() elif status == 'd': supervisor.status = "denied" supervisor.save() return HttpResponseRedirect(reverse_lazy('timesheet:superltimesheet')) #display all the submitted timesheet def superltimesheet(request): query_results = Timesheet.objects.all() data={'query_results':query_results, 'some':'some'} return render(request, 'timesheet/supervisor_list_timesheet.html', data) class TimesheetForm(forms.ModelForm): checkbox = forms.BooleanField() studentName = forms.CharField() startDate = forms.DateField() class Meta: model = Timesheet fields = '__all__' exclude = ['action', 'status'] def clean(self): cleaned_data = super(TimesheetForm, self).clean() startDate = cleaned_data.get("startDate") @property def endDate(self): return self.startDate + timedelta(days=14) … -
Django expense manager aggregation
I am curently working on a django application for tracking expenses as well as keeping the balance of an account. I decided to go with a solution that does not compute the balance through aggregation of all the records in the expense table, but instead computes the current balance based on the last "confirmed" balance that is inputed once a month in a different table. Can I somehow overwrite the aggregation function? Or make a proxy class in order to do this computation? Thank you! -
How to use a generic view function to display model form and capture data at the same url - Django
I want to create a view function + template that displays a simple form (derived from a user model) and also captures the form submission. How do I do this using generic views in Django? My user model is: class User(models.Model): email = models.EmailField(unique=True) name = models.CharField(max_length=100) I only need to capture the email field in the form. I think there must be a simple way to do this using generic forms, however I'm not sure which one to use nor how to do it. The only other ways I know how to do it are: 1) Create UserForm explicitly and a single view function separating POST and GET requests. E.g., : def contact(request): if request.method == 'GET': # display UserForm .... elif request.method == 'POST': # process form submission .... 2) Create two views (with seperate URLs) - one using generic view to display form and another view to receive form submission e.g.,: class contact(generic.DetailView): # display form from User model model = User .... def submit(request): # process form submission .... So, my two questions are: can and how should this be implemented using ONLY a generic view? which generic view should be used? -
url automatically changing upon running django server admin
Trying to run a local server using python (Django) .Whenever i try to access the django admin by url http://127.0.0.1:8000/admin/ it automatically converts into http://127.0.0.1:8000/admin/login/?next=/admin/ giving me template does not exist error.Tried using atom terminal, windows cmd, changing from chrome to firefox but no use. -
How to get user input from web form in python and return result to web form
I am new to Django and HTML. I am trying to create user input forms to run python script. Whenever user submit data in forms, I want to run my python script and print results to output form again. For example, I have following python code. enter code here x= float(input(" Enter x value") y= float(input("Enter y value") z= 2*x+y*x print(z) I want to make three forms for x,y and z. When user submits x and y value, it will run python and print result z to output form. I am confused how I can achieve this. What is the best way to do this. This is just my sample code. My actual code is more complicated. But I hope, once I have idea, I can go next steps myself. Thanks in advance. -
Django's get_current_language() returns None
When I use django.utils.translations.get_current_language(), it returns None. What am I missing? My Django app has the following settings: USE_I18N = True USE_L10N = True LANGUAGE_CODE = 'en-us' LANGUAGES = ( ('en-us', _('English')), ('zh-cn', _('Chinese (Simplified)')) ) I also have LocaleMiddleware in my MIDDELWARE settings. Using Django 1.11 -
Django ImageField updates but doesn't render changes
I have the following field: logo = models.ImageField(_(u"Logo"), blank=True, null=True, upload_to=directory) That is rendered like: <img src="{{ logo.url }}"/> When I change the logo, the new image is uploaded and I can see the logo field has changed in the database. The problem is the template tries to render the old image. This URL is not valid anymore, and the image missing. This happens until I restart the server. After restarting, it works perfectly. It's like logo.url value keeps somehow cached. What am I missing here? -
Restrict access to particular pages for non-authenticated users
I'm building a simple forum in Django and I've got two models - Topic and Subtopic. I need to restrict access to some topics and subtopics for non-authenticated users, so that they couldn't access them, while other topics and subtopics should remain accessible to all the users -- both authenticated and anonymous. How do I achieve that? -
Deploying Django app on Yocto
I am currently working on a project that requires to deploy a Django Application to a ConnectCore 6 UL SBC Pro which runs a custom version of Yocto project. I have been having a lot of issues to deploy my app onto this device, I would like to know if anyone has ever achieved to do this on Yocto. So far I am trying to deploy my application using Cherokee and it is not as easy as they let you think! -
RecursionError: maximum recursion depth exceeded. Why
It seems i did something wrong? Can not config my urls. I have this error. Code below: urls.py (Root, main urls of application) from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('shop.urls', namespace='root_detail')) ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urls.py (my urls) from django.conf.urls import url from . import views urlpatterns = [ # Product list url(r'^$', views.product_list, name='product_list'), # Product list by category url(r'^(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_by_category'), # Product detail url(r'^(?P<category_slug>[-\w]+)/(?P<id>\d+)$', views.product_detail, name='product_detail'), ] I have this error RecursionError: maximum recursion depth exceeded -
Mpld3 inside of Django Views - "NoneType" Object has no attribute "split"
I am trying to make a request to my Django back-end with AJAX. I got the AJAX part working, but I am now trying to return an mpld3 figure to display it on the page. Here is my AJAX request: $.ajax({ type: "POST", url: url, data: data, dataType: "json", success: function(json){ }, }); This is my View: import mpld3 import matplotlib.pyplot as plt def get_figure(request): fig = plt.figure() plt.scatter(X, y) model = mpld3.fig_to_html(fig) data = {'Model': model} return JsonResponse(data) Any suggestions on why it could happen? Thanks in Advance -
using twython-django creating issues in libraries
I am trying to extract the tweets of the USES using my application. I was looking for a way to do it with DJango and I came across this thread on StackOverflow: How can I use Django Social Auth to connect with Twitter? From the thread I learned about twython-django library. I have a visit for sample to the github repository of the library. With the help of the instructions I have configured my application settings.py as: LOGIN_URL='/login' LOGOUT_URL='/logout' LOGIN_REDIRECT_URL='/' LOGOUT_REDIRECT_URL='/' TWITTER_KEY = 'xxxxx' TWITTER_SECRET = 'yyyyyyyyyyyyyyyyyyyyy' I used the following code in my Home.html to call the tweets: <div> {% for tweet in tweets %} {{ tweet.text }} {% endfor %} </div> But it is still a mystery from where the authentication will take place as there is nothing mentioned about the authentication in the library documentation. Well, then I tried t run the application as: python manage.py runserver This is what I got: An error: C:\Python27\lib\site-packages\sklearn\cross_validation.py:44: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This … -
How to toogle src attribute of script when user click element?
I use bootstrap 3.3.7 in my Django project. I have modal with textarea. Inside that textarea in the corner I put icon. Here below in the picture you can see my textarea. When user click to the icon I change textarea size to full screen of the browser. Also to my textarea I use autosize plugin which adjust textarea height to fit text. In normal situation (when textarea small) I need to use autosize plugin. When I click icon and change textarea size I dont need to use this plugin. Question: How to toogle src attribute of script when I click icon? P.S. I have little conflict with autosize plugin when textarea in full size mode. Cause when I started to write in textarea in full size mode autosize plugin change it's height. For thats why I want to cancer this plugin when textarea in fullscreen mode. html: <div class="dashboard-wrapper"> <div id="dashboard-content"> <div class="modal fade"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <form method="post" action=""> <div class="form-group"> <label for="body">Discription</label> <div class="textarea-wrapper"> <textarea name="body" class="form-control" id="body"></textarea> <i class="fa fa-arrows textarea-icon" aria-hidden="true"></i> </div> </div> </form> </div> </div> </div> </div> </div> <script id="" src="{% static 'js/autosize.js'%}"></script> JS: autosize(document.querySelectorAll('#body')); // Autosize for textarea with "body" id … -
Django number of products in basket by product ID
trying to count the number of items in my cart by specific product ID but struggling, e.g. 7 apples in basket. I have been trying to use the python count function but currently not working. I tried add the following code to my cart.py file but this didn't work: def count_prod(self, product) product_id = str(product.id) if product_id in self.cart: return count(self.cart[product_id]) This is my cart.py file from decimal import Decimal from django.conf import settings from shop.models import Product class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def __len__(self): """ Count all items in the cart. """ return sum(item['quantity'] for item in self.cart.values()) def __iter__(self): """ Iterate over the items in the cart and get the products from the database. """ product_ids = self.cart.keys() # get the product objects and add them to the cart products = Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)]['product'] = product for item in self.cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item def add(self, product, quantity=1, update_quantity=False): """ Add a product to the cart or update its … -
How do I 'Autofill' a CreateView field
I have a model called Artist, and now I'm working on building a comment section for the Artist DetailView. I've built a model called ArtistComment, created a CreateView and added this to the DetailView using modal divs so it looks nicer. The only issue is that when you click 'add comment' the modal shows both the 'artist' and the 'comment' fields. The artist field is a dropdown menu to select which artist the comment is applied to. I would like to be able to hide the 'artist' field, and have this auto-complete based on the page you follow the 'add comment' link from. I've managed to get the 'User' field to autocomplete with 'self.request.user' but whenever I try anything like self.request.artist_id it makes my modal form show blank. Can anyone help point me in the right direction to fix this issue? views.py: class ArtistCommentCreate(CreateView): model = ArtistComment fields = ['artist', 'message',] def get_success_url(self): return reverse('events:artistdetail', kwargs={'pk': self.object.artist_id}) def form_valid(self, form): form.instance.author = self.request.user return super(ArtistCommentCreate, self).form_valid(form) urls.py: url(r'^artist-(?P<pk>[0-9]+)/$', login_required(views.ArtistDetailView.as_view()), name='artistdetail'), url(r'^artistcomment/add/$', login_required(views.ArtistCommentCreate.as_view()), name='artistcomment-add'), artistdetail.html: <a data-toggle="modal" data-target="#artistcommentModal" href="{% url 'events:artistcomment-add' %}">Add A New Comment</a> <div id="artistcommentModal" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"></div> </div> </div> </div> -
The code should filter events from the future, but it does not
I have project in old django version - 1.5 (I know better is to upated to newer version, but for now this is not an issue). I have code connecting with pure sql - I want to have only events from the future - display on list. Here is my code - some reason I got event from the past. I tried without MIN(date), but I got an error: more than one row returned by a subquery used as an expression def get_events(): return Events.objects.extra(select={'next_activity': 'SELECT MIN(date) FROM productions_activity WHERE productions_activity.production_id = home_teaser.production_id'}).filter(Q(online__lte=now()), Q(online_end__gte=now()) | Q(online_end__isnull=True)).order_by('next_activity')