Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to set default value of model field from another model known field value?
I am new to Django and I am sure that this question has been asked before if it has been please link me in. I will try and explain exactly what I mean through an example. I have a biscuit/cookie tin and in my tin, I have packs of biscuits, chocolate circles (10 biscuits), vanilla wafers (15 biscuits), etc. I have made a model for the product (biscuit packs) that has contains the max number of biscuits per pack. from Django.db import models class Product(models.Model): barcode = models.CharField(max_length=200, primary_key=True) quantity = models.IntegerField() I want to have another model that contains the actual packs. When you create a pack with current_quantity defaulting to the product's quantity and as each biscuit is removed it can be decreased until 0. class Pack(models.Model): barcode = modes.ForeignKey(Product) current_quantity = models.IntegerField() So how do I get the model to get the Pack current_quantity to be the same as Product's quantity by default? If trying to do it in models is the wrong place to try and attempt this. I welcome better DRY KIS solutions. Thank you for your time. -
loop issue when inviting users
I am having trouble finding out my mistake. In my app I am creating a user that is set as inactive and then sending to those users a mail invitation to join my app. I set it up to be able to send multiple invitations but it only send one on the X invitations. So if I invite 5 people is only send and create 1 user. I guess there is something wrong with my loop but cannot find what.. here is my code views.py: def TeamRegister2(request): InviteFormSet = formset_factory(InviteForm2) if request.method == 'POST': formset = InviteFormSet(request.POST, prefix = 'pfix') if(formset.is_valid()): for i in formset: mail = i.cleaned_data['Email'] user = MyUser(email = mail) password = MyUser.objects.make_random_password() user.set_password(password) user.is_active = False user.is_employee = True user.save() u1 = user.id a1 = MyUser.objects.get(email = request.user.email) a2 = Project.objects.filter(project_hr_admin = a1) a3 = a2.latest('id') a4 = a3.team_id a4.members.add(u1) current_site = get_current_site(request) message = render_to_string('acc_active_email.html', { 'user':user, 'domain':current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) mail_subject = 'You have been invited to SoftScores.com please sign in to get access to the app' to_email = user.email email = EmailMessage(mail_subject, message, to=[to_email]) email.send() return HttpResponse('An email have been sent to each Team member asking them to join in') else: … -
Unknow Conections in console when active django server
Sorry for my bad english. I"ll try to make the question understandable. When i run the django server in the console appear this rare console logs (Like some sites is trying to do conect to it). This only happen when i make the site "public". Another website appear is this : apps.game.qq.com . Do you know what mean this message ? Some like "not find robot.txt" is like someone is trying to "index it" to some sort of search engine. Maybe this is a normal behavior when you make it public, if that is true. There is a way to block that specific conections? -
Message box styling using crsipy form in Django
After the form is successfully submitted, I would like to show a nice green box to display the success message. Code in views.py - upload.save() success = True messages.success(request, 'Result Uploaded Successfully.') In html file - {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} It displays as a bullet list. settings.py -- CRISPY_TEMPLATE_PACK = "bootstrap3" If there is any error then it displays in red box but not the form submit successfully message. Any help is highly appreciated. Thanks in advance. -
How can I get the post data from formdata
I am confusing how to get the data from ajax formdata. I only used get request until now. And I have never used formdata before. So, I don't know how can I handle the data. My client script is the following. var formData = new FormData(); formData.append('filename', image_file_name); formData.append('image', image_file); $.ajax({ url: HOST_NAME + "user/api/file_uploader/", type: 'POST', dataType: 'json', timeout: 10000, data: formData, processData: false, contentType: false }) .done(function (data) { console.log("success"); }) .fail(function (XMLHttpRequest, textStatus, errorThrown) { console.log("failed"); }) And my server side code is the following. def post(self, request, format=None): outputLogFile("Upload Function is called...") req_file_name = request.POST.form['filename'] req_image = request.POST.form['image'] I want to get the filename into req_file_name and get the image into req_image. But I have no idea what I should do to achieve this. Please give an advice. -
Twitter Typeahead notFound template does not render
I'm unable to get the notFound template to display on 0 results with Typeahead. The suggestions template renders fine with results as expected: templates: { suggestion: function(data) { img = '<img style="max-height:70px" src="' + data.thumbnail + '" width="45" class="hidden-xs"> '; return '<p>' + img + data.name + '</p>'; }, notFound: '<h2>empty</h2>' } There's no console errors. Do I need to return something special from the Django backend, I've tried None and an empty string with no success: results = [ {'name': item.name[0:50], 'url': item.get_absolute_url(), 'thumbnail': item.get_thumbnail()} for item in matching_items] data = json.dumps(results) return HttpResponse(data, content_type='application/json') -
Filtering Questions received max Answers in last 24 hours
Here's the model, class Question(models.Model): .... class Answer(models.Model): question = models.ForeignKey(Question) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) I wants to filter out the questions which received maximum answers in last 24 hours. How it can I filter them out? Please help me. Thank You! -
How can I authenticate user using Django websockets?
I try to create a chatbot. Every user can create an account and authenticate using Tokens. This is done in Django Rest Framework. After creating an account every user has own ID in PostgreSQL database. However chat is based on a websockets. I wonder how can I set session in websockets because I need to know which user sends message. So it seems to me that the best solution would be to have the same ID using both DRF and websockets. Or maybe am I wrong? I try in the way shown below but without positive results. @channel_session_user_from_http def msg_consumer(message): text = message.content.get('text') Message.objects.create( message=text, ) Group("chat").send({'text': text}) @channel_session_user_from_http def ws_connect(message): # Accept the connection message.reply_channel.send({"accept": True}) # Add to the chat group Group("chat").add(message.reply_channel) message.reply_channel.send({ "text": json.dumps({ 'message': 'Welcome' }) }) # @enforce_ordering @channel_session_user_from_http def ws_receive(message): message.reply_channel.send({"accept": True}) print("Backend received message: " + message.content['text']) Message.objects.create( message = message.content['text'], ) Channel("chat").send({ "text": json.dumps({ 'message': 'Can we start?' }) }) @channel_session_user_from_http def ws_disconnect(message): Group("chat").discard(message.reply_channel) -
How to display data on dynamodb in django admin page?
My django project have a postgres database to contain user data. And also I have items on dynamodb. With the help of django admin, showing all information about users on admin page is done easily. But I wonder if there are any ways to display and filter data on dynamodb like the ones on postgres? -
app not showing in django admin site
i am trying to add app in django admin site, but the app is not showing, i have searched other questions for answer but they are almost 7 years old and it's all becoming very confusing, can someone help me please. In settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', ] Following is the code in project's urls.py from django.conf.urls import url from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^admin/', admin.site.urls), ] -
Django: How to reference a AutoField?
I have a data model like this: class MaterialType(models.Model): materialType_id = models.AutoField(primary_key=True) materialType_name = models.CharField(max_length=20) parentNode_id = models.IntegerField() The third row in the class wants to reference to another materialType's id, just like in the first row. but the first row is an AutoField, I guess I could use IntegerField to reference it? Could you give some hint to solve this problem? -
PyCharm launching Django console for Flask app
For whatever reason, PyCharm thinks my Flask project is a Django project, and thus launches a Django console instead of a Python console in the toolbar: The project interpreter is configured properly: Here is my project hierarchy, if it's relevant: . ├── LICENSE ├── README.md ├── app │ ├── __init__.py │ ├── email.py │ ├── main │ │ ├── __init__.py │ │ ├── errors.py │ │ ├── forms.py │ │ └── views.py │ ├── models.py │ ├── static │ │ └── favicon.ico │ └── templates │ ├── 404.html │ ├── 500.html │ ├── base.html │ ├── index.html │ └── mail │ ├── new_user.html │ └── new_user.txt ├── config.py ├── data-dev.sqlite ├── data-test.sqlite ├── manage.py ├── migrations │ ├── README │ ├── alembic.ini │ ├── env.py │ ├── script.py.mako │ └── versions │ ├── 38c4e85512a9_initial_migration.py ├── requirements.txt └── tests ├── __init__.py └── test_basics.py Just because there is a module called manage.py doesn't mean I'm working on a Django project! How can I fix this?