Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I add new courses to EdX via api ? openedx has some built-in REST api for this or should we create custom api to add courses?
As we know EdX has the EdX studio which provides the UI to add new courses. say if we have like 3k courses, it is a tedious task to add each one of them manually through EdX studio. If we don't have any API in place can we create these api's on our own. I understand that edx-platform has the django-rest-framework out of the box. It should be possible to create custom API's but I am not sure how complex the model of EdX is as we have a number of functionalities and customizations associated with a course in EdX. -
How to rendering python variable in html template?
i need to change old value to new value in template file. Actually, when user enter 10 digits mobile number python function will call. if i check in log it's showing value but in html file it's showing value. how to get that value in second time? views.py from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def default(request): if request.is_ajax(): print("inside the ajax") phone_no = request.POST.get('phone_no') print(phone_no) dict = {'phone_no': phone_no} template_name = 'mobile_recharge.html' extended_template = 'base.html' dummy_var = 'test' print(dummy_var) if request.user.is_authenticated(): extended_template = 'base_login.html' return render(request,template_name, {'extended_template': extended_template,'phone_no': phone_no,'dummy_var': dummy_var}) template_name = 'mobile_recharge.html' extended_template = 'base.html' dummy_var = 'test' if request.user.is_authenticated(): extended_template = 'base_login.html' return render( request, template_name, {'extended_template': extended_template,'dummy_var': dummy_var} ) script <script type="text/javascript"> $(document).ready(function () { $('#phone_number').on('input', function () { if ($(this).val().length >= 10) { alert("user enter 10 digits numbers"); var phone_no = $('#phone_number').val() console.log(phone_no); $.ajax({ type: "POST", url: "http://localhost:8090/", data: {'phone_no' : phone_no}, dataType: "json", success: function(msg) { //alert(msg.phone_no); } }); return; } }); }); </script> html {{phone_no}} {{ dict }} {{dummy_var}} If i call above variables in templates. i didn't get any result. How to get result? -
IntegrityError at /accounts/regist_save/
I got an error, IntegrityError at /accounts/regist_save/ UNIQUE constraint failed: authtoken_token.user_id . The Traceback shows /Users/Desktop/accounts/views.py in regist_save user = form.save() ▶ Local vars I cannot understand why this part is wrong. I wrote in views.py @require_POST def regist_save(request): form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect('registration/accounts/index.html', context) context = { 'form': form, } return render(request, 'registration/accounts/regist.html', context) User regist form firstly had username&password validation system.They could work well.I added email validation system this time,but so I got this error.What can I do to fix it? -
Trying to use formset, getting __init__() got an unexpected keyword argument 'instance'
I need to use formset, and successfully implemented it for adding objects. But now i need to use formset for editing objects. I have following: models.py class Cell(models.Model): content = models.CharField(max_length=100) row = models.ForeignKey('Row') class Row(models.Model): pass forms.py class RowForm(forms.Form): cell = forms.CharField(label="Ячейка", max_length=100) number_of_cells = 5 RowFormset = formset_factory(RowForm, extra=number_of_cells) views.py def edit_row(request, row_pk): try: row = Row.objects.get(pk=row_pk) except Row.DoesNotExist: return HttpResponse('Такая строка не существует') if request.method == 'POST': formset = RowFormset(request.POST, instance=row) if formset.is_valid(): formset.save() return HttpResponseRedirect(reverse('table:index')) else: formset = RowFormset(instance=row) return render(request, 'table/edit-row.html', {'formset': formset}) Currently i'm getting TypeError: __init__() got an unexpected keyword argument 'instance'. How can i accomplish my task getting into account that using model form is likely not an option because model doesn't know anything about my cells, or the number of cells i should have in a row (so i presumably must stick to ordinary forms.Form). Thank you. -
Django (1.10.4) Migrations not applying datetime field changes(copies) in runpython
Changes in runpython are never applied for datetimefield. I'm adding a new datetimefield on a model with an optional default of timezone.now() model date = models.DateTimeField(default=timezone.now) migrations operations = [ migrations.RunPython(add_expense_date), migrations.AddField( model_name='expense', name='date', field=models.DateTimeField(default=django.utils.timezone.now), preserve_default=False, ),] I wrote a migrations.RunPython method that copies the values of another field _created_at to the new field date for existing fields. def add_expense_date(apps, schema_editor): Expense = apps.get_model("accounting", "Expense") db_alias = schema_editor.connection.alias for expense in Expense.objects.using(db_alias).all(): expense.date = expense._created_at expense.save() Problem is, it always applies the defaut value and never applies the changes in the runpython calls. The runpython methods do get called however. When I make the field nullable, it defaults all the values to null instead of the changes in the runpython call -
django : SetPasswordForm is not valid without error
This is my first time to use SetPasswordForm. The form is not valid but does not shows error message. So I'm having hard time to figure out which part went wrong. urls.py url(r'^password_change/(?P<username>[-\w.]+)/$', views.password_change, name='password_change'), url(r'^password_change_done/$', views.password_change_done, name='password_change_done'), When user input their new password and if the action succeeded, the page will redirect to password_change_done. views.py @login_required def password_change(request, username): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): oldpassword = form.cleaned_data.get('oldpassword') password1 = form.cleaned_data.get('password1') password2 = form.cleaned_data.get('password2') if password1 == password2: update_session_auth_hash(request, form.username) form.save() return HttpResponseRedirect('/blog/password_change_done/') else: return render(request, 'blog/profile.html', {'error_message': 'password mismatch'}) else: return render(request, 'blog/profile.html', {'error_messages': form.errors }) else: return redirect(reverse('blog:profile', args=[form.user.get_username()])) @login_required def password_change_done(request): return render(request, 'blog/password_change_done.html') forms.py class PasswordChangeForm(SetPasswordForm): error_messages = dict(SetPasswordForm.error_messages, **{ 'password_incorrect': ("Your old password was entered incorrectly. Please enter it again."), }) oldpassword = forms.CharField( label=("Old password"), strip=False, widget=forms.PasswordInput(attrs={'autofocus': True}), ) field_order = ['oldpassword', 'password1', 'password2'] def __init__(self, user, data, **kwargs): self.user = user super(PasswordChangeForm, self).__init__(data, **kwargs) def clean_oldpassword(self): oldpassword = self.cleaned_data["oldpassword"] if not self.user.check_password(oldpassword): raise forms.ValidationError( self.error_messages['password_incorrect'], code='password_incorrect', ) return oldpassword templates.py {{ form.errors }} {{ form.non_field_errors }} {% if error_message %} <h2><strong>{{ error_message }}</strong></h2> {% else %}<br> {% endif %} <form class="form-horizontal" role="form" action="{% url 'blog:password_change' user.username %}" method="post" … -
How to reuse django-model in elasticsearch and neo4j?
I am developing a django application in python. It consists several models. It makes uses of MySQL relation database. For certain features, it also makes use of elasticsearch and neo4J graph database. I am using elasticsearch_dsl library for elasticsearch and neomodel library for dealing with neo4j. For certain models, when new object is created, it's entered into elasticsearch and neo4j, along with MySQL. I am required to redefine same model(which i defined for django-orm)for elasticsearch_dsl and neomodel also. As a result, in my project, there're three different types of definition of same model. Is there any DRY way to do this ? I mean, I want to define model for django-orm and then elasticsearch_dsl and neomodel library automatically creates their model representation from django-model representation. Apologizing for poor english. Thanks in advance. -
UserCreationForm show error when fields are empty
I'm using Django built in UserCreationForm. I want to show message under the field when that field is empty and user tring to submit form. Unfortunatly I see only built-in behavior of browsers like "fill out this field", by the way in different browsers that behavior is different. Some browsers just encircle the field box with a red line. How to turn off this behavior and show message under the field. Why .error_messages didnt work?! Also I use {{ form.field_name.errors }} in my template. forms.py class RegistrationForm(UserCreationForm): required_css_class = 'required' email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name') def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) self.fields['username'].widget = TextInput(attrs={'placeholder': _('Username')}) self.fields['username'].required = True self.fields['username'].error_messages = {'required': 'Please enter your username'} self.fields['email'].widget = EmailInput(attrs={'placeholder': _('Email address')}) self.fields['email'].required = True self.fields['email'].error_messages = {'required': 'Please enter your email'} self.fields['first_name'].widget = TextInput(attrs={'placeholder': _('First name')}) self.fields['first_name'].required = True self.fields['first_name'].error_messages = {'required': 'Please enter your first_name'} self.fields['last_name'].widget = TextInput(attrs={'placeholder': _('Last name')}) self.fields['last_name'].required = True self.fields['last_name'].error_messages = {'required': 'Please enter your last_name'} self.fields['password1'].widget = PasswordInput(attrs={'placeholder': _('Password')}) self.fields['password1'].required = True self.fields['password1'].error_messages = {'required': 'Please enter your Password'} self.fields['password2'].widget = PasswordInput(attrs={'placeholder': _('Confirm password')}) self.fields['password2'].required = True self.fields['password2'].error_messages = … -
A page is not loaded
A page is not loaded. I got no error, but surely link is not good. I wrote in html file like, <button type="button" name="results" url="{% url 'results' %}"> <font size="10">Resulyshow</font> </button> in urls.py from django.conf.urls import url from . import views from django.views.generic import TemplateView urlpatterns = [ url(r'^results$', TemplateView.as_view(template_name='registration/accounts/result.html'), name='results'), ] I think,I should write url(..., name='page_name') in urls.py and {% url 'page_name' %} in html file.So,I wrote these code, but they could not work well.How can I fix this? -
Display Advertisement Based on Location of User
I have a website where I want to display advertisement based on location of a user. Like If a user visits from Place A he can see the adds related to Place A and same for person from Place B. -
Django and HTML5 application cache: index page is loaded from cache and csrf token is not available
I am using the latest django for my app, and recently I added application cache for the app to be available offline. I listed the necessary static resources in the CACHE list, for all other resourses I defined NETWORK *, so everything actually works as I expect. But there is such a problem - login fails due to incorrect csrf token in Google Chrome. It turns out that, even when online, Chrome loads the index page from cache and the fresh csrf cookies are not received, although I did not specify the index page in the list of cached resources. Is there any way to force load the index page when online? Or maybe you know some other work-around? In FF it works well, it loads the page from the server when online. I found one possible solution HTML5 cache and authorization issues but by default, django csrf token is changed per each request. -
Django Haystack Query
I am having a difficult time to figure out how to do a query with Djanog Haystack. I am using Elasticsearch as backend. I have a field which can be any string. And I want to query to get all entries that has any value in a list or empty. Here is an example: Let's say the field is called key and the strings in a list val_list = ['abc', 'def', ''] I tried SearchQuerySet().filter(key__in=val_list) But it does not work. I think the issue is with the empty string ''. I found some posts that use Raw("[* TO *]") to filter if a string is not empty and then use exclude to find empty ones. It works perfectly if it is used by itself. But how can I combine it with other possible values in the list? -
Django : 'function' object has no attribute 'ModelSelect2'
I've been working to make ajax autocomplete. I installed package autocomplete-light and tried to import select2 but failed. it displays error message like this. error message. 'function' object has no attribute 'ModelSelect2' settings.py INSTALLED_APPS = [ 'dal', 'dal_select2', 'dal_queryset_sequence', template.html <form action="{% url 'blog:ajax_article_autocomplete' %}" method="post"> <div class="ui-widget"> <label for="id_articles">search: </label> <input id="id_articles" type="text" size="50" name="articles" class="ui-autocomplete-input" autocomplete="off"> </div> </form> views.py from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.views.generic.edit import FormView from pip import autocomplete def ajax_article_autocomplete(request): if request.is_ajax(): q = request.GET.get('term', '') articles = Article.objects.filter(title__icontains = q )[:10] results = [] for article in articles: article_json = {} article_json['id'] = article.id article_json['label'] = article.title article_json['value'] = article.title results.append(article_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) urls.py url(r'^ajax/article/autocomplete/$', views.ajax_article_autocomplete, name='ajax_article_autocomplete'), forms.py class SearchForm(forms.ModelForm): class Meta: model = User fields = ('__all__') widgets = { 'title': autocomplete.ModelSelect2(url='ajax_tag_autocomplete') } -
Django Rest Swagger APIView
I made an API and want to make swagger doc. I don't develop any Serializes for that. Views.py class DeliveryView(APIView): renderer_classes = (XMLRenderer,) def get_campaign_vast(self, request, *args): return response def get(self, request): return self.get_campaign_vast(request, data) def post(self, request): """ This text is the description for this API --- param1 -- A first parameter param2 -- A second parameter """ data = request.data return self.get_campaign_vast(request, data) urls.py from django.conf.urls import url,include from django.contrib import admin from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='Add Delivery') urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',schema_view), url(r'^', include('deliverymanagment.urls')), ] I want to get all the parameters in Swagger which i am not getting. i am not able to get parameters i am using: django-rest-swagger==2.1.1 djangorestframework==3.5.3 -
Is it possible to use Python SpeechRecognition on Django?
I have the following script which works when running in a terminal: All is does is turn microphone speech to text. import speech_recognition as sr # obtain audio from microphone r = sr.Recognizer() with sr.Microphone() as source: print("Say something!") audio = r.listen(source) try: # for testing purposes, we're just using the default API key # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")` # instead of `r.recognize_google(audio)` print("Google Speech Recognition thinks you said " + r.recognize_google(audio)) except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e)) Would it be possible to have this work on Django after pushing a button? Something like: View: import speech_recognition as sr # Create your views here. def index(request): return render(request, 'app/index.html') def text(request): r = sr.Recognizer() with sr.Microphone() as source: #print("Say something!") audio = r.listen(source) try: # for testing purposes, we're just using the default API key # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")` # instead of `r.recognize_google(audio)` speech = r.recognize_google(audio) except sr.UnknownValueError: speech = "Google Speech Recognition could not understand audio" except sr.RequestError as e: speech = "Could not request results from Google Speech Recognition service; {0}".format(e) return … -
pass argument to view with reverse django
I have a view create_rating where after I submit a form I want it to be processed on a view rating_upload and then i want to redirect back to the create_rating view. Cant seem to get it to work, my latest code below. I would think when i click submit on the create-rating page that it should send video_id to rating_upload, and from there I can just send it back to create_rating as an argument. The docs show this too. I tried several things the latest error is what i have shown.. urls: urlpatterns = [ url(r'^upload', UploadVideo.as_view(), name='upload'), url(r'^(?P<pk>[0-9]+)/$', VideoView.as_view(), name='videoview'), url(r'^(?P<video_id>\d+)/create_rating', create_rating, name='create_rating'), url(r'^(?P<video_id>\d+)/rating_upload', rating_upload, name='rating_upload'), url(r'^(?P<video_id>\d+)/rating_uploaded', rating_upload, name='rating_upload') ] views: def create_rating(request, video_id): vid = get_object_or_404(Video, pk=video_id) past_ratings = vid.rating.order_by('date_created')[:5] template = loader.get_template('create_rating.html') context = { 'vid': vid, 'past_ratings': past_ratings } return HttpResponse(template.render(context, request)) def rating_upload(request, video_id): template = loader.get_template('rating_upload.html') rated_video = Video.objects.get(pk=video_id) context = { 'rated_video': rated_video } return HttpResponseRedirect(reverse('create_rating', video_id)) template, create_rating.html: <p>{{ vid.title }}</p> <form action="{% url 'rating_upload' vid.pk %}" method="post"> {% csrf_token %} <input type="text" name="rate_comment"> <input type="submit" value="Rate Video"> Latest error: Request Method: POST Request URL: http://127.0.0.1:8000/video/32/rating_uploaded Django Version: 1.10.5 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'video'] … -
Properly labeling multiple form fields with Django
I have a simple login screen with a Username and Password input, I want to label each field so that if a user were to click on 'Username' or 'Password' it would automatically toggle the control to the field. Like the Facebook homepage does for example. My problem is that I don't know how I should properly use the <input tags: <form action="/login/" method='post'> <label for='username_info'> Username </label> {% csrf_token %} {{ form.username }} <p> <label for="password_info"> Password </label> {{ form.password }} <p> <input id='username_info' type='submit'> </form> So that works for the Username text but not for the Password text obviously. How do I properly label each field? I looked at the Django Docs example but when I try to use a django template tag as the value attribute for the input tag it only displays the raw html in the field. -
Fill user profile on user registration with Django
I'm developing an application with the user default authentication provided by Django (and django-registration-redux). Also in docs, they recommend to link the user profile with a OneToOneField in a different model,as explain here: https://docs.djangoproject.com/en/1.10/topics/auth/customizing/ The problem is: How to build a registration view that includes the profile form? Note that it's only creating a user account with the basic data without profile info. I already have worked in other project inheriting from AbstractUser and customizing User Model but I would like this time use Profile model Can you help me? -
502 Bad Gateway with NGINX, Gunicorn, Django
I tried setting up a project with NGINX and Gunicorn using this guide. However, I keep getting a 502 Bad Gateway error. Here is my server conf: server { listen 80; server_name nexus-staging.chop.edu; access_log /webapps/nexus/logs/nginx/nexus-staging.chop.edu.access.log main; error_log /webapps/nexus/logs/nginx/nexus-staging.chop.edu.error.log warn; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /webapps/nexus/static_cdn; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/webapps/nexus/nexus.sock; } } Here is my gunicorn service file: [Unit] Description=gunicorn daemon After=network.target [Service] EnvironmentFile=/etc/sysconfig/nexus User=svc_dgdnexus Group=dgd_svc WorkingDirectory=/webapps/nexus ExecStart=/webapps/nexus/pyvenv/bin/gunicorn --workers 4 --bind unix:/webapps/nexus/nexus.sock django_config.wsgi:application --name nexus --access-logfile /webapps/nexus/logs/gunicorn/nexus-staging.chop.edu.access.log --error-logfile /webapps/nexus/logs/gunicorn/nexus-staging.chop.edu.error.log [Install] WantedBy=multi-user.target This is the nginx error: 2017/02/17 22:55:23 [error] 36168#0: *1 upstream prematurely closed connection while reading response header from upstream, client: 10.249.27.89, server: nexus-staging.chop.edu, request: "GET / HTTP/1.1", upstream: "http://unix:/webapps/nexus/nexus.sock:/", host: "nexus-staging.chop.edu" This is the gunicorn error: [2017-02-17 22:53:59 -0500] [36143] [INFO] Booting worker with pid: 36143 [2017-02-17 22:53:59 -0500] [36145] [INFO] Booting worker with pid: 36145 [2017-02-17 22:55:23 -0500] [36137] [CRITICAL] WORKER TIMEOUT (pid:36140) [2017-02-18 03:55:23 +0000] [36140] [INFO] Worker exiting (pid: 36140) [2017-02-17 22:55:23 -0500] [36202] [INFO] Booting worker with pid: 36202 -
Django WSGI error using Apache2
I'm running Django in VPS using Apache2 and wsgi but I am getting a 'no module named: Django' error when I access the domain, what could be wrong? here's my default.conf in apache2, <VirtualHost *:80> . . . Alias /static /home/sammy/myproject/static <Directory /home/sammy/myproject/static> Require all granted </Directory> <Directory /home/sammy/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-home=/home/sammy/myproject/myprojectenv python-path=/home/sammy/myproject WSGIProcessGroup myproject WSGIScriptAlias / /home/sammy/myproject/myproject/wsgi.py -
Why is Django is adding login/?next=/accounts/ to my HttpResponseRedirect?
I have a form that redirects a user to a different form depending on what account type they selected. This was working how I expected but now my HttpResponseRedirect is adding login/?next=/accounts/ in between the url. I cannot figure out why it stopped working. I have a project with an app called accounts. The form in my project: from django import forms USERTYPES = ( ('salon','Salon'), ('stylist', 'Stylist'), ('user', 'General User') ) class AccountTypeForm(forms.Form): userType = forms.ChoiceField(choices=USERTYPES, required=True,label='' ) urls in the project: from django.conf.urls import url, include from django.contrib import admin from . import views urlpatterns = [ url(r"^$", views.Home.as_view(), name="home"), url(r'^admin/', admin.site.urls), url(r'^account_type/$', views.AccountTypeView, name='account_type'), url(r"^accounts/", include("accounts.urls", namespace="accounts")), url(r"^accounts/", include("django.contrib.auth.urls")), ] views in my project: from django.core.urlresolvers import reverse from django.shortcuts import render from django.http import HttpResponseRedirect from django.views.generic import TemplateView from . import forms class Home(TemplateView): template_name = "index.html" def AccountTypeView(request): form = forms.AccountTypeForm() if request.method == "POST": form = forms.AccountTypeForm(request.POST) if form.is_valid(): if form.cleaned_data['userType'] == 'salon': #redirect to salon signup return HttpResponseRedirect(reverse('accounts:salon-signup')) elif form.cleaned_data['userType'] == 'stylist': #redirect to stylist signup return HttpResponseRedirect(reverse('accounts:stylist-signup')) elif form.cleaned_data['userType'] == 'user': #redirect to user signup return HttpResponseRedirect(reverse('accounts:user-signup')) return render(request, 'account_type.html', {'form': form}) urls in accounts app: from django.conf.urls import url from … -
Django - login with multiple DB
I'm facing a trouble today, I want to login from another database. I have one project where I'm having every table in my default database, I just added one more database only for loging system. so I have something like that: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'main.db'), }, 'db2': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'login.db') }, } I have created one user in my dafault database called user1 and user2 for database db2. I'm using https://django-registration-redux.readthedocs.io/en/latest/ for login I have been looking for internet for possible answers and no luck until now. is there a possible way to make my db2 to work for registration-redux ? Basically I want to make it work for db2 instead of my default, I mean I want to log in as user2 istead of user1. in both databases I have users created in auth_user. I don't know how to make it work for database db2. I was trying to look if a router could help me or something but I don't know. any help or any idea would be very very very appreciated :)!! I'm sorry if this question was answered before, I read so many answeres of my similar … -
Django mixer null value in column violates not-null constraint
I've just started using mixer with Django. My easiest test case fails because mixer isn't generating a value for a not null column. I started my project with cookiecutter: cookiecutter https://github.com/pydanny/cookiecutter-django Then I startapp orders users/models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_('Name of User'), blank=True, max_length=255) email = models.EmailField(_("email address"), unique=True) first_name = models.CharField(_("first name"), max_length=50) last_name = models.CharField(_("last name"), max_length=50) preferred_name = models.CharField(_("preferred name"), max_length=50, default="", blank=True) institution = models.CharField(_("institution"), default=None, max_length=200) group_lead = models.CharField(_("group leader"), default=None, max_length=200) account_number = models.CharField(_("account #"), default="", max_length=50, blank=True) address_street = models.CharField(_("street address"), default="", max_length=200, blank=True) address_street2 = models.CharField(_("street address cont..."), default="", max_length=200, blank=True) address_city = models.CharField(_("city"), default="", max_length=60, blank=True) address_zip = models.CharField(_("zip code"), max_length=5, default="", blank=True) address_country = models.CharField(_("country"), max_length=5, default="US", blank=True) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username}) orders/models.py class Order(DirtyFieldsMixin, models.Model): name = models.CharField(max_length=255) made_by = models.ForeignKey(settings.AUTH_USER_MODEL, models.PROTECT) status = models.ForeignKey('OrderStatus', models.PROTECT) date_accepted = models.DateField(blank=True, null=True) date_started = models.DateField(blank=True, null=True) … -
Django Celery Beat can't create table
I am getting this error when attempting to migrate for django celery beat: django.db.utils.OperationalError: (1005, "Can't create table 'django_celery_beat_crontabschedule' (errno: 13)") What I have done so far is follow this: http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#beat-custom-schedulers I ran "pip install django-celery-beat". Then, I added 'django_celery_beat' to my INSTALLED_APPS. But, when trying to run "python manage.py migrate", I get the error. Does anyone know how to fix this? -
django - how to replace repeated code in form validation
In my django forms.py file, I am trying to replace two occurrences of repeated validation code. Each attempt I make to have only one occurrence of each, does not seem to work. I cannot figure out how to write the code so that I have only one occurrence of each of the repeated code in the validation. It should be possible, but I cannot understand how to achieve this. I am hoping that someone can help me out as this has me confused. Here is my validation code: def clean(self): cd_cdf = super(CertificationDetailsForm, self).clean() # Must check the most specific cases first, then the general cases. if 'certification_type' in cd_cdf and cd_cdf['certification_type'] == '': self._errors['certification_type'] = self.error_class([_("This field is required.")]) elif 'certification_type' in cd_cdf and cd_cdf['certification_type'] == display_types.ENTER_MY_OWN_TYPE_DESCRIPTION: if 'certification_type_description' in cd_cdf and len(cd_cdf['certification_type_description'].strip()) == 0: self._errors['certification_type_description'] = self.error_class([_("This field is required.")]) # repeated code occurrence #1.1. if 'certification_title' in cd_cdf and len(cd_cdf['certification_title'].strip()) == 0: self._errors['certification_title'] = self.error_class([_("This field is required.")]) # repeated code occurrence #2.1. if 'certification_date' in cd_cdf and cd_cdf['certification_date'] is not None: if cd_cdf['certification_date'] > date.today(): self._errors['certification_date'] = self.error_class([_("Date must not be greater than today.")]) elif 'certification_type' in cd_cdf and cd_cdf['certification_type'] != display_types.ENTER_MY_OWN_DETAILS: # repeated code occurrence …