Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Render matplotlib image django
IΒ΄ve been trying to render a matplotlib graphic in Django in addition of some other objects like a form and some results. Currently the code is like this: plotter = plot_regions([ [(lambda x: (matrizRestricciones[0][2]-matrizRestricciones[0][0]*x)/matrizRestricciones[0][1],True), # x ^ 2 > 0 and (lambda x: (matrizRestricciones[1][2]-matrizRestricciones[1][0]*x)/matrizRestricciones[1][1],True)] # x + 5 > 0 ]) plt.grid() buffer = io.BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() graphIMG = PIL.Image.frombytes('RGB', canvas.get_width_height(), canvas.tostring_rgb()) graphIMG.save(buffer, "PNG") content_type = "Image/png" buffercontent = buffer.getvalue() graphic = io.StringIO canvas.print_png(graphic) return render(request, 'simplex.html',{'formulario': formulario, 'problemaSimplex': problemaSimplex, 'solucion': solucion, 'graphic': graphic}) but IΒ΄m getting this error: string argument expected, got 'bytes' in canvas.print_png() command. How to fix that? Thanks in advance. -
How can I remove a specific HTML tag in Django templates?
I tried to use striptags in a Django template, but it removes all HTML tags. I just want to remove a specific HTML tag, for example, <p> or <h1> tags. How can I do it? -
Django - Dispaly value of CommaSeparatedIntegerField
How can I display in HTML value of CommaSeparatedIntegerField ? Here is some code: models.py class Test(models.Model): oceny = models.CommaSeparatedIntegerField(max_length=150) def __str__(self): return "Test" Thanks for help ! -
How to solve double curly brackets issue when using Vue + Django template language?
I am using Django template language and would like to use Vue on my project. One main problem I encountered is {{...}} syntax. My Vue data is not rendered at all. <div id="app">{{ message }} // This is just empty on my page </div> And I am just using this basic Vue script: var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' } }) How do I solve this? -
Django Forms: Force the user to select one checkbox only at a time
I am using Django forms to display checkboxes on my webpage as following: class Myform(forms.Form): colors = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=COLORS) and it is working pretty well. My question is:: how to force the user to select only one checkbox at a time? My code allows the user to select multiple checkboxes at the same time. Thank you for your time. -
How do i integrate django CMS to work with existing django project templates so i can manage my front end content easily?
I have an existing django application that includes its own templates, now i want to use the capability of django CMS to enable the editing and updating of content in the front end easily.I have read the documentation and i understand that you use {% placeholder "" %} to include sections that you want to update, but i'm still not sure how or where to place the tags on my template or how to create them on the django CMS admin either. any explanation on this would be really appreciated. -
How to test if email was sent after executing celery task
I'm using Django 1.10 and Celery 4.1 I have a shared_task which sends an email to the user. # myapp/tasks.py @shared_task def notify_user(user_id): # TODO: send email and do other stuff here user = get_object_or_404(User, pk=user_id) send_mail( 'Subject', 'Body', 'from@example.com', [user.email], ) I have another file which contains a function that calls puts that tasks into the queue. # myapp/utils.py # ... def update_queue(self): # if user passes all requirements - notify user notify_user.apply_async((self.user_id,)) Now I am trying to test whether calling update_queue() (where all required checks passes) sends an email to the user when its executed. I tried to do the following: # myapp/tests.py def test_notify_user_should_send_an_email(self): with unittest.mock.patch('myapp.tasks.notify_user.apply_async') as notify_user_mock: # ... entry.update_queue() self.assertTrue(notify_user_mock.called) notify_user_mock.assert_called_with((user_id,)) # TODO: check if email was sent # I tried using : # self.assertEqual(len(mail.outbox), 1) # but it fails with error saying 0 != 1 I have set EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' in my project settings. Can someone please tell me what is wrong with what I am doing and how to correctly test this case? -
must i configure nginx for fb webhook?
i follow this article https://abhaykashyap.com/blog/post/tutorial-how-build-facebook-messenger-bot-using-django-ngrok for using fb bot to my django project. They used Ngrok but i have Ubuntu VPS so i passed this, at the end i send message to my page but no returns. Must i configure Nginx settings for this? Or how can i see to terminal? I mean , we can see the terminal which prints sending/receivng message to webhook when i type python manage.py runserver on localhost, but how can i see in a vps? -
Ajax, Vue component issue with csrf
At my Django project I try implement forms, with use Vue component and AJAX to connect with my DB, but I have problem with 403 Error. Can you help me? Thanks in advance! HTML: {% csrf_token %} <vue-form :state="formstate" v-model="formstate" @submit.prevent="onSubmit"> <validate auto-label class="form-group required-field" :class="fieldClassName(formstate.name)"> <label>Name:</label> <input type="name" name="name" class="form-control" required v-model.lazy="model.name" id="name"> <field-messages name="name" show="$touched || $submitted" class="form-control-feedback"> <div>Success!</div> <div slot="required">Name is a required field.</div> </field-messages> </validate> </validate> <div class="py-2 text-center"> <button class="btn btn-primary" id="submit" value="submit">submit</button> </div> </vue-form> script.js Vue.use(VueForm, { inputClasses: { valid: 'form-control-success', invalid: 'form-control-danger' } }); new Vue({ el: '#form', data: { formstate: {}, model: { name: '', } }, methods: { fieldClassName: function (field) { if(!field) { return ''; } if((field.$touched || field.$submitted) && field.$valid) { return 'has-success'; } if((field.$touched || field.$submitted) && field.$invalid) { return 'has-danger'; } }, onSubmit: function() { $.ajax({ type:'POST', url:'create', data:{ csrfmiddlewaretoken: '{{ csrf_token }}', name:$('#name').val(), }, success:function(){ } }); } } }); -
heroku local web is not working
it's my first time for me with heroku and i am trying to deploy my django project Everything is good when i run my server locally: python manage.py runserver but when i tried this: heroku local web i got this error [WARN] No ENV file found [WARN] Cannot read property '1' of null [FAIL] No Procfile and no package.json file found in Current Directory - See run_foreman.js --help i am pretty sure of the Procfile's path Procfile web: python manage.py runserver 0.0.0.0:5000 wsgi import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "omar.settings") application = get_wsgi_application() settings/local.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) SECRET_KEY = 'you dont have to know this :) ' DEBUG = True ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'django_hosts' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_hosts.middleware.HostsRequestMiddleware', 'django_hosts.middleware.HostsResponseMiddleware', ] ROOT_URLCONF = 'omar.urls' DEFAULT_HOST ="www" DEFAULT_REDIRECT_URL = "http://0.0.0.0:5000" PARENT_HOST = "0.0.0.0:5000" TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'omar.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, β¦ -
Check that ValidationError is actually the one I expect in a test
I have a test which creates a Django object "forgetting" to set one field. It should fail, so I check: p = Person.objects.create(name='test') self.assertRaises(ValidationError, p.full_clean) The forgotten field is birth_date, so if I intercepted the exception and printed it, the error would be: {'birth_date': ['This field cannot be blank.']}` Now I added another field to Person, which also shouldn't be left blank. The error now would be: {'birth_date': ['This field cannot be blank.'], 'category': ['This field cannot be blank.']} With the above code, I silently suppress both errors. I need to test that the code raises a specific validation error. Is there a good way to do it? For now I've this workaround: try: p.full_clean() except ValidationError as e: self.assertIn('birth_date', dict(e)) self.assertEqual(len(dict(e).keys()), 1, msg="Expected one error, found more") But if there could have been two different errors with 'birth_date', this would catch either. Is there a better way? -
Django cannot run with http
After open server, web only run without "http" url like this127.0.0.1:8000/blog/ and add http with 404 ERROR,where I did wrong? -
how to select user from auth_user django python for given username and hashed password
i am creating a python api that will return data from mysql database if the email and password are found in the database but the password is hashed, is their any way that i could hash the password entered from the api to compare it to the mysql password. i am using django.contrib.auth for creating new users that automatically created the table auth_user in the database containing the hashed password. i know one solution is to store the unencrypted password in another table but can it be done without creating another password field? i searched a lot and i couldn't find any solution. -
Django Rest Framework Nested Serializers Create NOT NULL Contraints
I'm trying to create a new model entry with nested serializers, but I am getting a NOT NULL constraint failed error. I'm not sure why models.py: class Messages(models.Model): sender = models.ForeignKey(User, related_name="sender") reciever = models.ForeignKey(User, related_name="reciever") message = models.TextField(null=True, blank=True) created_at = models.DateField(default=datetime.now) subject = models.CharField(max_length=150,blank=True) read = models.BooleanField(default=False) def __str__(self): return self.reciever.username Serializer class MessageSerializer(serializers.ModelSerializer): reciever = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) class Meta: model = Messages fields = '__all__' depth=1 def create(self,validated_data): print(validated_data) new_message = Messages.objects.create( sender = self.context['request'].user, # reciever = User.objects.filter(id=validated_data['reciever']), message = validated_data['message'], subject = validated_data['subject'], created_at = datetime.now(), ) new_message.save() return new_message POST request: { "reciever":12, "message":"Hello World", "subject":"newtest" } Response: IntegrityError at /api/messages/ NOT NULL constraint failed: index_messages.reciever_id -
How to override representation of a FilelField as its contents in Django Rest Framework?
Let's say I'm trying to serialize a Configuration model that looks like this: class Configuration(models.Model): name = models.CharField() data = models.FileField() The data is data that the front-end application needs to know for presentation purposes, but is of no use to the back-end. I want its serialized representation to accept and return data's content as a string, but for data's content to be actually stored in a file as it's of no relevance to the back-end application. Here's what I've got: class DataField(serializers.FileField): def to_internal_value(self, data): try: return data.read() except Exception as e: # not really sure what could turn up here raise ValidationError(e) class ForecastConfigSerializer(serializers.ModelSerializer): data = DataField() class Meta: model = Configuration fields = ('data', 'name',) This gives me a problem when django.db.models.fields.files wants to save: 'bytes' object has no attribute '_committed'. Fair enough, I'm probably screwing up things with to_internal_value as I read the data. I take it it works for serializing an instance, but not creating an instance from serialized data. How do I do this then? -
How should I give ForeignKey to model?
How should I give ForeignKey to model? Now models.py has User&Item table like from django.db import models # Create your models here. class User(models.Model): user_id = models.CharField(max_length=200) name_id = models.CharField(max_length=200) regist_date = models.DateTimeField(auto_now=True) class Item(models.Model): user_id = models.CharField(max_length=200) name = models.CharField(max_length=200) item_name = models.CharField(max_length=200) price = models.CharField(max_length=200) I wanna treat user_id&name_id as Foreing key.User table is parent table,and Item is child one.I think user_id&name_id in Item should have ForeignKey like class Item(models.Model): user_id = models.ForeignKey() name = models.ForeignKey() However,how should I connect these 2 model is User is parent&Item is child ?How should I write it? -
WSGI Mistake in Django
I try to deploy my project at pythonanywhere. My structure MyBlog β βββ blog β β βββ blog β β β βββ __init__.py β β β βββ __init__.pyc β β β βββ settings.py β β β βββ settings.pyc β β β βββ urls.py β β β βββ urls.pyc β β β βββ wsgi.py β β βββ db.sqlite3 β β βββ manage.py β β βββ posts β β β βββ __init__.py β β β βββ __init__.pyc ......... My wsgi file at server import os import sys path = '/home/Ivan/MyBlog' # use your own username here if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'blog.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() I got the mistake: Error running WSGI application ImportError: No module named blog.settings File "/var/www/ivan_pythonanywhere_com_wsgi.py", line 11, in <module> application = get_wsgi_application() what's the problem? -
Django - FileField invalid literal for int() with base 10: 'media'
I'm making simple blog website in Django and I got this error: invalid literal for int() with base 10: 'media'. It's happnes when I added FileField to models.py in my blog application. Here is some code: models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Roboczy'), ('publish', 'Publiczny') ) author = models.ForeignKey(User) title = models.CharField(max_length=140) slug = models.SlugField(max_length=140) image = models.FileField(blank=False, null=False, upload_to='media_cdn') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ['-publish'] def __str__(self): return self.title Here is part of settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn") And urls.py from django.conf import settings from django.conf.urls import url, include from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('blog.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Thanks a lot for help ! -
Create django groups based on attributes from the Admin Panel
I have I hope a simple question, how can I define three different groups based on three attributes. I extended my user model to include three boolean attributes: 1) is_HR 2) is_candidate 3) is_employee and I update my admin create user to be able to select those three my admin.py code look like this. # Register your models here. from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import MyUser class MyUserAdmin(UserAdmin): model = MyUser fieldsets = UserAdmin.fieldsets + ( (None, {'fields': ('is_hr','is_candidate','is_employee')}), ) admin.site.register(MyUser, MyUserAdmin) In the group admin panel I can only create groups base on permissions but not on attributes; How can I define groupes based on attributes and then give them different kind of permissions, Three groups based on if is_HR = True, is_candidate = True, is_employee = True Thx you very very much -
Dynamically alter form fields in views file-django
I was wondering if there is a way that i can alter a model form within the views.py file to create a multiple choice drop down field for form choices. I want to set each option on the choice field from the results of a queryset. for example: I want to from_acct fileld to have a scroll down option with the following list.. wells fargo chase tabz bank of america ** the list of banks are results of a query set. ** Here is what i have so far in the views.py file. form = TransferForm() form.fields['from_acct'].queryset = Accounts.objects.filter(user = currentUser).all() message = 'please fill out the below form' parameters = { 'form':form, 'currentUser':currentUser, 'message':message, } return render(request, 'tabs/user_balance.html', parameters) here is the forms.py file class TransferForm(forms.ModelForm): class Meta: model = Transfers fields = ['from_acct', 'to_acct', 'amount', 'memo'] labels = { 'from_acct':'from', 'to_acct':'to', } here is the model.py file class Transfers(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) from_acct = models.CharField(max_length=150, default='account') to_acct = models.CharField(max_length=150, default='accont') amount = models.DecimalField(decimal_places=2, max_digits=9, default=0) memo = models.CharField(max_length=200, default='memo') frequency = models.SmallIntegerField(default=1) status = models.SmallIntegerField(default=1) create = models.DateTimeField(auto_now_add=True) -
I am searching for a spell checker which is easily implemented to work with django and python 2.7
I want to check for a spelling mistakes while user is typing and it should support different languages. Thanks for your help guys -
How to serialize Django model for use in client-side application?
When designing a frontend webapp for a Django backend service, it would be nice to define the data model/validation code only once (using Django ORM). How can we serialize a Django data model, so that it can automatically generate (JavaScript) client-side forms and validation objects? Are there any notable projects or libraries bringing Django ORM/forms to client-side JavaScript frameworks? -
Blog matching query does not exist. (%3Fid=)
Used reverse() in the model`s method get_absolute_url(), but django raises an error - "DoesNotExist at /blog/detail/?id=23", becouse return not correct url - "/%3Fid=23" and urlpatterns haven't this in patterns, when I need the correct url - "/?id=23". Why this happens and how to fix it? urls.py (blog app) from django.conf.urls import url from django.contrib.auth.decorators import permission_required from blog.views import BlogListView, BlogDetailView, BlogCreate, BlogUpdate, BlogDelete urlpatterns = [ url(r'^$', BlogListView.as_view(), name = "blog"), url(r'^detail/(?:\?id=(?P<blog_id>\d+))?$', BlogDetailView.as_view(), name = "blog_detail"), url(r'^add/(?:\?id=(?P<blog_id>\d+))?$', permission_required("blog.add_blog")(BlogCreate.as_view()), name = "blog_add"), url(r'^edit/(?:\?id=(?P<blog_id>\d+))?$', permission_required("blog.change_blog")(BlogUpdate.as_view()), name = "blog_edit"), url(r'^delete/(?:\?id=(?P<blog_id>\d+))?$', permission_required("blog.delete_blog")(BlogDelete.as_view()), name = "blog_delete"), ] models.py (blog app) from django.db import models from datetime import datetime from taggit.managers import TaggableManager from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django_comments.moderation import CommentModerator, moderator from django.shortcuts import redirect # Create your models here. class Blog(models.Model): title = models.CharField(max_length = 100, unique_for_date = "posted", verbose_name = "Title") description = models.TextField(verbose_name = "Description") content = models.TextField(verbose_name = "Content") posted = models.DateTimeField(default = datetime.now(), db_index = True, verbose_name = "Posted") is_commentable = models.BooleanField(default = True, verbose_name = "Comments are allowed") tags = TaggableManager(blank = True, verbose_name = "Tags") user = models.ForeignKey(User, editable = False) def get_absolute_url(self): return reverse("blog_detail", kwargs = {"blog_id": self.pk}) class Meta: ordering = β¦ -
How to use foreign key in django ModelForm
I am trying to create a form based on ModelForm where, just like in django admin, someone will be able to select the foreign key field from a list of options. However when I do the following the input for the author appears blank. models.py : class Author(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Author_link(models.Model): url_text = models.CharField(max_length=100) url = models.CharField(max_length=200) author = models.ForeignKey(Author) def __str__(self): return self.url_text forms.py: class AuthorForm(forms.ModelForm): class Meta: model = Author fields = '__all__' class Author_linkForm(forms.ModelForm): class Meta: model = Author_link fields = '__all__' views.py : class CpanelAuthorLinks(TemplateView): template_name = "cpanel/authors.html" def get(self, request): form = Author_linkForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = Author_linkForm(request.POST) if form.is_valid(): form.save() return redirect('cpanel/authors-urls/') -
USE Raw SQL in Django
I recently migrated from PHP to django. I am creating a project which works on django.. I am used to write custom sql in php and hence i want to use raw() to filter results from my database in django. However i am not able to fully understand how django works.. Please find my code below. Currently i am receiving the below mentioned output [('11677795635',), ('12345',)] I want to use some for loop and print results in the below mentioned format. 11677795635 12345 can you please help me on how to for loop in django .. In PHP, the same was possible by $query=mysql_query("SELECT abcdashboard_customerinfo.customerbuyingid FROM abcdashboard_customerinfo WHERE abcdashboard_customerinfo.customerbuyingid in (select DISTINCT abcdashboard_orders.customerid from abcdashboard_orders)"); $queryrun=mysql_num_rows($query); for ($f=0; $f <$queryrun; $f++) { ${'customer'.$f}=mysql_result($query,$f, 'customerbuyingid'); echo ${'customer'.$f}; } models.py class customerinfo(models.Model): customerbuyingid = models.CharField(max_length=300, default='invalid customer id in database') customername = models.CharField(max_length=300, default='invalid customer name in database') customerphonenumber = models.CharField(max_length=12, default='0000000000') customermailid= models.CharField(max_length=80, default='email@email.com') class orders(models.Model): orderid = models.CharField(max_length=200) orderstatus = models.CharField(max_length=10) externalpurchaseid = models.CharField(max_length=100) externalstatus = models.CharField(max_length=100) customerid = models.CharField(max_length=100) ops = models.CharField(max_length=100) orderdate = models.DateField() updatedon = models.DateTimeField(default=timezone.now) views.py def index(request): all_customer = customerinfo.objects.all() cursor = connection.cursor() cursor.execute('''SELECT abcdashboard_customerinfo.customerbuyingid FROM abcdashboard_customerinfo WHERE abcdashboard_customerinfo.customerbuyingid in (select DISTINCT abcdashboard_orders.customerid from abcdashboard_orders) β¦