Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pytest: update Django DB in tests
I work on a library for Django using pytest 3.0.6 and pytest-django 3.1.2. I have this very simple test failing, and I don't understand what happen: # test_mytest.py import pytest from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType @pytest.mark.django_db def test_user_has_perm(django_user_model): # Create a new user john_doe = django_user_model.objects.create_user('johndoe', email='jd@example.com', password='123456') # Get or create the permission to set on user user_ct = ContentType.objects.get(app_label='auth', model='user') p, _ = Permission.objects.get_or_create(content_type=user_ct, codename='delete_user', name="Can delete user") # User don't have the permission assert john_doe.has_perm(p) is False # Set permission to user john_doe.user_permissions.add(p) assert john_doe.has_perm(p) is True # ---> FAIL When I put breakpoint to stop in the middle of the test, I see the Sqlite DB file is NOT on my disk. That sounds strange to me. Just in case, the result of the test is: $ pytest ============================= test session starts ============================= platform win32 -- Python 3.5.3, pytest-3.0.6, py-1.4.32, pluggy-0.4.0 Django settings: testsite.settings (from ini file) rootdir: D:\Dev\foss\django-modern-rpc, inifile: tox.ini plugins: pythonpath-0.7.1, django-3.1.2, cov-2.4.0 collected 1 items modernrpc\tests\test_test_test.py F ================================== FAILURES =================================== _____________________________ test_user_has_perm ______________________________ django_user_model = <class 'django.contrib.auth.models.User'> @pytest.mark.django_db def test_user_has_perm(django_user_model): # Create a new user john_doe = django_user_model.objects.create_user('johndoe', email='jd@example.com', password='123456') # Get or create the permission to set on user … -
Confirmation Email Sending via django-simple-email-confirmation
I am writing a code for sending a confirmation email to the one who has registered. I want to use django-simple-email-confirmation library, and I want to know how to manage my views.py file. Without this feature, my views.py code is like below: Please tell me how should I change it? class UserFormView(View): form_class=UserForm template_name='user_profile/register_form.html' def get(self,request): form=self.form_class(None) return render(request,self.template_name, {'form':form}) def post(self,request): form = self.form_class(request.POST) if form.is_valid(): user=form.save(commit=False) username=form.cleaned_data['username'] password=form.cleaned_data['password'] user.set_password(password) user.save() user=authenticate(username=username, password=password) if user is not None: if user.is_active: login(request,user) return redirect('user_profile:index') return render(request, self.template_name, {'form': form}) I would be thankful if you could help me in it. -
How to set resource name on an ad-hoc method of Viewset in Django Rest Framework JSON API?
I am using Django 1.10 with DRF 3.5 and Django Rest Framework JSON API 2.1.1. I have a Viewset that follows the normal pattern of a ModelViewset, but I need to add an ad-hoc as follows: class EnvoiViewSet(viewsets.ModelViewSet): queryset = Envoi.objects.none() serializer_class = EnvoiSerializer filter_class = EnvoiFilter ordering_fields = ('date_envoi',) # .... @decorators.list_route(methods=['post']) def ad_hoc_method(self, request): #.... My problem is that I want to change the resource name for the method but not for the class. Is this possible with a decorator or something like it ? For example: @decorators.list_route(methods=['post']) @resource_name('SpecialEnvoi') def ad_hoc_method(self, request): #.... -
Django: Model.objects.create, auto_now_add fields override my input
Given a model class Foo(models.Model): bar = models.DateTimeField(auto_now_add=True) When I do my_foo = Foo.objects.create(bar=yesterday) Then my_bar.foo is not yesterday but now. I have to do my_foo = Foo.objects.create() my_foo.bar = yesterday my_foo.save() This didn't use to be the case, but is true for Django 1.8.17 -
how to create mongodb backend for django application
how to integrate mongodb for my django application. i am using django version of 1.8... i made my settings as follows... enter code here DATABASES = { 'default': { 'ENGINE': 'django_mongodb_engine', 'NAME': 'projectdb', } } _MONGODB_USER = 'mani' _MONGODB_PASSWD = 'mani' _MONGODB_HOST = 'thehost' _MONGODB_NAME = 'projectdb' _MONGODB_DATABASE_HOST = \ 'mongodb://%s:%s@%s/%s' \ % (_MONGODB_USER, _MONGODB_PASSWD, _MONGODB_HOST, _MONGODB_NAME) mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST) AUTHENTICATION_BACKENDS = ( 'mongoengine.django.auth.MongoEngineBackend', ) but this doesnot work when i tried to syncdb -
running two instances of gunicorn
Trying to run two sites on gunicorn editing the service from [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/webapps/kenyabuzz ExecStart=/home/ubuntu/webapps/djangoenv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/webapps/kenyabuzz/kb.sock kb.wsgi:application [Install] WantedBy=multi-user.target to [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/webapps/kenyabuzz WorkingDirectory=/home/ubuntu/webapps/uganda_buzz ExecStart=/home/ubuntu/webapps/djangoenv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/webapps/kenyabuzz/kb.sock kb.wsgi:application ExecStart=/home/ubuntu/webapps/djangoenv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/webapps/uganda_buzz/ug.sock kb.wsgi:application [Install] WantedBy=multi-user.target the logs shows the exec start can't be duplicated ubuntu@ip-172-31-17-122:~$ sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: error (Reason: Invalid argument) Active: active (running) since Tue 2017-02-14 09:36:52 EAT; 35s ago Main PID: 26150 (gunicorn) CGroup: /system.slice/gunicorn.service ├─26150 /home/ubuntu/webapps/djangoenv/bin/python /home/ubuntu/webapps/djangoenv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/webapps/kenyabuzz/kb.sock kb.wsgi:application ├─26156 /home/ubuntu/webapps/djangoenv/bin/python /home/ubuntu/webapps/djangoenv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/webapps/kenyabuzz/kb.sock kb.wsgi:application ├─26157 /home/ubuntu/webapps/djangoenv/bin/python /home/ubuntu/webapps/djangoenv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/webapps/kenyabuzz/kb.sock kb.wsgi:application └─26160 /home/ubuntu/webapps/djangoenv/bin/python /home/ubuntu/webapps/djangoenv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/webapps/kenyabuzz/kb.sock kb.wsgi:application Feb 14 09:36:52 ip-172-31-17-122 systemd[1]: Started gunicorn daemon. Feb 14 09:36:52 ip-172-31-17-122 gunicorn[26150]: [2017-02-14 09:36:52 +0000] [26150] [INFO] Starting gunicorn 19.6.0 Feb 14 09:36:52 ip-172-31-17-122 gunicorn[26150]: [2017-02-14 09:36:52 +0000] [26150] [INFO] Listening at: unix:/home/ubuntu/webapps/kenyabuzz/kb.sock (26150) Feb 14 09:36:52 ip-172-31-17-122 gunicorn[26150]: [2017-02-14 09:36:52 +0000] [26150] [INFO] Using worker: sync Feb 14 09:36:52 ip-172-31-17-122 gunicorn[26150]: [2017-02-14 09:36:52 +0000] [26156] [INFO] Booting worker with pid: 26156 Feb 14 09:36:52 ip-172-31-17-122 gunicorn[26150]: [2017-02-14 09:36:52 +0000] [26157] [INFO] Booting worker with pid: … -
to open file witch contains hexa decimal value as TASK.txt.how can i convert that data into ascii value
"""this is my code""" import binascii import base64 from tkinter import * from tkinter.filedialog import askopenfilename def callback(): with open(askopenfilename(),'r') as r: next(r) for x in r: z = str(x[1:-2]) if len(z) % 2: z = '0' + 'x' + z print(binascii.unhexlify(z)) a = Button(text='select file', command=callback) a.pack() mainloop() """ this am getting error any body help me ================= RESTART: C:\Users\LENOVO\Downloads\hex2.py ================= Exception in Tkinter callback Traceback (most recent call last): File "D:\python sw\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "C:\Users\LENOVO\Downloads\hex2.py", line 16, in callback print(binascii.unhexlify(z)) binascii.Error: Non-hexadecimal digit found""" -
I have following error in my django code So please help me for this
I want to save data in my Db but there is type casting error in my code .So please help me to solve this issue The following is my code on Views.py: card.user_id = int((request.user.id)) card.card_no = int(request.POST['card-number']) card.expiray_month = request.POST['expiry-month'] card.expiray_year = request.POST['expiry-year'] card.card_type = 'Visa' #temp value change this value as per api #card.bank_id = 1 # temp value change this value as per api card.save() # Saving Card Details -
deploying Google Analytics on Django 1.9 website
I'm using django 1.9 and and i just hosted my website on digital ocean. I was thinking to add google analytics but i haven't used it before. I read some blogs but "context processors" confused me. What is context processors. How to deal with these? It will be better if you can guide from the beginning. Let's say my domain name is "example.in" and GOOGLE_ANALYTICS_PROPERTY_ID = UA-14845987-2. Thanks a lot! -
How insert form in base.html
This is my site: http://oriflame.pythonanywhere.com/ Each page is formed of two patterns: base (template for all page) and index, the main page. At the base you want to paste the application form for the call. But here's the problem: I want to insert in the parent template form made in forms.py. You can probably copy all views "form = CallForm ()" and the correct context, but maybe there is another solution? -
porting an existing database to lightadmin
Is there a quick way to create an admin utility over an existing database using LightAdmin? I am familiar with Django inspectdb utility and its very easy to create such a utility. But I am supposed to stick to Spring/Java ecosystem for developing this utility. Note: I am a novice to Spring ecosystem. -
Error in postgres database : table is not created
When I migrate my django application then in "Postgres" database "django_site" table is not created. Please help me to solve this problem. Thank you. -
Django-Celery in production?
So I've been trying to figure out how to make scheduled tasks, I've found Celery and been able to to make simple scheduled tasks. To do this I need to open up a command line and run celery -A proj beat for the tasks to happen. This works fine in a development environment, but when putting this into production that will be an issue. So how can I get celery to work without the command line use? When my production server is online, how can I make sure my scheduler goes up with it? Can Celery do this or do I need to go down another method? -
How to display a dropdown field __str__ in Django templates?
I've got a ModelForm where I can display either a foreignkey field which comes as a dropdown list ({{ form.auto_part }}) or the value or the ID of that foreignkey field which comes as a number ({{ form.auto_part.value }}). But I want to show the __str__ value of the foreignkey field. How can I do that? forms.py class AddCostPriceForm(forms.ModelForm): class Meta: model = Product fields = ['auto_part', 'cost_price'] models.py class Product(Timestamped): product_list = models.ForeignKey(List) auto_part = models.ForeignKey(AutoPart) quantity = models.SmallIntegerField() unit = models.CharField(max_length=20, default='pcs') cost_price = models.IntegerField(blank=True, null=True) class AutoPart(Timestamped): brand = models.ForeignKey(Brand) auto_type = models.ForeignKey(AutoType) part_no = models.CharField(max_length=50) description = models.CharField(max_length=255) def __str__(self): return "{brand} {auto_type} - {part_no}".format(brand=self.brand, auto_type=self.auto_type, part_no=self.part_no) -
How to render a form from another django app including error handling
on my landing page / home page I want to add a contact form and a subscribe to newsletter form. Since I want to keep the logic for both forms in separate apps I am wondering how I can use Django's internal form error handling in case the user does an input error. Similar to the standard form error handling I want that the landing page is reloaded with the errors next to the form fields. This is fairly easy if the logic stays within the same app but I can't wrap my head around it how to do this when the logic is in another app. Here is the basic layout: project/views.py: from django.views.generic.base import TemplateView from contact.forms import ContactForm from newsletter.forms import NewsletterForm class HomeView(TemplateView): template_name = "home.html" contact_form = ContactForm() newsletter_form = NewsletterForm() title = "Home" contact/forms.py from django import forms from .models import Contact class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ['contact_name', 'contact_email', 'content'] widgets = { 'contact_name': forms.TextInput(attrs={'placeholder': 'Your name'}), 'contact_email': forms.TextInput(attrs={'placeholder': 'Your Email address'}), 'content': forms.Textarea(attrs={'placeholder': 'Your message'}), } contact/models.py from django.db import models class Contact(models.Model): contact_name = models.CharField(max_length=120) contact_email = models.EmailField() content = models.TextField() timestamp = models.TimeField(auto_now_add=True, auto_now=False) def __str__(self): return … -
pushing django app to pivotal(Cloud Foundry)
pushing django app to pivotal(Cloud Foundry), it fails at the last stage, couldn't write proper Procfile. I diddn't find any tutorials about pushing django app to Cloud Foundary. Can anyone help? (i'll show logs) -
Can't log in to Django admin locally or in prod
I'm having two problems with my new Django admin, but I'm not sure if they're related so I don't want to split them into two questions just yet. The site is live and working--I went to the admin for the first time and got a csrf error. So I went back to my dev site and tried to log in, and it told me that my username/password was incorrect. I did python manage.py createsuperuser and still was unable to log in with the new user (credentials were definitely correct). Here are some of my settings files based on what seemed relevant from other askers. MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False X_FRAME_OPTIONS = "DENY" Note that the three Boolean values had previously been set to True. I changed them to False to experiment, and cleared cookies. No change. -
Django Call Built in validator from defined validator
Can I call a Built-in django validator from my own defined validator ? Here my form.py def validate_trx_no(value): if not re.match(r'^[A-Za-z0-9]+$',value) : raise forms.ValidationError("Invalid Document Number Format") elif #SomeBuiltInValidator like MinLengthValidator raise forms.ValidationError("Invalid Document Number Length") class TrxDetailForm(forms.Form): trx_no = forms.CharField(label='Number' ,required=True ,validators=[validate_trx_no]) Note : I know basicly it suposed to called from TrxDetailForm class, but I want to know is that possible to call it from validate_trx_no() ? -
Django : get data and edit in the same form, edit in one place
I've been working to make an edit form where shows data saved in db and user can edit it like jsp model and view. When user click button it shows add form but all the relevant information in db is already filled up in the form, so user can modifying old data and once they click submit button it redirect to main. I succeeded to display a form when user click edit button but failed to get data. this is views.py @login_required def update_article(request, article_no): article = get_object_or_404(Article, no=article_no) if request.method == "POST": form = ArticleForm(request.POST, instance=article) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('blog.views.detail', no=article.no) else: form = ArticleForm(instance=article) return render(request, 'blog/update_article.html', {'form': form}) urls.py url(r'^update_article/(?P<article_no>[0-9]+)/$', views.update_article, name='update_article'), update_article.html {% extends 'blog/base.html' %} {% block body %} <form class="form-horizontal" role="form" action="create_article.html" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include 'blog/form_template.html' %} <!-- <input class="u-full-width" type="text" name="title"/> <textarea class="u-full-width" name="content"></textarea> --> <button type="submit" class="button-primary">등록</button> </form> <a href="{% url 'blog:home' %}" class="button button-primary">list</a> {% endblock %} detail.html This is part of the page send users to update_article.html <form action="{% url 'blog:update_article' item.no %}" method="post" style="display: inline;"> {% csrf_token %} <input type="hidden" name="no" value="{{ item.no }}" /> <button type="submit" class="button-primary">edit</button> </form> -
User Interface/ Front End with Djngo
I'm in the process of developing a website for travel planner. It is my first time to use a web framework which will be Django, I have no idea about it, but I'm in the learning process. I'm trying to figure out how I can integrate my front end or the HTML, CSS, And java script into dingo. I mean I'm going for Django as a back end and I don't know if Django has the ability to facilitate a front end design, I'm concerned a lot about design, so I want to feel free to play around with the front end. So, is there is anyway that I can code my own pages in notpad++ and add them to djngo as web pages, or any platform I should use in order to integrate the fron end with Django? Just because prior to my research about Django the front end templating that Django provides has other scripts than css and html and I honestly have no idea what does that mean! So a little feedback about this would really make a huge help! Thanks in advance, Maryam -
Django Wagtail Project - Conflict with django.contrib.sites (using django-allauth)
I'm running into issues when adding a 3rd party 'user accounts' app to a Wagtail project. Most 3rd party user account apps (such as django-alluth) require django.contrib.sites as a dependency. When I include the django-allauth dependencies (including the required django.contrib.sites) in INSTALLED_APPS, along with wagtail.wagtailsite app, I run into issues with the site loading correctly (static files don't load correctly, for example). I am unable to track down exactly what isn't loading correctly, but from what I can tell, it is a runtime conflict between the wagtail 'sites' app and the django 'sites' app. It seems like there should be a way to have wagtail and django-allauth running side-by-side... Does anyone have django-alluth and wagtail working nicely together? Is it possible and what did you need to do? Any tips or examples of django-alluth and Wagtail working together are greatly appreciated. Versions: Django 1.10.1, Wagtail 1.8 -
How i can send model data in new field on template
How i can do custom fields for my Model and send it to tempalte? supp - new property for Dish model. If i do print (i.dish.supp) i will see Supplement objects But in template i don't have it... how i can get it in template. for order in userorders: for i in order.userorder.all(): i.dish.supp = Supplement.objects.filter( id__in=eval(i.supplements)).values('name') -
How to add function result to <p> tag in Django
I am trying to print the results of a function I have into a <p> tag once a button on that same HTML page has been clicked. I am working within a Django web application as well. Here is my function: def Question_Init(): Beginning_Question_Prompts = ("Who","Whom","What","Where","When","Why","Which", "Whose","How","Was","Were","Did","Do","Does") Ending_Question_Prompts = ("?",":","...") questions = [] text1 = open('/Users/joshuablew/Documents/myCorpus/version1.txt').read() textList = sent_tokenize(text1) for sentence in textList: if sentence.startswith(Beginning_Question_Prompts): questions.append(sentence) if sentence.endswith(Ending_Question_Prompts): questions.append(sentence) return questions I want to add the results of this function - which is the "questions" list - into the paragraph tag here: <div class="content"> <button type="button" class="btn btn-primary">Show Questions</button> <p>#Where I want the results of Question_Init() to go</p> </div> What must I do to the button attributes for this to happen? Should this be done with Javascript? Or can it be done some other way? Thanks for the help. -
Django: How can I manage Redis-server storage?
I saw some packages(django-redis-cache, django-redis-session) that store session or cache data in redis-server. I wonder how I can manage the redis-server storage then. I mean that if tons of cache or session data were stored in the redis-server, how can I delete some of data? I also use django-recommends (http://django-recommends.readthedocs.io/en/latest) and it also use redis-server as a storage. I think it store recommendation or similarity result datas in this storage... Need some advices. Thanks -
django-password-strength "meter" not updating
I am trying to implement a password strength "meter" using the django-password-strength library: https://github.com/noodlecake/nc-django-password-strength . The strength meter is able to render in the my change_password.html template, but doesn't update when I type something in the password field. Does anyone have any experience implementing this in their Django projects? Any help would be appreciated. Here is a link to my repo: https://github.com/brianweber2/project7_user_profile_with_django . Below are the main files of interests. Thanks! forms.py class ValidatingPasswordChangeForm(PasswordChangeForm): """Form for changing user's password.""" MIN_LENGTH = 14 class Media: js = ( 'js/zxcvbn.js', 'js/password-strength.js' ) new_password1 = forms.CharField( widget=PasswordStrengthInput(attrs={'placeholder': 'New password'}), label='New Password' ) new_password2 = forms.CharField( widget=PasswordConfirmationInput( attrs={'placeholder': 'Confirm new password'}, confirm_with='new_password1' ), label='Confirm Password' ) change_password.html {% extends 'layout.html' %} {% load static from staticfiles %} {% load bootstrap3 %} {% block title %} {{ block.super }} - Change Password {% endblock %} {% block header %} {{ form.media }} {% endblock %} {% block body %} <div class="form-container" style="max-width: 500px; margin: 0 auto;"> <h1>Change Password</h1> <form method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Change Password" class="button"> </form> </div> {% endblock %} settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'assets'), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'assets', 'media') MEDIA_URL = '/media/'