Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to take a uploaded file in django and pass to a function
Hi upload csv files in the media folder and now i want to take this files to pass a list in python to make a pdf. How can i call this files in a fucntion in django or there is a better way to do it?? This is how i upload the files: def subir_archivos(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'subir_csv.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'subir_csv.html') And the method to pass a csv to a python list: def csv_empresas(request): lista = [] with open('media/empresas.csv') as csvfile: lector = csv.reader(csvfile, delimiter=',',quotechar='|') for row in lector: lista.append(row) return render(request,'preparar_pdf.html',{"lista": lista}) -
Generate uuid for User Model id field
I am trying to extend a User model and add some fields and below is my approach Class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) mobile_number = models.CharField(max_length=20) gender = models.CharField(max_length=2, choices=GENDER_CHOICES) location = models.ForeignKey(Location, blank=True, null=True) class User_One(UserProfile): field_1 = models.CharField(max_length=20) .... .... class User_Two(UserProfile): field_1 = models.CharField(max_length=20) .... .... So basically there are two types of users User_One and User_Two and now whenever we save the two types of users in to database the following happens A User model record will be created with separate id of values 1,2,3 etc., A User_One model record will be created with id's 1,2,3 A User_Two model record will be created with id's 1,2,3 So for each every model record saving, django or database was generating id's 1,2,3. But i got a requirement that User model should generate a uuid for id field value in place of integers, was that possbile ? I mean something like below class User_Profile(models.Model): id = models.IntegerField(default=uuid.uuid4) -
Custom Django user model with UUID as the id field
I am trying to extend a User model and add some fields and below is my approach: Class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) mobile_number = models.CharField(max_length=20) gender = models.CharField(max_length=2, choices=GENDER_CHOICES) location = models.ForeignKey(Location, blank=True, null=True) class User_One(UserProfile): field_1 = models.CharField(max_length=20) .... .... class User_Two(UserProfile): field_1 = models.CharField(max_length=20) .... .... So basically there are two types of users User_One and User_Two and now whenever we save the two types of users into database the following happens A User model record will be created with separate id of values 1,2,3 etc., A User_One model record will be created with id's 1,2,3 A User_Two model record will be created with id's 1,2,3 So for each every model record saving, Django or database was generating id's 1,2,3. But I got a requirement that User model should generate a uuid for id field value in place of integers, was that possible? I mean something like below class User_Profile(models.Model): id = models.IntegerField(default=uuid.uuid4) -
Django points to different locations for static files
I have deployed django website on debian 8 vps. The static files are held in static folder witch is at the same level as the app folder. The server can reach them on debian VPS. However the development version is located on Windows10 machine. The files are identical (cloned git repositories) but in the developement version tI get 400 when I try to reach my static files. From my setting.py file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT=os.path.join(BASE_DIR, 'static') -
Django points to different locations for static files
I have deployed django website on debian 8 vps. The static files are held in static folder witch is at the same level as the app folder. The server can reach them on debian VPS. However the development version is located on Windows10 machine. The files are identical (cloned git repositories) but in the developement version tI get 404 on static/css/ when I try to reach my static files. From my setting.py file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT=os.path.join(BASE_DIR, 'static') UPDATE: I have moved my files to project_name/app_name/static (just as it is recommended in django documentation ) in both versions of the project. The effect is that now development server sees the files and deployed version does not (i.e. it displays raw html without any css styles) - so exactly the opposite to the previous situation. I am out of ideas. (maybe it has something to do with the fact that at certain point I did collectstatic so I have static folder in two locations???) -
Django Models.filefiled file dosent exist
I wish to access the file i upload using models.FileField(), but its shows different path when i click on the link provided in the admin page. May i know what's the problem here? -
Django Models.filefiled file dosent exist
I wish to access the file i upload using models.FileField(), but its shows different path when i click on the link provided in the admin page. May i know what's the problem here? Updated my code, but the url dosent seem corret. getting a 404 code error. -
how to add images to django
I can't add images to mya db in django. without images my code adds everything to db. Could you help me please. views.py: from django.shortcuts import render, redirect from .models import Announcement, Categories from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.contrib.auth.models import User def dobavit(request): if request.POST: ads=Announcement( title=request.POST.get('Title'), description=request.POST.get('Description'), phone_num=request.POST.get('Phone_number'), price=request.POST.get('Price'), first_image_original=request.FILES['file'],) ads.save() else: return render(request, 'announcement/dobavit.html') return HttpResponseRedirect('/announcement/example') and my models.py: from django.db import models from .forms import ImageUploadForm from django.contrib.auth.models import User from imagekit.models import ImageSpecField from imagekit.processors import Adjust, ResizeToFit, ResizeToFill class Announcement(models.Model): class Meta: db_table='announcements' title=models.CharField(max_length=250) description=models.CharField(max_length=300) phone_num=models.IntegerField() price=models.IntegerField() first_image_original=models.ImageField(upload_to='images/') -
how to add images to django
I can't add images to mya db in django. without images my code adds everything to db. Could you help me please. views.py: from django.shortcuts import render, redirect from .models import Announcement, Categories from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.contrib.auth.models import User def dobavit(request): if request.POST: ads=Announcement( title=request.POST.get('Title'), description=request.POST.get('Description'), phone_num=request.POST.get('Phone_number'), price=request.POST.get('Price'), first_image_original=request.FILES['file'],) ads.save() else: return render(request, 'announcement/dobavit.html') return HttpResponseRedirect('/announcement/example') and my models.py: from django.db import models from .forms import ImageUploadForm from django.contrib.auth.models import User from imagekit.models import ImageSpecField from imagekit.processors import Adjust, ResizeToFit, ResizeToFill class Announcement(models.Model): class Meta: db_table='announcements' title=models.CharField(max_length=250) description=models.CharField(max_length=300) phone_num=models.IntegerField() price=models.IntegerField() first_image_original=models.ImageField(upload_to='images/') HTML code: -
how to used python code to search for the number of xlsm file in a folder?
In a folder I have unknown xlsm file, how I used python code to do some searching and print out the number of the xlsm file. Anyone can share idea with me? -
how to used python code to search for the number of xlsm file in a folder?
In a folder I have unknown xlsm file, how I used python code to do some searching and print out the number of the xlsm file. Anyone can share idea with me? -
How to read / write to elasticsearch using Django REST framework?
I am trying to read / write to elasticsearch using Django REST framework. As a result of investigation, I found the following method using Elasticsearch DSL. elasticsearch-with-django-the-easy-way However, this method is written to the DB at the same time as elasticsearch. How can I write this in only elasticsearch? I'm sorry. My English is not very strong. -
How to read / write to elasticsearch using Django REST framework?
I am trying to read / write to elasticsearch using Django REST framework. As a result of investigation, I found the following method using Elasticsearch DSL. elasticsearch-with-django-the-easy-way However, this method is written to the DB at the same time as elasticsearch. How can I write this in only elasticsearch? I'm sorry. My English is not very strong. -
Count value based on same date in django query
am not able to sum value based on date. because the below table having same date but different time. I need to sum the value of same date. Date revenue "2017-05-22 06:49:44.246+02" 10 "2017-05-22 16:31:10.588288+02" 12 "2017-05-23 06:49:44.246+02" 5 "2017-05-23 16:31:10.588288+02" 6 I need to get the output like below. The above table have same date but different time Date sum 2017-05-22 22 2017-05-23 11 I did like this today = datetime.date.today() d = xxx.filter(date__year=today.year,date__month=today.month).values('date').annotate(date_revenue=Sum('revenue')) but it's not woring -
Count value based on same date in django query
am not able to sum value based on date. because the below table having same date but different time. I need to sum the value of same date. Date value "2017-05-22 06:49:44.246+02" 10 "2017-05-22 16:31:10.588288+02" 12 I need to get the output like below. The above table have same date but different time Date sum 2017-05-22 22 -
Django raises 404 error during HttpResponseRedirect but after refreshing, shows the current page
I have a page called 'Read Later' where the users read later posts are stored. I have the Read Later on the nav bar. Now, when the user has no read later posts and clicks on Read Later, the user is redirected back to the original page. I have a function based def for Read Later. views.py : def show_readlater(request, *args): global redirect global redirect_lock global return_address if not(redirect_lock): redirect = None else: redirect_lock = False if not(request.user.is_authenticated()): raise PermissionDenied else: user_instance = User.objects.get(username = request.user.username) userprofile_instance = UserProfile.objects.get(user = user_instance) readlater_objects = ReadLaterList.objects.all() readlater_list = [] count = 0 for x in readlater_objects: if x.username == request.user.username: readlater_post = Post.objects.get(slug = x.slug) readlater_list.append(readlater_post) count = count + 1 if count == 0 : redirect = "no_readlater" redirect_lock = True return HttpResponseRedirect(return_address) # The user is redirect back to the original page post_title = "Read Later" template = "posts/show_posts.html" dictionary = { "total_posts" : readlater_list, "title" : post_title, "count" : count, "redirect" : redirect, } return render(request, template, dictionary) Here, redirect is to display a message that no Read Later posts are there, in the original page. The issue is that, when the redirect happens, Django says page not found, … -
Django raises 404 error during HttpResponseRedirect but after refreshing, shows the current page
I have a page called 'Read Later' where the users read later posts are stored. I have the Read Later on the nav bar. Now, when the user has no read later posts and clicks on Read Later, the user is redirected back to the original page. I have a function based def for Read Later. views.py : def show_readlater(request, *args): global redirect global redirect_lock global return_address if not(redirect_lock): redirect = None else: redirect_lock = False if not(request.user.is_authenticated()): raise PermissionDenied else: user_instance = User.objects.get(username = request.user.username) userprofile_instance = UserProfile.objects.get(user = user_instance) readlater_objects = ReadLaterList.objects.all() readlater_list = [] count = 0 for x in readlater_objects: if x.username == request.user.username: readlater_post = Post.objects.get(slug = x.slug) readlater_list.append(readlater_post) count = count + 1 if count == 0 : redirect = "no_readlater" redirect_lock = True return HttpResponseRedirect(return_address) # The user is redirect back to the original page post_title = "Read Later" template = "posts/show_posts.html" dictionary = { "total_posts" : readlater_list, "title" : post_title, "count" : count, "redirect" : redirect, } return render(request, template, dictionary) Here, redirect is to display a message that no Read Later posts are there, in the original page. The issue is that, when the redirect happens, Django says page not found, … -
how to make the django project in live server
I have a small project with basic crud operations done in djnago, in my local it works fine, now I have uploaded it into a live domain, and run the project,It has run without any issues, Performing system checks... System check identified no issues (0 silenced). May 22, 2017 - 10:20:14 Django version 1.11.1, using settings 'callluge.settings' Starting development server at http://127.0.0.1:8001/ Quit the server with CONTROL-C. So far so good, Now my question is, how could I see this in browser, if i simply access http://127.0.0.1:8001/ browser shows "Unable to connect", if my domain name is say "osho.com", how should see the project interface in browser.Please help. -
How correctly save multiple files in django?
I need form where user can create article with several images. I use django-multiupload app for image field. I can select several images but when I try to submit the form I have message under the image field: "Field is empty and field is required". Where is my mistake? Why I have such message when image field is not empty? Also maybe someone can advice good examples or apps to save several images. I would be very grateful for any help. models.py: class Article(models.Model): description = models.TextField(_('Description')) class Image(models.Model): article= models.ForeignKey(Article, on_delete=models.CASCADE) image = models.FileField(_('Image'), upload_to='images/%Y/%m/%d/') forms.py: class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ('description', ) image = MultiFileField() def save(self, commit=True): instance = super(ArticleForm, self).save(commit) for each in self.cleaned_data['image']: Image.objects.create(image=each, article=instance) return instance views.py: def article_add(request): data = dict() if request.method == 'POST': article_form = ArticleForm(request.POST, request.FILES) if article_form.is_valid(): article = article_form.save(commit=False) ****** article.save() data['form_is_valid'] = True articles = Article.objects.all context = {'articles': articles} context.update(csrf(request)) data['html_article'] = render_to_string('project/article_list.html', context) else: data['form_is_valid'] = False else: article_form = ArticleForm() context = {'article_form': article_form} data['html_article_form'] = render_to_string('project/article_add.html', context, request=request) return JsonResponse(data) article_add.html: {% load widget_tweaks %} <form method="post" action="{% url 'article_add' %}" class="article-add-form"> {% csrf_token %} {% for field in … -
Wagtail Recaptcha Localhost - SSL: CERTIFICATE_VERIFY_FAILED
Let me know if more or different information needs to be provided. I don't want to add too much if it's unnecessary. I'm trying to incorporate Wagtail recaptcha to a contact me form. I can do the google captcha just fine, but once I hit submit I run into an error. I am currently running into this error: SSL: CERTIFICATE_VERIFY_FAILED which you can see here https://pastebin.com/4WaqX1xT In my current setup I'm using ./ngrok 8000. My wagtail application runs on localhost:8000 In my settings base.py I have this included to my INSTALLED_APPS INSTALLED_APPS = [ ... 'sslserver', 'captcha', 'wagtailcaptcha', ... ] That being said, I did try django-sslserver and received the same error. HTTPS was crossed out when I went to the url using HTTPS instead of HTTP. Also in base.py I am using Google Recaptcha's development keys. Using my actual keys also result in the same error being generated. RECAPTCHA_PUBLIC_KEY = '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI' RECAPTCHA_PRIVATE_KEY = '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe' NOCAPTCHA = True RECAPTCHA_USE_SSL = False SECURE_SSL_REDIRECT = False Other things I've tried: stunnel, I get a 403 regarding CSRF Verification Failure https://pastebin.com/JXWVWNJq My stunnel setup was from http://userpath.co/blog/a-simple-way-to-run-https-on-localhost/ Then I did the command below, but HTTPS was crossed out when I tried going to … -
Doesn't show image in browser using variables inside static tag
I need to concatenate two strings inside a static tag, i checked previous question about how to concatenate strings in django template and i found this answer, but when i used that solution, the broser (Firefox) doesn't show the image. Details: This is my code: {% with "images/my_twitter_wordcloud_"|add:user.id|add:"png" as image_static %} <center> <img src="{% static 'image_static' %}" width="650" height="350" style="margin-left: 10%;"/> </center> {% endwith %} When i ckecked the inspector in the browser, it showed the image like this: <img src="/static/image_static" style="margin-left: 10%;" height="350" width="650"> I think that it should be: <img src="/static/images/my_twitter_wordcloud_"|add:user.id|add:"png" style="margin-left: 10%;" height="350" width="650"> I checked the django documentation about add reference, and i tried using "" and "" after add, but It seems like django doesn't interpretate the variable, what i'm doing wrong? Thanks for your help. PD: i'm apologyze for my English. -
Django - Set a value before save
I am trying to create a wallet at the moment the user signs up, but when the user fills out the form he is not redirected to the home, so little is persisted in the bank and get an error Models.py =============================================== from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from coinbase.wallet.client import Client class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) key_simple = models.CharField(max_length=128, blank=True) key_secret = models.CharField(max_length=800, blank=True) wallet = models.CharField(max_length=30, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: client = Client('xxxxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxx') data_account = client.create_account(name= 'Wallet of %s' % user.name) profile.walletid = data_account['id'] data_address = client.create_address(data_account['id']) wallet_address_id = data_address['id'] profile.wallet = data_address['address'] Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() -
Applying bootsrap and custom css to {{form}} elements in django
I am trying to apply CSS to individual {{form}} fields on my html template. I am referencing this solved question: CSS styling in Django forms` using the answer I created my forms.py page as follows: from django import forms from .models import ContactInfo class ContactForm(forms.ModelForm): # class meta brings in the fields from models class Meta: model = ContactInfo # grab the fields from models ContactInfo class fields = ('Fullname') # specify which bootstrap class each html widget should take def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.fields['Fullname'].widget.attrs.update({'class': 'form-control'}) html using {{form}} elements: <div class="form-group"> <label for="id_Fullname">Full Name:</label> {{form.Fullname}} </div> The working html w/o usage of {{form}}: <div class="form-group"> <label for="fullname">Full Name:</label> <input type="text" class="form-control" id="fullname"> </div> How do I get the "label" tag to point to the id inside {{form.Fullname}}. My guess is it is not doing that right now hence it doesn't apply the css. That or the class i specified in the widgets in the forms.py is not working how I want it to. -
Charts.js 2.5 does not display in django
I am trying to get some charts displaying in my main view with Django version 1.11. I did some test to check if the JS libraries were working correctly by typing some alert("Success") but the alerts did not appear in my browser (Chrome version 58). Main HTML file: {% extends "personal_website/header.html"%} <script> {% block jquery %} var endpoint = 'statistics' //Code to display the charts var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); {% endblock %} // end of code to display charts </script> {% block content %} <div class ='row'> <div class="col-sm-12" url-endpoint='{% url "statistics" %}'> <h1>Statistics for week 21</h1> <canvas id="myChart" width="600" height="600"></canvas> … -
Angular filter for dropdown
I am new to angular and i am trying to build basic search + filter functionality I am able to get search working but i am having difficulty with filter on unique skills (1,2,3 in this example) I tried using "ng-click" and calling custom function but didn't get any solution here is my code example : <html lang="en"> <meta charset="UTF-8"> <title> Exercise</title> <!--Angular JS--> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script> var app = angular.module("app", []); app.controller('person', ['$scope', function($scope ){ $scope.players = [{"name" : 'commonABC', 'skill' : 1},{"name" : 'commonXYZ', 'skill' : 3},{"name": 'SAMEqwe', 'skill': 1},{"name": 'SAMEjkl', 'skill': 2}] $scope.search = function(row) { return (angular.lowercase(row.name).indexOf(angular.lowercase($scope.player_filter) || '') !== -1); }; }]); </script> </head> <body> <div ng-app="app"> <div ng-controller="person"> <input type="text" ng-model="player_filter" placeholder="search name"> <select> <option value=1>1</option> <option value=2>2</option> <option value=3>3</option> </select> <br><br> <div ng-repeat="player in players | filter: search"> <strong>name is :{{player.name}}</strong <br> <strong>and skill is :{{player.skill}}</strong> <hr> </div> </div> </div> </body> </html>