Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Nginx not serve media files
I develop an application with Django and Angular 4, before I can see media files without problems in my localhost, but in my LightSailServer I delete my sock file created with gunicorn and deploy my app again, but I don't understand why I don't see my media files in this moment, this is my nginx file, but I don't touch this in all moment, I think my problem is in other way, any ideas? server { listen 80; server_name 54.12.12.142; location = /favicon.ico { alias /home/ubuntu/tracker-web/trackerServer/favicon.ico; } include /etc/nginx/mime.types; location /static/ { root /home/ubuntu/tracker-web/trackerServer; } location /media/ { autoindex on; alias /home/ubuntu/tracker-web/trackerServer/media/; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/tracker-web/trackerServer/trackerServer.sock; } } I don't see problems in this file, but I can't see my media files and these exists! PD: I obtain correct path to media files from my web server, only I can't see these. Thanks -
Django CORS Access-Control-Allow-Origin missing
I'm trying to implement google oauth2 authentication in my django app. I have followed all the steps as per the docs. On the browser address bar,if I browser this https://foo.bar.net/api/v1/auth/login/google-oauth2/ this url, it properly authenticated by google and it returns a google-auth-token to the mentioned redirect-url and it fetches the auth-token and converts it to a normal token which then sends to the user or frontend in json format. But if I tried to make a GET request to the above mentioned url from my js code, it shows Reason: CORS header 'Access-Control-Allow-Origin' missing Full traceback on the frontend looks like, GET https://foo.bar.net/api/v1/auth/login/google-oauth2/ 302 Found 718ms polyfil...ndle.js (line 7507) GET https://accounts.google.com/o/oauth2/auth?client_...DW&response_type=code&scope=openid+email+profile 200 OK Login Failed Response { _body=Event error, status=0, ok=false, more...} main.bundle.js (line 367) Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://accounts.google.com/o/oauth2/auth?client_id=kguygvh868697-khgkhvkgvkgkgv.apps.googleusercontent.com&redirect_uri=https://foo.bar.net/api/v1/auth/complete/google-oauth2/&state=Cbms1QhSQVzjO3xkjhkyuu&response_type=code&scope=openid+email+profile. (Reason: CORS header 'Access-Control-Allow-Origin' missing). I have searched google which prompts me to install djang-CORS-headers. I have installed and configured the above package. But the same error appears. A part of my settings.py looks like, MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'oauth2_provider.middleware.OAuth2TokenMiddleware', ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'oauth2_provider', 'corsheaders', 'rest_framework_swagger', … -
How do I use a form to update a model?
So what I'm trying to do is display a model on a page and then use a form to update said model on the page. I've managed to create a form and display it on the page, and I have managed to create to create a model--though I haven't gotten to display it on the page. This is what I have so far for the form: from django import forms class IndexForm(forms.Form): post = forms.CharField() This is my models: from django.db import models class Post(models.Model): post = models.CharField(max_length=141) And of course, my views. from django.shortcuts import render from firstapp.forms import IndexForm from django.views.generic import TemplateView from firstapp.models import Post class HomePage(TemplateView): template_name = 'home/home.html' def get(self, request): form = IndexForm() posts = Post.objects.all() args = {'form': form, 'posts': posts} return render(request, self.template_name, args) Now how would I go about changing this so the home page would display a form and a model with something like "Name:" and when you input your name in the form, the model would update itself to be "Name: [Your Name]"? -
Django REST group foreign key models
I have models like below. Menu Model class Menu(models.Model): name = models.CharField(max_length=40, unique=True, verbose_name='menu name') Item Model class Item(models.Model): class Meta: unique_together = ('shop', 'menu',) shop = models.ForeignKey(Shop) menu = models.ForeignKey(Menu) name = models.CharField(max_length=500) price = models.IntegerField(default=0) I want to get the menus for the shop id. Item.objects.filter(shop_id = 1) How can I group my results by menu name for the shop id 1. ? Sample. { menu: menuname1 items: [ {item1}, {item2}] }, { menu: menuname2 items: [ {item1}, {item2}] } Thanks.. -
Django: serving user uploaded files
I'm new to Django and Python.I want to display a link to my files stored in my static folder.Here is the required code from settings.py: MEDIA_ROOT = os.path.join(BASE_DIR,'static') MEDIA_URL = "/media/" When I access these files through my admin I get the following url displayed in my browser: http://127.0.0.1:8000/media/filename.pdf Hence what I tried is to give a link to the file in my HTML code : <a href="/{{instance.docFile.url}}/">File</a> But instead of displaying http://127.0.0.1:8000/media/filename.pdf it just displays /media/filename.pdf which results in an error. Adding localhost:8000/ before {{instance.docFile.url}} also didn't work. Why isn't this working?What is the correct way to display link to my files? Let me know if anything else is required.Thank you. -
Reverse for 'user_review_list' not found. 'user_review_list' is not a valid view function or pattern name
Even after going through similar STACKOVERFLOW solutions this doubt was not solved. I have also been through other resources. Been engaged in django since 2 days only !! :) project -> winerama app ->reviews my views.py > def review_list(request): latest_review_list =Review.objects.order_by('-pub_date')[:9] context ={'latest_review_list': latest_review_list} return render(request, 'reviews/review_list.html',context) def wine_list(request): wine_list =Wine.objects.order_by('-name') context ={'wine_list':wine_list} return render(request, 'reviews/wine_list.html',context) def review_detail(request , review_id): review = get_object_or_404(Review , pk = review_id) context = {'review':review} return render(request,'reviews/review_detail.html',context) def wine_detail(request , review_id): wine = get_object_or_404(Wine, pk = wine_id) context = {'wine':wine} return render(request,'reviews/wine_detail.html',context) def add_review(request,wine_id): wine = get_object_or_404(Wine , pk = wine_id) form = ReviewForm(request.POST) if form.is_valid(): rating = form.cleaned_data['rating'] comment = form.cleaned_data['comment'] user_name=form.cleaned_data['user_name'] review =Review() review.wine = wine review.user_name = user_name review.user_name = user_name review.rating =rating review.comment = comment review.pub_date = datetime.datetime.now() review.save() return HttpRespponseRedirect(reverse('reviews:wine_detail',args = (wine.id,))) return render(request,'reviews/wine_detail.html',{'wine':wine,'form':form})` reviews/urls.py urlpatterns = [ # ex: / url(r'^$', views.review_list, name='review_list'), # ex: /review/5/ url(r'^review/(?P<review_id>[0-9]+)/$', views.review_detail, name='review_detail'), # ex: /wine/ url(r'^wine$', views.wine_list, name='wine_list'), # ex: /wine/5/ url(r'^wine/(?P<wine_id>[0-9]+)/$', views.wine_detail, name='wine_detail'), url(r'^wine/(?P<wine_id>[0-9]+)/add_review/$', views.add_review, name='add_review'), ] reviews/templates/reviews/base.html {% block bootstrap3_content %} <div class="container"> <nav class="navbar navbar-default"> <div class="navbar-header"> <a class="navbar-brand" href="{% url 'review_list' %}">Winerama</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'wine_list' %}">Wine list</a></li> <li><a href="{% … -
Django - Admin forms data generation with fields which are not in model
I have a specific scenario and I am unable to figure out how to approach this problem, some direction will be great help: I have a model: class RollNumber(models.Model): r_no_prefix = models.CharField(max_length=10, verbose_name='Roll number suffix') r_no= models.IntegerField(verbose_name='Number') r_no_suffix = models.CharField(max_length=10, verbose_name='Roll number prefix') def __unicode__(self): return '%s -%s-%s' % (self.r_no_prefix,self.r_no,self.r_no_suffix) No, I want to generate these Roll numbers in bulk by asking the user to input the following in a form which is not having any of the above model fields. Number of roll numbers you want to generate: ____________ Roll number prefix: ________________ Roll number suffix: ________________ [SUBMIT][CANCEL] The submission of above form should be able to generate the number of rollnumbers and create records in RollNumber table in bulk. If I try to use this form again, if should get the last number and then start the sequence from there. Considering the that user may have deleted some of the roll number records. -
Django rating system
I am trying to implement a rating system on a Django website. I have done my rating with just one star (booleanfield) false/true : <!-- Favorite Album --> <a href="{% url 'music:favorite_album' album.id %}" class="btn btn-default btn-sm btn-favorite" role="button"> <span class="glyphicon glyphicon-star {% if album.is_favorite %}active{% endif %}"></span> </a> and this these are my album model : class Album(models.Model): user = models.ForeignKey(User, default=1) artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=100) album_logo = models.FileField() is_favorite = models.BooleanField(default=False) So, I want to know how to change this rating, so I will be able to select from 1 to 5 (in numbers) to rate the album. And by that, the album model should look like this I think : .......... is_favorite = models.IntegerField() .......... -
Django & Heroku | How to log 400 error in detail?
I have created an app on Heroku and I push my Django app to it. I monitor the logs using heroku logs --tail to see them in real time. How to display 400 error log in detail at such a production environment (when DEBUG=false)? I know debug.technical_500_response(request, *exc_info)method and use it for logging 400 errors, but it seems there is no technical_400_response method. I'm using Django 1.11.5 Python 3.6.1 whitenoise 3.3.0 Procfile web: gunicorn --env DJANGO_SETTINGS_MODULE=myapp.settings myapp.wsgi --log-file - settings.py LOGGING = { 'version': 1, 'formatters': { 'all': { 'format': '\t'.join([ "[%(levelname)s]", "asctime:%(asctime)s", "module:%(module)s", "message:%(message)s", "process:%(process)d", "thread:%(thread)d", ]) }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'django.log'), 'formatter': 'all', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'all' }, }, 'loggers': { 'command': { 'handlers': ['file', 'console'], 'level': 'DEBUG', }, }, } Thanks in advance. -
django rest create api to show count of distict field in a model
i'm amateur in Django Rest! i have a model named 'person' with some field 'name,family,tel,....' i want to create an api to show count of distict family my serializer: class PersonCountSerializer(ModelSerializer): class Meta: model = Person fields = 'family' my view: class PersonCountView(ModelViewSet): queryset = Person.objects.all().distinct('family').count serializer_class = PersonCountSerializer url: router.register(r'personcount', views.PersonCount) and it doesnt work,please help to fix it thanks -
Disadvantages of using ASGI instead of WSGI
What is the explicit and clear disadvantages of using ASGI instead of WSGI for HTTP request handling in Django in general? I know ASGI is for asynchronous tasks, but it can also handle synchronous HTTP requests via http.* channels. Is it slowly than normal WSGI or is there any unsupported features comparing to WSGI? One more, for providing both REST API and websocket handling in same project, which way do you prefer and why? WSGI for REST + ASGI for websocket in different server instances WSGI for REST + ASGI for websocket in same machine ASGI for both -
Django sitemaps while using Jinja2 templating
I am trying to set up a sitemap.xml on my Django project. However, I am currently experiencing this error: TemplateDoesNotExist at /sitemap.xml I have added sitemaps to my installed apps: INSTALLED_APPS = [ # Django base. 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sitemaps', 'django.contrib.staticfiles', # Own modules. ... ] This is my TEMPLATES configuration: TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': TEMPLATE_DIRS_, 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.messages.context_processors.messages', ], }, }, ] I thought it could be because I am missing the loader. I have tried adding it: TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': TEMPLATE_DIRS_, 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.messages.context_processors.messages', ], 'loaders': [ 'django.template.loaders.app_directories.Loader' ], }, }, ] When doing this, however, the error evolves into: ?: (templates.E001) You have 'APP_DIRS': True in your TEMPLATES but also specify 'loaders' in OPTIONS. Either remove APP_DIRS or remove the 'loaders' option. I need APP_DIRS for Jinja2. Even if I tried to set it to False, then the homepage (nor any page for that matter) would not load. Anyway to import sitemaps.xml from Django while keeping Jinja2? Thank you! -
Accessing ValidationError in PyCharm
I'm having issues with accessing ValidationError in the models.py file of my django app (running in PyCharm 2017.2.3): from django.core.exceptions import ValidationError ValidationError is underlined red, and hovering over it, it says "Unresolved reference to 'ValidationError'" Further, when looking up that file in 'External Libraries', that file (django.core.exceptions) has a different icon to the other python files, and no syntax highlighting. I've also tried to create my own 'exceptions.py' file in my app so I can define some commonly-used exceptions, and that file has the same issue (different icon, no syntax highlighting). Both issues are with files called 'exceptions.py', so I can't help but think they're connected somehow. While typing this, have also realised that if I start typing "from django.core.ex..", 'exceptions' isn't picked up/offered by the autocomplete feature. Running: PyCharm professional 2017.2.3 Python 3.6.2 in virtualenv Django 1.11.5 Have also tried a fresh install of everything, issue still exists.