Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Query with just the date
In [97]: cust = CustomerProfile.objects.get(pk=100) In [98]: CustomerProfile.objects.filter(user__date_joined=datetime.datetime(2017, 7, 28)) Out[98]: <QuerySet []> In [99]: CustomerProfile.objects.filter(user__date_joined=datetime.datetime(2017, 7, 28, 14, 43, 51, 925548)) Out[99]: <QuerySet [<CustomerProfile: George George's customer profile>]> In [100]: cust Out[100]: <CustomerProfile: George George's customer profile> In [101]: cust.user.date_joined Out[101]: datetime.datetime(2017, 7, 28, 14, 43, 51, 925548) I am not sure why it is not working here just with the date 2017/07/28. Why is it empty with just the date? How could I obtain the last queryset with just the date and not all the stuff datetime.datetime(2017, 7, 28, 14, 43, 51, 925548) ? -
Django, MultiValueDictKeyError, how to solve?
I make like in tutorial, but nothing work, how to solve? if you have some ideas, which can help pls, tell me about it) and again stack ask add more text, what wrong with him? if only i had some text which can explain my head pain , i will be add it but i have no! THIS IS FULL TRACE BACK Traceback (most recent call last): File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\utils\datastructures.py", line 83, in __getitem__ list_ = super(MultiValueDict, self).__getitem__(key) KeyError: 'payment_method_nonce' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\src\orders\views.py", line 143, in pay_for_one_product nonce = request.POST["payment_method_nonce"] File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\utils\datastructures.py", line 85, in __getitem__ raise MultiValueDictKeyError(repr(key)) django.utils.datastructures.MultiValueDictKeyError: "'payment_method_nonce'" this is view def some_view(request): nonce_from_the_client = request.POST["payment_method_nonce"] amoun_of_pr = get_pr_from_bs.total_price_for_this_good result = braintree.Transaction.sale({ "amount": amoun_of_pr, "payment_method_nonce": nonce_from_the_client, "options": { "submit_for_settlement": True } }) if result.is_success: print("YES THAT'S WORK") else: print("YOU WAS **") return JsonResponse({"Successfully":"added"}) this is html <div id="pay_it_wrapper"> <div id="dropin-container"></div> </div> {% block scripts %} <script src="https://js.braintreegateway.com/web/dropin/1.7.0/js/dropin.min.js"></script> <script> $(document).ready(function(){ var button = document.querySelector('.pay_it'); braintree.dropin.create({ authorization: '{{ … -
how push to heroku non project files?
I have a project deployed on heroku. I then added Multilingal Model with pip install which now exists under my externalLibrairies\myvirtualenv\multigual_model I then changed in a non project file which is externalLibrairies\myvirtualenv\multigual_model\models.py\. The problem is that the project works fine locally, but not on heroku, since I didn't push the exernal file that I have changed. Is there is a way to push to heroku all your files and not just the project files? -
How to use default database in django testing
Now I want to test API using my default database as I need too many data first to mock the request so I don't want to setup test database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'bills_db', 'USER': 'root', 'PASSWORD': '****', } } How can I use it ? -
Relation does not exist error in Django
I know there are many questions about this problem, I looked through the solutions and unfortunately none of them worked for me. I created a new app called "usermanagement", and added a model to the app. After adding the model I added usermanagement to INSTALLED_APPS in settings. Then I ran python manage.py makemigrations, and python manage.py migrate. This all worked fine! The problems start when I try to add a new instance of the model to the database in the Python-Django shell, by using: a = ClubOfficial(name="randomName", email="randomemail@random.com"), and a.save(), I get the following error: django.db.utils.ProgrammingError: relation "usermanagement_clubofficial" does not exist LINE 1: INSERT INTO "usermanagement_clubofficial" ("name", "email") ... Below is the model code: class ClubOfficial(models.Model): name = models.CharField(max_length=254) email = models.EmailField(max_length=254) If it helps, I use postgresql, and have tried restarting the server. The other apps in the program also work perfectly fine, it is just usermanagemenet that has this problem. Does anyone know what could be going wrong? Thank you for your time! -
Should I use Django for simple website?
I have been learning the Django framework for the last few weeks and I need to create a simple website for a dentist. The site just needs to have a few pages with flat data. I was wondering whether using django for this sort of project is good? I am also not sure whether I need any applications for this except a contact form, the site will mostly contain only views and templates. Looking for some advices/recommendations. Thanks in advance, David -
MultiValueDictKeyError with braintree, how to solve WITH MY CODE?
I make like in tutorial, but nothing work, how to solve? I make like in tutorial, but nothing work, how to solve? I make like in tutorial, but nothing work, how to solve? THIS IS FULL TRACE BACK Traceback (most recent call last): File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\utils\datastructures.py", line 83, in __getitem__ list_ = super(MultiValueDict, self).__getitem__(key) KeyError: 'payment_method_nonce' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\src\orders\views.py", line 143, in pay_for_one_product nonce = request.POST["payment_method_nonce"] File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\django\utils\datastructures.py", line 85, in __getitem__ raise MultiValueDictKeyError(repr(key)) django.utils.datastructures.MultiValueDictKeyError: "'payment_method_nonce'" this is view def some_view(request): nonce = request.POST["payment_method_nonce"] result = braintree.Transaction.sale({ "amount":get_pr_from_bs.total_price_for_this_good, "payment_method_nonce":nonce }) if result.is_success: print("YES THAT'S WORK") else: print("YOU WAS FUCKED UP") return JsonResponse({"Successfully":"added"}) this is html <div id="pay_it_wrapper"> <form action="/orders/pay_for_one_product/" id="pay_it_form">{% csrf_token %}</form> </div> {% block scripts %} <script src="https://js.braintreegateway.com/v2/braintree.js" ></script> <script> $(document).ready(function(){ braintree.setup("{{ client_token }}", "dropin",{ container: "pay_it_form", paypal:{ singleUse: true, amount: "{{ one_product.total_price_for_this_good }}", currency: 'USD' } }) }) </script> {% endblock scripts %} -
Django messages are not shown if Google Data Saver plugin is used
I hava a simple Python 3.5/Django 1.10.8 app consisting of one main page with one form with submit button (it's test app for catching this bug). On submit the corresponging view redirects back: messages.add_message(request, messages.INFO, "succeed") return HttpResponseRedirect('/') When I open the web page from Chrome with Google data saver plugin disabled (i.e. disable it manually or use incognito mode), everything is fine - after redirect the "succeed" info message is displayed. When I open same page with GDS enabled (i.e. from chrome of any android phone or from desktop chrome with DSE plugin manually enabled) the "succeed" message is not displayed. There is simply no "_messages" in request.GET (I've checked this in developer console)! Setting cache-control to "no-transform" as suggested here does not help. Why GDS clears django messages? How can I fix it? I guess this because it proxifies traffic but it's only the guess and anyway I need a fix/workaround. Thanks! -
Is model cycling ok in Django?
Can't figure out how to get rid of cycle in my ERD (or model) graph. Every user can have multiple products and every product is on multiple pages (urls). I scan these products every day for their description, price etc. I want to store information like when the product has been scanned, how many urls had valid scan, datetime of product scanning (not url) etc. I've created a ProductScanning model which is created when first Url object is being scanned where I store such data. I can use ProductScanning when I want to compute average price of last scans like this: sum([x.price for x in product.productscannings.last().scans]) The problem is that, as you can see there is a cycle in this graph which I should probably avoid. Do you have any ideas? -
What do I get this error : match = date_re.match(value) TypeError: expected string or bytes-like object?
Hello All I am attempting to create a patient model form for a medical database using django. I want to derive age for DOB but I keep getting a type error that I cannot fix. The following is a layout of my algorithm. This is my code : from django.db import models from django.contrib.auth.models import User import datetime from django.utils.timezone import now from Self import settings class Identity_unique(models.Model): NIS_Identity = models.IntegerField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) date = models.DateTimeField(auto_now =True) First_Name = models.CharField(max_length = 100, default =0) Last_Name = models.CharField(max_length = 100, default=now) date_of_birth = models.DateField(max_length=8, default=now) patient_age = models.IntegerField(default=0) def __str__(self): Is_present = date.today() patient_age = Is_present.year - date_of_birth.year if Is_present.month < date_of_birth.month or Is_present.month == date_of_birth.month and Is_present.day < date_of_birth.day: patient_age -= 1 return self.patient_age contact = models.IntegerField() This is my ModelForm : from django import forms from .models import Identity_unique class Identity_form(forms.ModelForm): NIS_Identity = models.IntegerField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) date = models.DateTimeField(auto_now =True) First_Name = models.CharField(max_length = 100, default =0) Last_Name = models.CharField(max_length = 100, default=now) date_of_birth = models.DateField(max_length=8, default=now) patient_age = models.IntegerField(default=0) class Meta: model = Identity_unique fields = ('NIS_Identity','First_Name', 'Last_Name', 'date_of_birth', 'patient_age', 'Contact', ) This is my Template: {% extends 'base.html' %} {% block head%} {%endblock%} {%block body%} … -
Django sql query sql server
I am experiencing a very strange case : When running this query c.execute ('select * from banks_row_data where Record_id=544') test=c.fetchall() The result is None while when running : c.execute ('select * from banks_row_data') test=c.fetchall() The result is the entire table What am i doing wrong? Thanks -
NameError at /accounts/upload_save/ global name 'ContactForm' is not defined
I got an error,NameError at /accounts/upload_save/ global name 'ContactForm' is not defined . I am making photo upload system. Now views.py is like def upload(request, p_id): form = UserImageForm(request.POST or None) d = { 'p_id': p_id, 'form':form, } return render(request, 'registration/accounts/photo.html', d) @csrf_exempt def upload_save(request): photo_id = request.POST.get("p_id", "") if (photo_id): photo_obj = Post.objects.get(id=photo_id) else: photo_obj = Post() files = request.FILES.getlist("files[]") if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): return HttpResponseRedirect('registration/accounts/photo.html') else: photo_obj.image = files[0] photo_obj.image2 = files[1] photo_obj.image3 = files[2] photo_obj.save() photos = Post.objects.all() context = { 'photos': photos, } return render(request, 'registration/accounts/photo.html', context) Traceback says Traceback: File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/Users/xxx/Downloads/KenshinServer/accounts/views.py" in upload_save 120. form = ContactForm(request.POST) Exception Type: NameError at /accounts/upload_save/ Exception Value: global name 'ContactForm' is not defined] Before,I got an index out of range error in files = request.FILES.getlist("files[]"),I can understand why this error happens empty files cause it .So,I tried to use ContactForm and wrote my code by seeing sample code in django document.However,I got this error and I cannot understand … -
Django taggit form label
I've found a solution to render tags registered in taggit models as choices list by doing: from taggit.models import Tag class BlogPost(models.Model): tags = models.ForeignKey(Tag, on_delete=models.CASCADE, default='') (i changed something in taggit folder i guess, .... i forgot but i works without any problem ) but i would like to change label name ("Tags" by default) i tried in forms.py: imports ... class PostForm(forms.ModelForm): tag = [(i, i) for i in Tag.objects.all()] tags = forms.ChoiceField(label='another label name', choices=tag ) class Meta: model = BlogPost fields = ('tags',) it shows the result i expected but when i save or POST it return a form validation error 'Cannot assign "u'tag name'": "BlogPost.tags" must be a "Tag" instance.' so can someone handle this and thanks -
Count customers per period
In my django project, it is possible to show every customer in the application with CustomerProfile.objects.all() and find the creation date of a specific customer with In [12]: cust = CustomerProfile.objects.get(pk=100) In [13]: cust.user.date_joined Out[13]: datetime.datetime(2017, 7, 28, 14, 43, 51, 925548) In [14]: cust Out[14]: <CustomerProfile: FistName LastName's customer profile> According to the creation date, I would like to make a listing of how many customers has been created per day, week, month or year. An example of the result could be ... week 28 : [ 09/07/2017 - 15/07/2017 ] - Count : 201 customers ... I probably need a range start_date and end_date where we will list that kind of information. start_date will be the date of the first customer created and the start_week created would be the week of this first_date. Obviously, the end_date is the date of the last customer created and last_week is the week of this end_date. For instance, if I select Per week in the drop-down menu and press Apply in the form, I want to send information to my model in such I could code what I explained. So far I know how to count the number of client in a … -
TemplateDoesNotExist Django
I am new to Django. Getting this error (TemplateDoesNotExist ) when I refresh the page . My code looks like this : Project name : newsHtml urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', include('news.urls')), ] I have created another directory called news where files looks like this : views.py from django.http import HttpResponse from django.template import loader def index(request): template= loader.get_template('/home/index.html') return HttpResponse(template.render(request)) # def index(request): # return HttpResponse("<h1>its working<\h1>") urls.py from django.conf.urls import url from. import views urlpatterns = [ url(r'^$',views.index,name='index'), ] when i uncomment the HttpResponse i am getting the output . But not able to find why template is not working . my directory structure looks like this : First directory :newsHtml->settings.py,urls.py,wsgi.py Second directory:news->templates/home/index.html,views.py,urls.py I am not able to figure out what is missing . I am using Django 1.11.5. -
django request.POST is None
This is views.py class RegisterView(View): def get(self,request): register_form = RegisterForm() return render(request,'register.html',{'register_form':register_form}) def post(self,request): register_form = RegisterForm(request.POST) if register_form.is_valid(): pass class LoginView(View): def get(self,request): return render(request,'login.html',{}) def post(self,request): login_form = LoginForm(request.POST) if login_form.is_valid(): user_name = request.POST.get("username", '') pass_word = request.POST.get("password", '') user = authenticate(username=user_name, password=pass_word) if user is not None: login(request, user) return render(request, 'index.html') else: return render(request, 'login.html', {"msg": "User name or password error!"}) else: return render(request, 'login.html', {'login':login_form}) Why does register_form = RegisterForm(request.POST) and login_form = LoginForm(request.POST) return empty,I tried many ways to solve it but failed, so how should I write it? -
Django CSRFCOOKIE when DEBUG = False
I use CSRFCOOKIE secure on my server. It was working fine until I set DEBUG option to False. After that CSRFCOOKIE cookie disappeared on client. Why? And what can I do? -
static css is not fetching style in django
when i am trying to load my style sheet from static it not fetch and implement the css to my project my folder as goes onething\home\static\home in home i'm having style.cssu can check folder structure in image here is my base.html <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0"> <title>{% block title %}One Thing{% endblock %}</title> {% load staticfiles %} <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.pink-purple.min.css"/> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Lobster"> <link rel="stylesheet" type="text/css" href="{% static 'home/style.css' %}"/> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script> </head> </html> and my setting as go INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' but my css stylesheet is not loading. please help me where i did mistake -
Debugging Django in Eclipse. One request results in two separate requests
One thing that has bugged for some time now is this: I set a breakpoint somewhere in the code. Make a rgular HTTP get request. The execution stops at the breakpoint. I hit the F8 "continue" button. Another exact request comes along. Is this how the debugger works, or is it a bug, or some configuration I have messed up? I use python 2.7.X, Eclipse Neon 4.6.2. Any answers are appreciated. -
django auth login is not working
i am using django 1.11.4 cannot understand why this code is not working i am printing request.user.is_authenticated() before and after login but in both cases i get False if i login from /admin then the same user logsin user = authenticate(username='myuser',password='mypassword') if user is not None: if user.is_active: print("before",request.user.is_authenticated()) login(request,user) print("after",request.user.is_authenticated()) return HttpResponse("login success") else: return HttpResponse("account is disabled") else: return HttpResponse("invalid login") -
Python Requests with Json-API
I'm using Django, python 3.5 and trying to make request with json-Api (header - Content-Type = application/vnd.api+json) but it seems like it doesn't know that kind of payload. couldn't find also documentation in Requests library. Did anybody have any experience with that and can assist? header: Content-Type: application/vnd.api+json payload (part of it): { "data": { "type": "commands", "attributes": { "extension": { "type": "commands", "version": "1.0.0", "data": { "resourceId": "e7e35e43-c2a2-4670-bd4b-9db3f917b35f" } } }, "relationships": { "resources": { "data": [ { "type": "folder", "id": "1" } I'm getting response: {'error': {}, 'message': 'Unexpected token d in JSON at position 0'} -
Angular 4.3 httpclient empty response headers
I have an Django backend. And trying to get http headers from it by using: 1) Angular 4.3 Http (it is going to be deprecated) 2) Plain XmlHttprequest. 3) Angular 4.3 HttpClient 1) and 2) have headers. But 3) does not. Headers from 1): var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(this); console.log(xhttp.getAllResponseHeaders()); } }; xhttp.open("GET", "http://127.0.0.1:8000/csbg/survey/sometest/", true); xhttp.send(); Headers from 2): import { HttpModule} from '@angular/http'; this.http.get('http://127.0.0.1:8000/csbg/survey/sometest/') .subscribe( data=>{ console.log('GET OK') console.log(data) }, error=>{ console.log("GET ERROR: " + error); } ) Headers from (2) Headers from 3): import { HttpClient} from '@angular/common/http' this.http.get('http://127.0.0.1:8000/csbg/survey/sometest/', { observe: 'response' }) .subscribe( data=>{ console.log('GET OK') console.log(data) }, error=>{ console.log("GET ERROR: " + error); } ) There is no headers ! Why? Also, Why default Access-Control-Expose-Headers headers is not present in there: By default, only the 6 simple response headers are exposed: Cache-Control Content-Language Content-Type Expires Last-Modified Pragma but my custom header is ? -
how can I reqrite this by using inclusion template tags with arguments django
I have the following snippets: def chunk(it, size): it = iter(it) return iter(lambda: tuple(islice(it, size)), ()) @register.inclusion_tag('web/pages/french/news.html', takes_context=True) def fetch_french(context): news = Francais.objects.all().filter(categorie__titre=context).order_by('-id')[:3] return { 'french_group_list': list(chunk(news, 3)), } What I am willing to achieve is that my inclusion tag has to check whether the context passed contains the following words: politique, news, sports, technologie by filtering as I did news = Francais.objects.all().filter(categorie__titre=context).order_by('-id')[:3] in and return the correct french_group_list that will display one of the filtered categorie. When I do this: @register.inclusion_tag('web/pages/french/news.html', takes_context=True) def fetch_french(): news = Francais.objects.all().filter(categorie__titre="Politique").order_by('-id')[:3] return { 'french_group_list': list(chunk(news, 3)), } it works fine, but I want to be able to do it with a context parameter and with a filter tag has shown, I will be able to filter the correct catgorie. I will appreciate any help. -
Is it possible to more than one object description in Django?
In model class we can define th object description def __unicode__(self): return u'%s %s %s %s %s %s %s %s ' % ("ID:", self.id, "Active:", self.is_active, "Bilingual:", self.is_bilingual, "Description:" , self.description ) But sometimes I need different descriptions in different situations. Is it possible to maintain more than one description formats for same object in Django? -
How to combine dynamically created fields from django template with standard django form?
I use simple django form class MassPaymentForm(forms.ModelForm): class Meta: model = LeasePayment fields = ['payment_type', 'is_deposit', 'amount', 'method', 'payment_date', 'description'] On my template I have created few chained dropdowns using AJAX <form method="POST" class="form" action="" method="get"> <div class="form-group"> {% csrf_token %} <br><br> <b>Building:</b><br> <select name="building" id="building" onchange="getunit();"> <option id="-1">Select building</option> </select> <br> <b>Unit:</b><br> <select name="unit" id="unit" onchange="getlease();"> <option id="-1">Select unit</option> </select> <br> <b>Lease:</b><br> <select name="lease" id="lease" onchange="getleaseterm()"> <option id="-1">Select lease</option> </select> <br> <b>Term:</b><br> <select name="leaseterm" id="leaseterm"> <option id="-1">Select lease term</option> </select> {{ form|crispy}} {{ form.media }} <BR><BR> <button type="submit" class="btn btn-primary btn-primary">Save</button> </div> </form> I need 'lease' and 'leaseterm' to be part of my form when it saves since they are mandatory fields in the model.. How can I include those AJAx dynamically generated dropdown as part of my Django form?