Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unit tests in Django: no such table error for class that does not exist
I have very annoying problem. If I run my unit tests in Django with python manage.py jenkins environment=local I get error: Creating test database for alias 'default'... Traceback (most recent call last): ... django.db.utils.OperationalError: no such table: connectors_testex1 My test database is sqlite3, real database is postgres. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': CONFIG['database']['db'], 'USER': CONFIG['database']['user'], 'PASSWORD': CONFIG['database']['password'], 'HOST': CONFIG['database']['host'], 'PORT': CONFIG['database']['port'], } } if 'test' or 'jenkins' in sys.argv: DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test', } Problem is that connectors_testex1 does not exist. Even if I do grep -r -i "connectors_testex1" /myproject/* it doesn't found anything. If I use same code on different machine (same git branch) it works normally. what could be the problem? -
Failed to check INSTALLED_APPS in django template
I am trying to load some HTML element in my django template, if a specific app is defined in my settings.py file. But it doesn't work. The if statement behaves like the app doesn't exist: {% if 'myapp.edit_data' in INSTALLED_APPS %} <p> dfsdfsdf </p> {% endif %} I also tried with other apps and I get the same behavior. What am I missing? -
Django AppRegistryNotReady when defining a model
I wanted to add the first model to an already working app, and now I can't start it because it always gives AppRegistryNotReady. This does only happen, if my model MailLog is child of models.Model. from __future__ import unicode_literals from django.db import models #class MailLog(models.Model): # like this, it crashes class MailLog(): # like this, it works # Field definitions The error occurs no matter what's inside the class, even if there is only a pass. However, I can import my models in the admin.py, and it crashes when I import from a file I called core.py. That file looks like this: import boto3 from botocore.exceptions import ClientError from django.template import loader from django.conf import settings from .templates import * from .models import MailLog -
django-mptt: test for consistency
I'm using django-mptt for my application and I found that a branch with no consistency between parent and left/right. So I launched .rebuild() to fix it. But the question is: is there a way to test if the tree is consistent? -
Django How to route to a js file from urlpattern
I want to route to a js file (may be static or dynamic). The js file has format same thing: (function() { var img = new Image, url = encodeURIComponent(document.location.href), title = encodeURIComponent(document.title), ref = encodeURIComponent(document.referrer); img.src = '%s/a.gif?url=' + url + '&t=' + title + '&ref=' + ref; })(); And from client I will run this script from header by: <script async="" src="https://localhost/a.js"> </script> without use staticfile, I think we can use it by urlpattern. But I don't know use for javascript file. -
How to join not relational model in django rest framework?
i have a problem about join not relational model in django rest framework. for example, i have two model : Model Category template class CategoryTemplate(models.Model): name = models.CharField(max_length=256) Model Commodity class Commodity(models.Model): name = models.CharField(max_length=255, default=None, null=False) Example Data: *category template id | name 1 | Pupuk 2 | Pestisida *commodity id | name 1 | Pisang 2 | Semangka my question is, with that model how to join that model to get the result like this ? cat_temp_id | cat_temp_name | comm_id | comm_name | category 1 | Pupuk | 1 | Pisang | Pupuk Pisang 1 | Pupuk | 2 | Semangka | Pupuk Semangka 2 | Pestisida | 1 | Pisang | Pestisida Pisang 2 | Pestisida | 2 | Semangka | Pestisida Semangka Please advice. Thank you. -
Creating a Table of Context from a list of dicts using Django templates
Say that I have the following dict list: fruits = [ {"Name": "Apple", "id": 1, "url": "/apple", "Desc": "Red or green skin with white flesh."}, {"Name": "Pear", "id": 2, "url": "/pear", "Desc": "Green fruit with white flesh."}, {"Name": "Coconut", "id": 3, "url": "/coco", "Desc": "Brown hairy shell with with flesh."} ] and it's passed to the context of a Django template via a view. How would I go about building a Table of Context that looks something Like this? A Apple Red or green skin with white flesh. C Coconut Brown hairy shell with with flesh. P Pear Green fruit with white flesh.. I was thinking of doing something like this: {% for fruit in fruits %} <B>{{ fruit.Name|first_letter_upper }}</B><BR> <A HREF="{{ fruit.url }}">{{ fruit.Name }}</A><BR> {{ fruit.Desc }}<BR> {% if not forloop.last %}<BR>{% endif %} {% endfor %} But then I would have to implement the custom filter "first_letter_upper". Not a big deal, but I'm just wondering if there's a simpler way to do that without having to use custom filters? -
django - extending User model for registration
I am really new to django. I have a model and 2 forms like this below extending the User model. The UserProfile is linked to the user model which would be where I have my extra field. I have seen numerous posts but still was't able to solve it. I would like to save the profile with additional parameters like the phone number stated below when the registration form is submitted, I have been spending hours trying to make it work, thanks a lot for your help in advance: class UserProfile(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length = 50) phone_number = models.CharField(max_length=12) #In form.py class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2' ] def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user class RegistrationFormProfile(forms.ModelForm): phone_number = forms.CharField(max_length = 12) class Meta: model = UserProfile fields = [ 'phone_number', ] def save(self, commit=True): profile.phone_number = self.cleaned_data['phone_number'] if commit: profile.save() return profile #In views.py def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) profileForm = RegistrationFormProfile(request.POST) if form.is_valid(): user = form.save() if(profileForm.is_valid()): profileForm.save() return redirect('accounts/profile') else: return redirect('accounts/wrong') else: form … -
Static files are not loading in django1.11
I'm a newbie in django. I've been trying to develop a website with django1.11. But I got stuck at some point. The static files are not coming through the templates. Any help! settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'agr8w4(pcdz077#8n2ow1z8_@e-%6(evtw((-3g$&$_wf1&!@1' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'photo', ] 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 = 'pro.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', '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 = 'pro.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', }, { '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 files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static", "static_root") STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static", "our_static" ), ] STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder' ) MEDIA_URL ='/media/' MEDIA_ROOT =os.path.join(BASE_DIR, "media_root") urls.py from django.conf import settings from django.conf.urls import include,url from django.conf.urls.static import static from django.contrib import admin from photo.views import home … -
Django REST Framework. How to handle FileNotFoundError error
When I make dumb from dev DB to local, I don't have files to show on my machine. Is some smart way to avoid this error without changing DB? Thank you. UPD My serializer: class ProductImageSerializer(serializers.ModelSerializer): image_size = serializers.IntegerField( source='image.size', required=False, ) image_name = serializers.SerializerMethodField( required=False, ) image = serializers.FileField(required=False) class Meta: model = ProductImage fields = ( 'id', 'image', 'product', 'is_main', 'image_size', 'image_name', ) -
White HTML page after redirection with Django CBV model
I'm getting an issue and I don't find a way to solve this problem. All seems to be fine, but it doesn't work. This is the process : I have a template with all informations about the object which is just created by Django form. I have a button which have to redirect to an other template taking account the object id but when I'm redirect to this template, I'm getting an html white page. This is my model : class Societe(models.Model): NumeroIdentification = models.CharField(max_length=30, null=True, verbose_name='Numero Identification physique', unique=True) Nom = models.CharField(null= False, max_length=30, verbose_name='Nom de Société') Etat = models.CharField(max_length = 30, choices = CHOIX_ETAT_SOCIETE, null=False, verbose_name="Etat") ... def get_absolute_url(self): return reverse_lazy('SocieteResume', kwargs={'id': self.id}) def __unicode__(self): return unicode (self.id, self.NumeroIdentification, self.Nom, ...) I have a first class which let to display created object in detail : class IdentitySocieteResumeView(LoginRequiredMixin, ListView) : template_name = 'Identity_Societe_Resume.html' model = Societe def get_context_data(self, **kwargs) : context_data = super(IdentitySocieteResumeView, self).get_context_data(**kwargs) id = self.kwargs['id'] societe = get_object_or_404(Societe, pk=id) obj = Societe.objects.filter (Nom=societe.Nom, SIRET=societe.SIRET, SIREN=societe.SIREN, Ville=societe.Ville) if obj: sc_obj = obj[0] ... return context_data With the associated template which has this button in order to redirect to the next template : <form method='POST' action="{% url 'SocietePDF' societe.id … -
Retrieve data on a django templates
I am having trouble to understand the principles of retrieving data in template. I understand very well how to do it from the Shell. But I always block on how to do it using class based view. I have a simple view : class ProjectDetailView(generic.DetailView, LoginRequiredMixin): #import pdb; pdb.set_trace() model = Project template_name = 'project_details.html' so in my template I easily retrieve data from the model Project like {{project.name}} or {{project.team_id}} But If I want I would like to show in my project detail data from other models, how can I do it ? Let assume I would like to show a list of all team members ? here are my models: class Team(models.Model): team_name = models.CharField(max_length=100, default = '') team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) members = models.ManyToManyField(MyUser, related_name="members") def __str__(self): return self.team_name class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True) candidat_answers = models.ManyToManyField('survey.response') -
Django-Allauth is getting failed to login the other users for Facebook Django Pyhton 2.7
Here is the scenario: I am trying to login or authenticate the user using the Django-allauth Application. I am using Django 1.11.5 and python 2.7 as environment for the application. I am getting stuck at the url: http://websiteIP:port/accounts/facebook/login/callback/?code=AQA2UQcbZ7GKyikNSV3rIRY3MxF6QcIsVrElIlSaN51Uhbz10qKtEuphoR1kj4CziEctuZbeXLOlCejMUqTP8yJOgm7NhS7QSTypyTU3eUVaHVY59cb6wdbUDihaRYgzU9WiwM9e1D52s_7XPMT8F3EgaPiowKjhdwzDltm58ZvgOj-P3GCfr8JZaHroWqukNPckhHw11uylfzjo8UIcDiCOjBD3Qs92DD1quTgqNsx9XX95smkXWVeHPhRG7M80X8jIeUa2JUOqPf3YoY5CAwluIN_f587GiEkQFZM9sCUQyK5Nc2r11cmCutlSVi2kHxSSH0oQKwiThs7s4OAbBRT0&state=9p3yt6ErhCRP#_=_ I have tried hard to check what can be the reason for this issue. I found that the people has always said that the application is trying to verify the email address. and some suggested to apply some EMAIL_HOST setting. I tried to set that. Have a look at my settings.py as below: SITE_ID = 1 LOGIN_REDIRECT_URL = '/' SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email', 'user_posts', 'user_photos', 'user_about_me', 'user_likes', 'user_friends'], 'METHOD': 'oauth2', 'FIELDS': [ 'email', 'name', 'first_name', 'last_name', 'posts', 'about', 'picture.type(large)', 'likes', 'cover', 'taggable_friends.limit(1){name,picture.type(large){url},first_name}', ], 'LIKED_FIELD': [ 'link', 'name', # 'picture.type(normal){url}', ], 'EXCHANGE_TOKEN': True, # 'VERIFIED_EMAIL': True, 'VERSION': 'v2.10', } } ACCOUNT_LOGOUT_ON_GET = True EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'example@gmail.com' EMAIL_HOST_PASSWORD = 'password' I am now fed up, as I got nothing at the end. Kindly, suggest me what is the missing part. I have setup Django Alluth usong the GoDjango Tutorials -
django.db.utils.IntegrityError: duplicate key value violates unique constraint "auth_permission_pkey"
Got stuck I have an database in which when I try to make python manage.py migrate it's giving this error as follows: django.db.utils.IntegrityError: duplicate key value violates unique constraint "auth_permission_pkey" DETAIL: Key (id)=(241) already exists. following is whole error : Operations to perform: Apply all migrations: admin, auth, companyapp, contenttypes, djcelery, kombu_transport_django, loginapp, projectmanagement, recruitmentproject, sessions, smallproject Running migrations: No migrations to apply. Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 227, in handle self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, File "/home/ubuntu/.local/lib/python2.7/site-packages/django/core/management/sql.py", line 53, in emit_post_migrate_signal **kwargs File "/home/ubuntu/.local/lib/python2.7/site-packages/django/dispatch/dispatcher.py", line 193, in send for receiver in self._live_receivers(sender) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/contrib/auth/management/__init__.py", line 83, in create_permissions Permission.objects.using(using).bulk_create(perms) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/db/models/query.py", line 443, in bulk_create ids = self._batched_insert(objs_without_pk, fields, batch_size) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/db/models/query.py", line 1080, in _batched_insert inserted_id = self._insert(item, fields=fields, using=self.db, return_id=True) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/db/models/query.py", line 1063, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1099, in execute_sql cursor.execute(sql, params) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/ubuntu/.local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) … -
Django 1.11 csrf_token dose not generate
I'm new in Django, When I try to use csrf, I didn't event see the csrfmidderwaretoken generate in html code. Please someone help me out:) blow is clips of my code: urls.py: `url(r'^register/$', register, name="register"),` views.py: def register(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] if not (User.objects.filter(username=username)): User.objects.create(username=username, password=password) User.save() return render(request, "register.html", {"status":True}) else: return render_to_response('register.html') register.html: Template Html Code Link And what shows out is this:Appearance on site . Django 1.11, Python3.6. Can somebody help me check this, much appreciated in advance. -
access to another model fields with foreign key in django admin
I have a contact us class in django model,that using "user_id" foreign key,in admin.py file,i want using userprofile data with user_id key,such as "name" filed,in userprofile model "user_id" is foreign_key too,how can do it? -
Is it a good idea to use 'GET' or 'POST' to retrieve an image from user for Flask Restful API (python)?
I am new to Restful API development. I am developing a Restful API (using python flask) which will accept an image array from Client. There are two ways I can get image from a user: one way is using 'GET' where the user will pass the image in URI. e.g. http://127.0.0.1:5000/api/example?image=[[1,2,3,4,5,6,7,8], [1,2,3,4,5,6,7,8]] another way is using 'POST' where the user will post the image through some sort of request library. Which is a better option? I am looking for answers in terms of security, performance, ease-of-use. -
How to add to REcaptcha to django login form
I need to integrate Google's REcaptcha to the standard django authentication system. I already have a working template which shows the reCaptcha. Now I need to integrate the validation against google's API endpoint. I found this tutorial which basically explains how to do it with generic forms. https://simpleisbetterthancomplex.com/tutorial/2017/02/21/how-to-add-recaptcha-to-django-site.html But how can I integrate this into the standard authentication mechanism of django? I guess, I need to implement and overload some function in my views.py file. But what would be that function? -
django python: best algorithm to plot 2*2 arrary into excel
I have the following postgres db class Prescription(TimeStampedModel): name = models.CharField() patient_name = models.CharField() class PrescriptionLine(TimeStampedModel): prescription = models.ForeignKey(Prescription, related_name="prescriptionlines") pill = models.ForeignKey(Pill, related_name='prescriptionlines') quantity = models.IntegerField() class Pill(TimeStampedModel): pill_category = models.ForeignKey(PillCategory, related_name='pills') class PillCategory(TimeStampedModel): name = models.CharField() Suppose I have 3 different prescriptions(A,B,C) with different number of prescriptionlines. Prescriptions = { Prescription A : {'name': 'A', 'patient_name': 'David', 'pill X': '4g', 'pill Y': '6g', 'pill Z': '10g'}, Prescription B : {'name': 'B', 'patient_name': 'James', 'pill U': '2g', 'pill X': '6g', 'pill Z': '3g'}, Prescription C : {'name': 'C', 'patient_name': 'Mary', 'pill S': '2g', 'pill T': '6g', 'pill Y': '3g', 'pill Z': '4g'} } Above data should be plotted into excel file as following table with the following code df = pd.DataFrame(prescriptions).fillna('') df.to_excel('prescriptions.xls') Table | | Prescription A| Prescription B | Prescription C | | patient_name | David | James | Mary | | -------- |:-------------:| --------------:|----------------| | Pill S | | | 2g | | Pill T | | | 6g | | Pill U | | 2g | | | Pill X | 4g | 6g | | | Pill Y | 6g | | 3g | | Pill Z | 10g | 3g | 4g | -
How to filterfalse pandas dataframe from django queryset
This is to add a to a postgres table data from an html table, without having to recreate the table, but simply insert new data. I need to remove some row from a pandas dataset, those data are already inside the django db and would trow an error triyng to reinsert them in the db. So first I look for the rows in the df already archived in the db: items_to_be_removed_from_df=MyModel.objects.filter(id=df['id']).annotate().values(id) Now I need to get the other rows from the df, would it be possible something like this? filtered_df=df.filterfalse(id=items_to_be_removed_from_df) -
Django-Allauth not allowing me to access the login with facebook Python2.7 Django
I have tried to login with django-Allauth application in Django 1.11.5. I am using python 2.7. The problem is: when I logged in with my account I got a clean chit ... successful login. I have submitted the application but the review failed as there was flaw in the login of the application using the other user. Then I sent that application to my friend to test it and he found the same issue. I wonder why I do not see anything and I get a successful login, while my friend or the facebook app reviewer didn't. See the following codes and please let me know what I might need to improve to make the application work accordingly. settings.py SITE_ID = 1 LOGIN_REDIRECT_URL = '/' SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email', 'user_posts', 'user_photos', 'user_about_me', 'user_likes', 'user_friends'], 'METHOD': 'oauth2', 'FIELDS': [ 'email', 'name', 'first_name', 'last_name', 'posts', 'about', 'picture.type(large)', 'likes', 'cover', 'taggable_friends.limit(1){name,picture.type(large){url},first_name}', ], 'LIKED_FIELD': [ 'link', 'name', # 'picture.type(normal){url}', ], # 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': True, 'VERSION': 'v2.10', } } INSTALLED_APPS = ( 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', ) AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.core.context_processors.tz', 'django.contrib.messages.context_processors.messages', 'django.core.context_processors.request', 'allauth.account.context_processors.account', 'allauth.socialaccount.context_processors.socialaccount', ) … -
Deploy Django 1.10 app with python 3.6 on Google Computer Engine
I have created a project using with Django 1.10.5 and python 3.6, now I need to deploy this project on google compute engine.I have googled a lot but couldn't find any clear guide to deploy my Django app on compute engine. What I have tried: Create a compute engine instance Install python 3.6 (But not succeded that's why using pre-installed python 3.5.2) Setup pip and virtualenv Create a virtualenv and clone my project from GitHub Install all requirements from requirements.txt now when I try to run my app as python manage.py runserver from my directory, it says : Django version 1.10.5, using settings 'brain.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. when I visit http://127.0.0.1:8000/ doesn't load any page. How can I deploy my Django 1.10 & Python 3.6 app on google compute engine? Help me, please! Thanks in advance! -
django rest framework reverse foreign field doesn't updated, return empty list
I have following model structure, class Bill(models.Model): created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='bill_created_by') total_bill_amount = models.IntegerField(blank=True, null=True) class Route(models.Model): start_time = models.DateTimeField(auto_now=False,blank=True, null=True) end_time = models.DateTimeField(auto_now=False,blank=True, null=True) start_lat = models.FloatField(default=0.0,blank=True, null=True) start_lon = models.FloatField(default=0.0,blank=True, null=True) end_lat = models.FloatField(default=0.0,blank=True, null=True) end_lon = models.FloatField(default=0.0,blank=True, null=True) distance = models.FloatField(default=0.0,blank=True, null=True) transport = models.CharField(max_length=300,blank=True, null=True, choices=ROUTE_MODE, default=ROUTE_MODE[0]) fare = models.IntegerField(blank=True, null=True) purpose = models.CharField(max_length=1000, blank=True, null=True) bill = models.ForeignKey(Bill, related_name="routes",on_delete=models.CASCADE, blank=True, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL,blank=True, null=True, related_name='routes', max_length=255) and the serializers, class BillSerializer(ModelSerializer): routes = RouteSerializer(many=True, read_only=True) class Meta: model = Bill fields = ('id','created_on','created_by','total_bill_amount','routes') lass RouteSerializer(ModelSerializer): all_directions = AllDirectionSerializer(many=True, read_only=True) user = ReadOnlyField(source='user.email') bill = ReadOnlyField(source='bill.id') class Meta: model = Route fields = ('id','start_time','end_time','start_lat','start_lon','fare', 'end_lat','end_lon','distance','transport','all_directions','user', 'bill') and Bill api using viewset, class BillViewSet(viewsets.ModelViewSet): queryset = Bill.objects.all() serializer_class = BillSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly,) now if i want to update Bill api with list of Routes according to the serializer structure, like this **calling put method on Bill api where Bill id is 29** { "id": 29, "created_on": "2017-10-15T10:05:19.786057Z", "created_by": 4, "total_bill_amount": 301, "routes": [ { "id": 31, "start_time": null, "end_time": null, "start_lat": 23.77201, "start_lon": 90.3602333333333, "fare": 0, "end_lat": 0.0, "end_lon": 0.0, "distance": 0.0, "transport": "BUS", "all_directions": [], "user": "tanvir@gmal.com", "bill": 29 }, { … -
Add aldryn categories and tags to aldryn newsblog
I installed Aldryn NewsBlog on my Django CMS project. Aldryn NewsBlog documentation on content creation states I should be seeing the following meta options for each blog post: (1) Tags, (2) Categories, (3) Application configuration. But I don't see (1) and (2). Using (2) as example: I understand Aldryn NewsBlog uses Aldryn Categories app. I further referred to Aldryn Categories documentation and visited its github. Question: As Aldryn's documentation is silent, am I supposed to add the files in github to my project? If yes, where do I add them? Thanks very much. -
Spyne lxml validation error soap11env:Client.SchemaValidationError
This is the xml I need to parse https://codepad.co/snippet/nob995lf#= Here is my models: https://codepad.co/snippet/VsqZTQ2i But I got this error: :83:0:ERROR:SCHEMASV:SCHEMAV_ELEMENT_CONTENT: Element '{http://www.opentravel.org/OTA/2003/05}RestrictionStatus': This element is not expected. Any help would be appreciated. Thank you.