Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is an efficient method to import a database into Django/Postgres?
I am working on a project using Django and Postgres.The previous version was done using other technology. How can I migrate the previous version to Django? The data is very large, so speed of import is critical. -
Internal Server Error 500 Django Ajax Form
url.py url(r'^open-signup-page/', 'zamapp.registration.open_signup_page', name='signup_page'), url(r'^signing-up/', 'zamapp.registration.signing_up', name='signing_in'), register.html <form id="signup_form"> {% csrf_token %} <div class="form-group"> <P id="error_msg"></P> </div> <div class="form-group"> <label class="control-label" for="FirstName">First Name*</label><label id="lbl_first_name" style="color:white">&nbsp Fill out First Name</label> <input type="text" placeholder="First Name" title="Please enter you first name" required="" value="" name="first_name" id="first_name" class="form-control"> </div> <div class="form-group"> <label class="control-label" for="LastName">Last Name*</label><label id="lbl_last_name" style="color:white">&nbsp Fill out Last Name</label> <input type="text" placeholder="Last Name" title="Please enter you last name" required="" value="" name="last_name" id="last_name" class="form-control"> </div> <div class="form-group"> <label class="control-label" for="username">Username*</label><label id="lbl_username" style="color:white">&nbsp Fill out Username</label> <input type="text" pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" placeholder="example@gmail.com" title="Please enter you username" required="" value="" name="username" id="username" class="form-control"> </div> <div class="form-group"> <label class="control-label" for="username">User Role*</label><label id="lbl_selectuserrole" style="color:white">&nbsp Please Select User Role</label> <select required class="form-control js-source-states" name="selectuserrole" id="selectuserrole"> {% for userrole in user_role_list %} <option value="{{ userrole.role_id }}">{{ userrole.role }}</option> {% endfor %} </select> </div> <div class="form-group"> <label class="control-label" for="password">Password*</label><label id="lbl_password" style="color:white">&nbsp Fill out Password</label> {% comment %}<input type="password" name="newpass" id="inputPassword" class="form-control" pattern="(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[*@#\$%&\?])^\D.{8,18}" placeholder="******" required="required" maxlength="15" data-error="Password must be between 8 to 18 characters, starts with letter and must contain one uppercase letter, one lowercase letter, one number and among these special characters &,*,$,%,^,#,@">{% endcomment %} <input type="password" data-toggle="validator" data-minlength="8" data-maxlength="15" title="Please enter your password" placeholder="******" required="" value="" name="password" id="password" class="form-control"/> <div id="pwd_policy"> <span … -
Django - issue with settings after changing the project structure
I have changed the structure of Django project containing several apps, and ended up with a thorny error ImportError: No module named my_project.settings settings.py import os import main BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'byw9_e0p$1x2a!snm!4n(#mq=vmn=s4cde1np$*a#y)3d@jft)' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'el_pagination', 'main', 'rest_framework', 'rest' ] 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', ] ROOT_URLCONF = 'main.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.dirname(BASE_DIR),"static","templates")], #'DIRS': [os.path.join(BASE_DIR,"templates")], '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 = 'wsgi.application' PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'main', 'USER': 'root', 'PASSWORD': '1234', 'HOST': '127.0.0.1', # Or an IP Address that your DB is hosted on 'PORT': '3306', 'default-character-set': 'utf8', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' if DEBUG: MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static","static-only") MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static","media") STATICFILES_DIRS = ( os.path.join(os.path.dirname(BASE_DIR),"static","static"), ) The project structure: my_project main init.py forms.py models.py urls.py views.py rest init.py admin.py apps.py serializers.py … -
Jmeter - django application non functional testing
I'm thinking on using Jmeter for django applications. I basically wanted to carry out the following tests on my django application. 1) Performance testing 2) Load testing 3) Capacity testing 4) Stress testing Will I be able to carry out all the testing methods in jmeter for my django app? I'm new here and yet to acquire basic knowledge on jmeter application. -
nginx url redirect to custom url
I have a domain binging a IP: a.a.com -> 1.1.1.1 In 1.1.1.1 has a nginx , for access a.a.com/bbb/ to 2.2.2.2's django service. ` #1.1.1.1 server { listen 8090; server_name localhost; location /bbb/ { proxy_pass 2.2.2.2:8000; } } ` when I input a.a.com/bbb/, I can access, it's ok. But when Django login's session timeout , It automatic redirect a.a.com:8090/bbb/. I want to ask how to automatic redirect a.a.com/bbb/. ps. the 8090 port cant access Sorry my poor English , Thanks. -
How to remove duplicate records from multiple lists in order in python
I have three list with four values in each list, I have to remove duplicate values from these three list Here are three lists country_list = ['USA', 'India', 'China', 'India'] city_list = ['New York', 'New Delhi', 'Beijing', 'New Delhi'] event_list = ['First Event', 'Second Event', 'Third Event', 'Second Event'] As its showing in all three lists "India", "new delhi", and Second event" are repeating, means they again are repeating with each other. I want to remove these repeating value, and wants the result like country_list = ['USA', 'India', 'China'] city_list = ['New York', 'New Delhi', 'Beijing'] event_list = ['First Event', 'Second Event', 'Third Event'] So how can i get this result is there any function for this ? -
Installing django-import-export raises ValueError
I'm trying to install django-import-export. Python version = 3.6 Django version = 1.10.3 When I entered: pip install django-import-export It says: raise ValueError("cannot use LOCALE flag with a str pattern") ValueError: cannot use LOCALE flag with a str pattern Thanks in advance. -
Using load_all() in searchqueryset and how to display all results in template
I am using haystack with elasticsearch. I am not able to display results on my search template, when I provide load_all() to searchqueryset. Urls.py urlpatterns = [ ... url(r'^doctor/search/all/$', FacetedSearchView(template="search/search.html",form_class = FacetedSearchForm,searchqueryset=SearchQuerySet().models(Doctor).facet('doctorLocation').load_all()), name='haystack_doctor_search'), ... ] In my template I am trying to get the results my doing this : {% for result in page.object_list %} <p> <a href="{{ result.object.get_absolute_url }}">{{ result.object }}</a> </p> {% endfor %} But the 'page' variable in the template contains nothing in it. How do I display all the objects in the searchqueryset in this template.? -
"next" is not redirecting to expected position
I am making a wallet app so if someone goes to http://127.0.0.1:8000/add_money/ to add money and they are not logged in they will be redirected to the login page with next there after the user logs in it should be redirected back to add_money but it is being redirected to their profile. //ADD MONEY VIEW def add_money(request): if not request.user.is_authenticated(): return render(request, 'registration/login.html', {"next": '/add_money/'}) else: if request.POST: username = request.user.username add_amount = request.POST['amount'] wallet = Wallet.objects.filter(username=username).update(add_money(add_amount)) now = datetime.now() trans = Transaction(from_name=username, wallet_id=wallet.id, date=now, amount=add_amount) trans.save() return render(request, 'user_profile.html', {'user': request.user}) return render(request, 'registration/login.html', {"next": '/add_money/'}) //Login View def user_login(request): if request.POST: username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) if request.POST['next']: return render(request, '/add_money/') return render(request, 'user_profile.html',{'user': user, 'wallet': user.userprofile.wallet_id}) else: return render(request, 'registration/login.html', {'error': 'User is not active'}) else: return render(request, 'registration/login.html', {'error': 'User does not exist'}) else: return render(request,'registration/login.html') //login template {% if next %} <form action="/login/?next={{next}}" method="post"> <input type="hidden" name="next" value={{ next }}> {%else%} <form action="/login/" method="post" > {% endif %} USERNAME <input type="text" name="username"> PASSWORD <input type="password" name="password"> <input type="submit"> <input type="hidden" name="next"> {% csrf_token %} </form> //add_money template <form action="user_profile.html" method="post"> Amount:<input … -
Error when running makemigrations on django project
I am running a new django project and when I run makemigrations I get this error : ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'login.stylista', but app 'login' isn't installed. The field authtoken.Token.user was declared with a lazy reference to 'login.stylista', but app 'login' isn't installed. I haven't put login app in the INSTALLED_APPS settings and I haven't put 'login.stylista' as the AUTH_USER_MODEL. Here are my settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'accounts', 'events', 'gallery' ] 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', ] ROOT_URLCONF = 'wyat.urls' 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 = 'wyat.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] #User Model AUTH_USER_MODEL = 'accounts.user' # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = … -
Find diffrent category into all product in django
I had stuck i such a small thing. I have a list of all product which belongs to different categories. model.py class Product(models.Model): product_name = models.CharField(max_length=50,null=True, blank=True) details = models.CharField(max_length=100, null=True, blank=True) company_name = models.CharField(max_length=50,null=True, blank=True) category = models.ForeignKey(ProductClass,null=True, blank=True) Category is a foriegnKey of ProductClass. now i want a list of all different category.I do not want list of repeative category.For that i tried obj = CustomerLeads.objects.all() obj = CustomerLeads.objects.all() c = [] for i in obj: c.append(i.item_required) cat = set(c) return JsonResponse({'data':cat}) I am getting errro set([<ProductClass: accessories>, <ProductClass: other>]) is not JSON serializable How can i get a list all different category . Please help by some sample code. Thanks in advance. -
How to retrive data from db group by month and return zero if no value for certain month in django?
I have a table transaction table and I tried this but it give transactions which present in database. class transactions(models.Model): amount=models.FloatField() ts = models.DateTimeField(null=True) revenueByMonth = transactions.objects.annotate(month=TruncMonth('ts')).values('month').annotate(c=Sum('amount')).values('month', 'c') It will give: <[ {'c': 353.13, 'month': datetime.datetime(2016, 5, 1, 0, 0, tzinfo=<UTC>)}, {'c': 706.26, 'month': datetime.datetime(2016, 8, 1, 0, 0, tzinfo=<UTC>)}, {'c': 353.13, 'month': datetime.datetime(2016, 9, 1, 0, 0, tzinfo=<UTC>)}, {'c': 706.26, 'month': datetime.datetime(2016, 10, 1, 0, 0, tzinfo=<UTC>)}, {'c': 353.13, 'month': datetime.datetime(2016, 11, 1, 0, 0, tzinfo=<UTC>)}, {'c': 756.26, 'month': datetime.datetime(2016, 12, 1, 0, 0, tzinfo=<UTC>)} ]> I want sum of amount of each month and if a month have no transaction then it should be return zero.So please help me. -
How do I prevent form submission if the form is invalid?
So when the form is invalid and I click submit, it just redirects to /home because of return redirect('/'). So what do I have to return here to prevent form submission and raise an error message? Here's my code: views.py def register(request): form = UserRegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] email = form.cleaned_data['email'] user = User.objects.create_user(username=username, password=password, email=email) user.save() return redirect('/') else: print(form.errors) form = UserRegistrationForm() return redirect('/') And in my forms.py it raises an exception error to the terminal but the form still submits. forms.py class UserRegistrationForm(forms.ModelForm): email = forms.EmailField() username = forms.CharField(max_length=25) password = forms.CharField(widget=forms.PasswordInput) confirm_password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [ 'username', 'email', 'password', ] def clean(self): email = self.cleaned_data.get('email') current_emails = User.objects.filter(email=email) if current_emails.exists(): raise forms.ValidationError("That email is taken") base.html <form method="post" enctype="multipart/form-data" action="{% url 'register' %}">{% csrf_token %} <div class="registerBox"> <p><label for="id_username"></label> <input id="id_username" type="text" name="username" maxlength="30" placeholder="username"/></p> <p><label for="id_email"></label> <input type="email" name="email" id="id_email" placeholder="email"/></p> <p><label for="id_password"></label> <input type="password" name="password" id="id_password" placeholder="password"/></p> <p><label for="id_confirm_password"></label> <input type="password" name="confirm_password" id="id_confirm_password" placeholder="confirm password"/></p> <input type="submit" value="register" /> </div> </form> Any idea? -
How to dynamically show selected option in Django Many-to-Many relation form ?
I have a Django form with mant-to-many relation form with checkboxes : which looks like this And The drop down is something like this: The dropdown in form For each element in dropdown, I have few preselected options in the checkboxes. I want to display checks in the preselected (pre-mapped) elements . OR Do not show the pre-selected 'extraction type' for corresponding 'section' in the checkboxes. Django: models.py (many to many relation) (models.py) class SectionsExtractions(models.Model): section_id = models.ForeignKey(Sections, on_delete=models.CASCADE) extraction_id = models.ManyToManyField(Extractions) def __str__(self): return str(self.section_id) + ' - ' + ', '.join([a.extraction_type for a in self.extraction_id.all()]) Django: forms.py (forms.py) class SectionExtractionForm(ModelForm): extraction_id = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'checked' : 'checked'}), queryset=Extractions.objects.all()) class Meta: model = SectionsExtractions fields = '__all__' -
Forbidden (403) CSRF verification failed Request aborted
I am getting a 403 error while I tried most of the responses in the forum to the same problem, but no luck! This registration code is originally from tango with django site, but it is not working on django 1.10. Any help would be appreciated, here are the files I use: views.py: def register(request): # Like before, get the request's context. context = RequestContext(request) # A boolean value for telling the template whether the registration was successful. # Set to False initially. Code changes value to True when registration succeeds. registered = False # If it's a HTTP POST, we're interested in processing form data. if request.method == 'POST': # Attempt to grab information from the raw form information. # Note that we make use of both UserForm and UserProfileForm. user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) # If the two forms are valid... if user_form.is_valid() and profile_form.is_valid(): # Save the user's form data to the database. user = user_form.save() # Now we hash the password with the set_password method. # Once hashed, we can update the user object. user.set_password(user.password) user.save() # Now sort out the UserProfile instance. # Since we need to set the user attribute ourselves, we set … -
Django Rest Auth Token on Android Studio
So I'm running into a problem when calling rest-auth/user/ on Android Studio. I am able to login and obtain the key from said login, but from that I'm not sure how to use it in regards to rest-auth/user/. I've tried using it with GET in volley, as well as POSTing it in volley. But everytime I try to do so, I get a 403 back saying credentials were not provided. I've also tried saving the token to Android's SharedPreferences. I'm not sure what could be wrong or how to fix this problem, so any help would be appreciated. My code looks like this: getUserQueue = Volley.newRequestQueue(this); JSONObject jsObj = new JSONObject(); try { jsObj.put("token", token); } catch (JSONException e) { e.printStackTrace(); } JsonObjectRequest jsObjRequest = new JsonObjectRequest (Request.Method.GET, "http://hurst.pythonanywhere.com/supportal/rest-auth/user/", jsObj, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { result = response.getString("username"); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); // add the request object to the queue to be executed getUserQueue.add(jsObjRequest); -
Attribute error at Django Blog Zinia
I had this error before and got it fixed with django-mptt but this time I couldn't figure it out. I am having trouble working with zinnia with the error below: Request Method: GET Request URL: http://localhost:8000/admin/zinnia/category/add/ Django Version: 1.8.11 Python Version: 2.7.11 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'works', 'newsletter', 'chat', 'mptt', 'tagging', 'zinnia', 'django_comments', 'django_extensions', 'sorl.thumbnail') Installed Middleware: ('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', 'django.middleware.security.SecurityMiddleware') Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in wrapper 618. return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view 110. response = view_func(request, *args, **kwargs) File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in inner 233. return view(request, *args, **kwargs) File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in add_view 1518. return self.changeform_view(request, None, form_url, extra_context) File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapper 34. return bound_func(*args, **kwargs) File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view 110. response = view_func(request, *args, **kwargs) File "C:\Python27\lib\site-packages\django\utils\decorators.py" in bound_func 30. return func.__get__(self, type(self))(*args2, **kwargs2) File "C:\Python27\lib\site-packages\django\utils\decorators.py" in inner 145. return func(*args, **kwargs) File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in changeform_view 1481. form = ModelForm(initial=initial) File "C:\Users\DELL\portfolio\mportfolio\zinnia\admin\forms.py" in __init__ 30. Category.parent.field.remote_field, Exception Type: AttributeError at /admin/zinnia/category/add/ Exception Value: 'TreeForeignKey' object has no attribute 'remote_field' Error is seems to be in \zinnia\admin\forms.py" in __init__ … -
Check if dictionary value is empty in html template in Django/python notation
I am sending a context dictionary to an html page but I don't know how to perform an if statement on a specific value in the dictionary. This is what I'm doing. In views where I'm calling a view method I am returning: return render(request, 'shop/register.html', {'errors': errors, 'data': data}) where errors and data are also dictionaries themselves. So in the html template how can I access one of the values in the errors field? I tried doing this but it's not working: {% if errors.username_error %} //should check if that value is not blank <h3>{{errors.username_error}}</h3> //display error message {% endif %} -
Apply https only for a few views using django sslserver
I am using django sslserver for enabling https. Now the server is working with https and not http. Is it possible to apply https only for a few views using sslserver. I came across a this link and tried it. But to run the server with https we need to run the command python manage.py runsslserver 0.0.0.0:8000 which starts the server is with https. And if I just run python manage.py runserver 0.0.0.0:8000 and use the @secure_required decorator as mentioned in the link for the views which I want to be rendered with https, I get the following error, You're accessing the development server over HTTPS, but it only supports HTTP. Is there a way I can use sslserver and run only a few views with https? -
Web application development using Django?
Which is the best Operating system to develop a web applicaton using Django? I am already using windows 10 . but there is a problem while installing django. i can't able to installed it properly . -
Is there a good default query parser for django haystack (whoosh AND solr)?
I'm building a site with django and haystack that I need to support complex user queries being submitted to either whoosh or solr backends (sometimes possibly the simple backend as well). Whoosh has a great default query language (http://whoosh.readthedocs.io/en/latest/querylang.html). Solr also has a great one, and very similar to whoosh's (https://cwiki.apache.org/confluence/display/solr/The+Standard+Query+Parser). The closest thing I've found is https://github.com/Aplopio/haystack-queryparser but it is a little old and looks somewhat abandoned. It also doesn't seem to support all of the features supported in the default query languages specified by whoosh and solr. Is this something that I will have to write or is there a good parser that works with haystack for these engines already. If I would have to write this in my application how would I go about it in haystack? new input type? -
DRF: TypeError: <Model: Model object> is not JSON serializable
I have problem getting an object data from the request using django-rest-framework ModelViewset create(self, request) method. Here is my model.py class Heat(models.Model): # Relationship Fields animal = models.ForeignKey( Animal, related_name='heats', on_delete=models.CASCADE ) # Fields performer = models.CharField(max_length=25) is_bred = models.BooleanField(default=False) note = models.TextField(max_length=250, blank=True, null=True) And this is my serializers.py class HeatSerializer(serializers.ModelSerializer): class Meta: model = Heat fields = [ 'id', 'animal', 'performer', 'is_bred', 'note', ] And here is where we can find the error in my ModelViewset: class HeatViewSet(viewsets.ModelViewSet): queryset = Heat.objects.all() serializer_class = HeatSerializer @transaction.atomic def create(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): print serializer.validated_data['animal'] If you look at this line of code: // this purpose is to print the actual value of an animal object // but it gave me the TypeError: <Animal: Animal object> is not JSON serializable. print serializer.validated_data['animal'] If we include this one it works fine because this it just a normal field the same true to the other field except the animal which is a relational field: print serializer.validated_data['performer'] Now when i do this the object was saved directly to the database. serializer.save() But django would prompt me the SAME TYPE ERROR! When removing the entire create(self, request) the method flow works well … -
django: how to create a column whose default value is now()?
I am using django model to create a table. And the table has a inserted_time column, and I am using plain sql to insert the data, so in the insert sql I don't want to care about this column since I expected database should auto fill now() to the column (using mysql). But how to create such column whose default value is now() in django model. I am using auto-now, but it doesn't work. -
Django Templates and drop-down list
I would like to render a Django form in the following manner... Form UI In particular, how would I go about populating and rendering the three drop-down lists based on the model provided. The model class Positions(models.Model): position_code = models.CharField(primary_key=True, max_length=8) name = models.CharField(max_length=64, blank=True, null=True) description = models.CharField(max_length=4000, blank=True, null=True) position_type = models.CharField(max_length=8, blank=True, null=True) class Meta: managed = False db_table = 'positions' class Clubs(models.Model): club_id = models.AutoField(primary_key=True) short_name = models.CharField(max_length=4, blank=True, null=True) club_name = models.CharField(max_length=4000, blank=True, null=True) nickname = models.CharField(max_length=4000, blank=True, null=True) class Meta: managed = False db_table = 'clubs' class Players(models.Model): player_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=512, blank=True, null=True) last_name = models.CharField(max_length=512, blank=True, null=True) dob = models.CharField(max_length=512, blank=True, null=True) display_name = models.CharField(max_length=512, blank=True, null=True) active = models.BooleanField(default=True) class Meta: managed = False db_table = 'players' class DefaultSquads(models.Model): default_squad_id = models.AutoField(primary_key=True) club = models.ForeignKey(Clubs, models.DO_NOTHING) player = models.ForeignKey('Players', models.DO_NOTHING) position_code = models.ForeignKey('Positions', models.DO_NOTHING, db_column='position_code', blank=True, null=True) playing_status_code = models.CharField(max_length=16, blank=True, null=True) class Meta: managed = False db_table = 'default_squads' The view class DefaultSquadsViewCreate(CreateView): template_name = 'fafl/defaultSquad_form.html' model = DefaultSquads fields = ['player', 'position_code', 'playing_status_code'] success_url = reverse_lazy('fafl:defaultSquads-list') def get_context_data(self, **kwargs): context = super(DefaultSquadsView, self).get_context_data(**kwargs) context['clubs'] = Clubs.objects.all().order_by('club_id') context['players'] = Players.objects.all().order_by('player_id') return context The template <form method="POST" class="form-horizontal"> {% … -
Email markup not working with django send_email
I'm trying to send emails with action markup through a gmail account using django's EmailMultiAlternatives. I am able to successfully send regular emails, but am not having luck with the email markup. I followed Google's quickstart and that works. The html file is <html> <head> <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "EmailMessage", "description": "Check this out", "potentialAction": { "@type": "ViewAction", "target": "https://www.youtube.com/watch?v=eH8KwfdkSqU", "url": "https://www.youtube.com/watch?v=eH8KwfdkSqU" } } </script> </head> <body> <p> This a test for a Go-To action in Gmail. </p> </body> </html> The received email source looks like: Subject: Test Email markup - Wed Dec 14 2016 20:00:41 GMT-0600 (CST) From: <my gmail>@gmail.com To: <my gmail>@gmail.com Content-Type: multipart/alternative; boundary=94eb2c11658811d31e0543a8d263 --94eb2c11658811d31e0543a8d263 Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes This a test for a Go-To action in Gmail. --94eb2c11658811d31e0543a8d263 Content-Type: text/html; charset=UTF-8 <html> <head> <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "EmailMessage", "description": "Check this out", "potentialAction": { "@type": "ViewAction", "target": "https://www.youtube.com/watch?v=eH8KwfdkSqU", "url": "https://www.youtube.com/watch?v=eH8KwfdkSqU" } } </script> </head> <body> <p> This a test for a Go-To action in Gmail. </p> </body> </html> --94eb2c11658811d31e0543a8d263-- Now in django, I have subject = "Test Subject" from_email = 'Name <%s>' % settings.EMAIL_HOST_USER to = '<my gmail>@gmail.com' text_content = 'This is an important message.' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) …