Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Period in primary key for django API resulting in detail not found
I made a mistake of using unix time with a period in it as my primary key. In my API I access objects through the api with {site_url}/api/requests/{primarykey} An example of the primary key with the period in it would be "id": "1507224845.340847" However, a period messes up the url ({site_url}/api/requests/1507224845.340847) causing the API to return: {"detail":"Not found."}. I've removed the period from my PK but I'm wondering how I can access these already created objects through the API given I can't PUT to the URL, which is my normal method of modification. -
Django Rest Framework - OPTIONS request - Get foreign key choices
Lets say I have two models in Django, and I'm using standard Viewsets and Serializers to expose endpoints. ModelA has a ForeignKey field to ModelB. When I do an OPTIONS request to the ModelA endpoint it just lists it as a field, like below: "actions": { "POST": { "pk": { "type": "integer", "required": false, "read_only": true, "label": "ID" }, "created": { "type": "datetime", "required": false, "read_only": true, "label": "Created" }, "foreign_key_field": { "type": "field", "required": true, "read_only": false, "label": "Wcp" }, } } I would like it to have a 'choices' property which pulls down every single instance of Model B. This way in my Angular frontend I can create a dropdown of all the choice. I think I need to make a new MetaData class or somthing. But I can't find any solid way of doing this. I also think this functionality has changed in 3.X of DRF so old answers around the internet no longer help. Cheers, Dean -
SHORT way to map list into another
I have the following list and dict : [u'customer_id', u'bank_statement', u'pay_stub'] and 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')), ) I already know I could access each element on that way list = dict(Meta.REQUEST_DOCUMENT_TYPE_CHOICES) list['void_cheque'] The purpose of this question is to convert the first list into ['Void Cheque', 'Bank Statement (31 days)', 'Pay Stub'] How, with a short line, could I map the first list into that last list in using the dictionnary? I know I could do it with simple for statement, but I want to code it under a single line in such a way I could return it inside a function... return your_code -
Hello, I am trying to create a supreme bot with python [on hold]
I need this bot to add the item to my basket, checkout and if possible, bypass captcha. This is all I have so far: import webbrowser webbrowser.open('http://www.supremenewyork.com/shop/all') from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from django.contrib import messages from .models import Cart, Jackets, Anorak @login_required def add_to_cart(request,jacket_id): jacket = get_object_or_404(Jacket, pk=jacket_id) cart,created = Cart.objects.get_or_create(user=request.user, active=True) order,created = Jacket Order.objects.get_or_create(jacket=jacket,cart=cart) order.quantity += 1 order.save() messages.success(request, "Cart updated!") return redirect('cart') -
in django rest framework I want to create a filter with relatedFilter and compare just with the last[by date]
in django rest framework I want to create a filter with relatedFilter and compare just with the last[by date] (current state of the document) https://paste2.org/wfY136Lt https://paste2.org/syCnmBkN class DocumentoFilterSet(FilterSet): nombre = filters.CharFilter(name="nombre", lookup_expr='icontains') descripción = filters.CharFilter(name="descripción", lookup_expr='icontains') estados = filters.RelatedFilter( HistoriaEstadoFilterSet, name='estados', queryset=Estado.objects.all() ) prueba = filters.CharFilter(name='estados', method='ultimoEstado') categorías = filters.RelatedFilter( HistoriaCategoríaFilterSet, name='categorías', queryset=Categoría.objects.all() ) class Meta: model = Documento fields = ['nombre', 'descripción', 'categorías', 'estados'] def ultimoEstado(self, qs, name, value): lookup_expr = LOOKUP_SEP.join([name, 'exact']) return qs.filter(**{lookup_expr: qs.estado()}) -
Passing from method, views to template
I have this method in my cart.py file. I am trying to work out how to pass the method to my views and templates but cant get it work. Method in cart.py: def count_prod(self, product) product_id = str(product.id) if product_id in self.cart: self.cart['product_id']['quantity'] Views.py: def count_prodview(request, product_id): cart = cart(request) product = get_object_or_404(Product, id=product_id) dict1 = cart.countprod(product) return render(request, 'shop/list.html',context=dict1) The end result I am looking for is for some button or heading tag to say 4 items in basket/cart. Any help is appreciated! -
Smaller Notifications Tab like Stack Overflow has
I'm trying to make a Notification system similar to Quora or Stack overflow. Whenever user clicks a button notifications should show up in a small window no matter at which page user is. But I couldn't do it. Since notifications are connected to a view & a url then firstly I need to go to the url & then click on notification button only then notifications show up in smaller window. How can I prevent myself from going to a URL connected to the view linked with Notifications & then click on notification button so that notifications will appear in smaller tab! Here's the url, url(r'^$', views.notifs, name='notifs') In View, def notifs(request): answers = Notifs.objects.filter(user=request.user) # not the actual method context = {'answers': answers} return render(request, 'base.html', context) In between base.html I have this "Notifications" link. Note: Here I have used jQuery to load the div that will show up the Notifications in smaller tab when it's clicked. <a href="{% url 'notifications:notifs' %}" class="a">Notifications</a> Here's that div on the same base.html page, <div class="b messMess myTab" hidden="hidden"> {% if answers %} {% for answer in answers %} Answer on{{ answer.question }}<br /> {% endfor %} {% endif %} </div> I … -
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!