Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which language better to use for server side scripting django or php or node.js what would be result if django vs php vs node.js
Please suggest me for strong webserver interpreter node.js,php,django -
django-cors-headers not working at all
Well, initially I had forgotten the middleware class but after adding it just worked fine ( It was a week ago ). Now, I am back to my workstation and I find it again not working. The ACCESS_CONTROL_ALLOW_ORIGIN headers are not at all being set. I have tried all that is, placing the middleware at top, before CommonMiddleware but it just doesn't work. This is my setting.py file : DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'account', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', ] # if DEBUG: # INSTALLED_APPS += 'corsheaders', # MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware', ] # else: # MIDDLEWARE = [] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = DEBUG This is the response I am getting : Date: Sun, 14 Jan 2018 09:35:09 GMT Server: WSGIServer/0.1 Python/2.7.14+ X-Frame-Options: SAMEORIGIN Content-Type: text/html; charset=utf-8 Content-Length: 146 -
Save Instance Nested Serializers in Django Rest Framework
I have problem with saving instance Live_In Nested Serializers in Django Rest Framework. Hope your guys help me! I think just a basic issue. My Serializers: I think it comes error when I write saving instance class UserEditSerializer(ModelSerializer): live_in = CityLiveInSerializer(many=False) about = serializers.CharField(source='profile.about') class Meta: model = User fields = [ 'username', 'live_in', 'about', ] def update(self, instance, validated_data): instance.username = validated_data.get('username', instance.username) instance.save() # Update Serializers Profile if (validated_data.get('profile') is not None): profile_data = validated_data.pop('profile') profile = instance.profile profile.about = profile_data.get('about', profile.about) profile.save() if (validated_data.get('live_in') is not None): live_in_data = validated_data.pop('live_in') ins = instance.city.live_in ins.live_in = live_in_data.get('name', ins.live_in) ins.save() return instance My City Model (Live_in) class City(BaseCity): class Meta(BaseCity.Meta): swappable = swapper.swappable_setting('cities', 'City') class BaseCity(Place, SlugModel): name = models.CharField(max_length=200, db_index=True, verbose_name="standard name") country = models.ForeignKey(swapper.get_model_name('cities', 'Country'), related_name='cities') Data sent by Postman (Json) { "live_in": { "name": "Encamp" } } TraceError: Exception Value: Cannot assign "u'Encamp'": "Profile.live_in" must be a "City" instance. File "/Users/lecongtoan/Desktop/FeedTrue/backend/api/authentication/views.py" in edit 43. serializer.save() File "/Users/lecongtoan/Desktop/FeedTrue/backend/api/authentication/serializers.py" in update 185. ins.live_in = live_in_data.get('name', ins.live_in) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py" in set 216. self.field.remote_field.model._meta.object_name, Exception Type: ValueError at /api/v1/users/account/edit/ -
Admin css won't load when deploying Django project on pythonanywhere
So I had some trouble with static files when I tried deploying them... Thing is that I manage to server the main static files and everything is working except for the admin. I think maybe something is wrong with my configuration. Here is screenshot of my web: https://i.imgur.com/RtuStM2.png This is my settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') MEDIA_DIR = os.path.join(BASE_DIR, 'media') SECRET_KEY = 'ie&_vj_d)t5itbpun3%58tlw(3=ptn1^5qj43kgm^&_z^!5(' DEBUG = False ALLOWED_HOSTS = ['danielcirstea.pythonanywhere.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rango', 'registration' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware' ] ROOT_URLCONF = 'tango_with_django_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR, ], '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', 'django.template.context_processors.media' ], }, }, ] WSGI_APPLICATION = 'tango_with_django_project.wsgi.application' LANGUAGE_CODE = 'ro' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [STATIC_DIR, ] STATIC_URL = '/static/' MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' REGISTRATION_OPEN = True ACCOUNT_ACTIVATION_DAYS = 7 REGISTRATION_AUTO_LOGIN = True LOGIN_REDIRECT_URL = '/rango/' LOGIN_URL = '/accounts/login/' -
Django Rest-Framework nested serializer order
Is there a way to order a nested serializer _set, for example order by pk or time-stamp. So basically order song_set shown in the json data below from the most reacent to the latest object created, in this case by order_by('-timestamp') or order_by('-pk'). Json data { "pk": 151, "album_name": "Name", "song_set": [ { pk: 3, timestamp: '5 seconds' }, { pk: 2, timestamp: '10 seconds' }, { pk: 1, timestamp: '15 seconds' } ] } Model class Album(models.Model): album_name = models.CharField(max_length=100, blank=True) class Song(models.Model): album = models.ForeignKey('album.Album', default=1) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) Searilizer class SongListSerializer(HyperlinkedModelSerializer): class Meta: model = Song fields = [ 'pk', 'timestamp' ] class AlbumSerializer(HyperlinkedModelSerializer): song_set = SongListSerializer(many=True, read_only=True) class Meta: model = Album fields = [ 'pk', 'timestamp', 'song_set' ] -
How to display Last name in custom user profile in Django
I need to display the last name of all the user in user profile but I am able to display only the username. Admin.py from django.contrib import admin from commonpage.models import UserProfile,PositionTable #register the above models class user_action(admin.ModelAdmin): list_display = ['user', 'useractive','position','team_name','preferd_shift'] ordering = ['id'] list_filter = ('useractive','position','team_name','preferd_shift') list_editable = ['position','team_name','preferd_shift'] actions = [make_user_active,make_user_deactive] # Register your models here. admin.site.register(UserProfile,user_action) admin.site.register(PositionTable) -
Why can I not customize the style on certain input fields within Django framework?
My issue is simple: my first three input fields are able to be customized and the last three input fields are not. I do not see any discrepancies between the individual input fields. Could someone please spot my (hopefully) overlooked error? Thanks in advance. Note: I am using Bulma as my CSS framework and am specifically using only Bulma's base settings. from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User widgets = { 'username': forms.TextInput(attrs={'class':'input'}), 'first_name': forms.TextInput(attrs={'class':'input'}), 'last_name': forms.TextInput(attrs={'class':'input'}), 'email': forms.TextInput(attrs={'class':'input'}), 'password1': forms.TextInput(attrs={'class':'input'}), 'password2': forms.TextInput(attrs={'class':'input'}) } fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') Below is the HTML: <body> {% include "navbar.html" %} <section class="section"> <div class="container"> <h1 class="is-size-1">Sign up below!</h1> <form id="register_form" class="field" method="POST" action="{% url 'oraclewebsite:register' %}" enctype="multipart/form-data"> {% csrf_token %} <div class="field"> <label for="label">Username</label> <div class="control"> {{form.username}} </div> <label for="label">First Name</label> <div class="control"> {{form.first_name}} </div> <label for="label">Last Name</label> <div class="control"> {{form.last_name}} </div> <label for="label">Email</label> <div class="control"> {{form.email}} </div> <label for="label">Password</label> <div class="control"> {{form.password1}} </div> <label for="label">Re-enter Password</label> <div class="control"> {{form.password2}} </div> </div> <br> <input class="button is-info" type="submit" name="submit" value="Register"/> </form> </div> </section> -
How to display ValidationErrors to users, and not 500s?
I'm having trouble understanding how to display errors to users in Django when DEBUG = FALSE. I'm just learning Django, so I could very well be missing something obvious/simple. One example I'm trying to solve, is when a user is registering and their username/email is already taken, a validation error is presented. I can't seem to get this error to show when debugging is off. Here is my code: registration.html {% block content %} <div class="container"> <div class="row main"> <div class="panel-heading"> <div class="panel-title text-center"> <h1 class="title">My title</h1> <hr /> </div> <div class="main-login main-center"> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} <form class="form-horizontal" method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> <div class="login-register"> <a href="{% url 'login' %}">Already registered? Login!</a> </div> </form> </div> </div> </div> </div> {% endblock %} views.py def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): userObj = form.cleaned_data first_name = userObj['first_name'] last_name = userObj['last_name'] username = userObj['username'] email = userObj['email'] password = userObj['password'] … -
Django Model - facing error while makemigrations - 'UserSkill.user' is not a foreign key to 'UserProfile'
I am new to Django - ORM and facing issues with creating relations . The db is SQLite . I am trying to solve following problem such that N+1 db problem is not present - A User will add different Skills to his/her profile .S/He can also create new skills which were earlier not present and can add to the profile . Other users can upvote the skills on user profile - this should be recorded in Database too . Uptill not I have created following models but it is giving foreign key error on running makemigrations .Also I figured out this that I need a new class to Map the upvotes of skills by other user on current user profile - for this I am not sure should I create a New class or use existing model class . Error - > SystemCheckError: System check identified some issues: ERRORS: wantedly_webapp.UserProfile.user_skills: (fields.E339) 'UserSkill.user' is not a foreign key to 'UserProfile'. wantedly_webapp.UserSkill: (fields.E336) The model is used as an intermediate model by 'wantedly_webapp.UserProfile.user_skills', but it does not have a foreign key to 'UserProfile' or 'Skill'. #import from django models module from django.db import models # This class will more or less … -
Can't extend user models in Django Admin?
The admin console doesn't show me the UserProfile in Django Admin. There are no errors that show up. I reloaded my server but it still doesn't show in the console. from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') website = models.URLField(default='') phone = models.IntegerField(default=0)` admin.py: from django.contrib import admin from account.models import UserProfile admin.site.register(UserProfile)` -
import error during running my server in django project
Unhandled exception in thread started by Traceback (most recent call last): File "/home/kamal/.local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/kamal/.local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/home/kamal/.local/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/home/kamal/.local/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/home/kamal/.local/lib/python2.7/site-packages/django/core/checks/urls.py", line 10, in check_url_config return check_resolver(resolver) File "/home/kamal/.local/lib/python2.7/site-packages/django/core/checks/urls.py", line 19, in check_resolver for pattern in resolver.url_patterns: File "/home/kamal/.local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in get res = instance.dict[self.name] = self.func(instance) File "/home/kamal/.local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/kamal/.local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in get res = instance.dict[self.name] = self.func(instance) File "/home/kamal/.local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/home/kamal/Desktop/mywebsite/mywebsite/urls.py", line 17, in from django.urls import path ImportError: No module named urls -
I cannot do a lookup through the foreignkey anymore
I have a model for shops inside shops app class ShopAccount(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) managers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="manager_workers", blank=True) business_name = models.CharField(max_length=200) dashboard_banner_image_1 = models.ImageField(upload_to = upload_location, null = True, blank = True) I have another model inside of bookings app class Booking (models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) destination = models.CharField(max_length=200, blank=True, null=True) shop = models.ForeignKey(ShopAccount, null=True, blank=True) booking_date = models.DateTimeField() mobile_contact = models.CharField(max_length=11, blank=True, null=True) inside of bookings app (bookings/views.py) i have this code snippet def booking_create_view(request): if request.method == 'POST': print (request.POST) shop_id = request.POST.get('shop') instance_location_destination = request.POST.get('instance_location_destination') form = BookingForm(request.POST) shop = ShopAccount.objects.get(id=shop_id) print (shop) everything is correct until this point shop = ShopAccount.objects.get(id=shop_id) my code returns an error saying cannot resolve 'id' into fields: Choices are print(shop) returns None to my database -
Implement AWS authentication to use end user's resources in Python & Django App
I'm working on a project using Python(3.6) and Django(1.10) in which i need to use end user's account resource to make his code deployed on his aws account. I have set up 2 accounts(1 as my app & 2nd as a user's account) and make authentication successful.But when I have passed this auth in another view it throws some errors. Here's what I have tried: From views.py: def boto3_with_role(role_arn, session_prefix, external_id, **kwargs): """ Create a partially applied session to assume a role with an external id. A unique session_name will be generated by {session_prefix}_{time} `session` can be passed, otherwise the default sesion will be used see: http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-api.html """ sts = boto3.client('sts') res = sts.assume_role( RoleArn=role_arn, RoleSessionName='{}_{}'.format(session_prefix, int(time.time())), ExternalId=external_id, *kwargs, ) creds = res['Credentials'] print(creds) return partial(boto3.session.Session, aws_access_key_id=creds['AccessKeyId'], aws_secret_access_key=creds['SecretAccessKey'], aws_session_token=creds['SessionToken'], ) class AwsAuthentication(LoginRequiredMixin, CreateView): def post(self, request, *args, **kwargs): AwsSession = boto3_with_role('arn:aws:iam::497736713165:role/IstiocloudCrossAccount', 'MyPrefix', 'abd37214@cloud') my_session = AwsSession() client = my_session.resource('s3') for bucket in client.buckets.all(): print(bucket.name) return render(request, 'dockerDep/aws/selectDeployment.html', {'bucket': bucket.name}) # return HttpResponse('Your Bucket is: {}'.format(bucket.name)) # From here AWS Deployments starting class AwSlsDeployment(LoginRequiredMixin, CreateView): def get(self, request, *args, **kwargs): AwsSession = boto3_with_role('arn:aws:iam::497736713165:role/IstiocloudCrossAccount', 'MyPrefix', 'abd37214@cloud') user_session = AwsSession() client = user_session.resource('s3') for bucket in client.buckets.all(): print(bucket.name) return render(request, 'dockerDep/aws/slsDeployment.html', {'bucket': bucket.name}) … -
How do I only check for existing form fields values if it was modified?
I am trying to allow users the ability to update their profile, but can't seem to figure out how to only raise an error if the 2 fields username, email were modified, or if the user is not that user. As of now, I can't save the updates as the error is continuously popping up since the user has those values obviously. I've also tried excludes but couldn't get it to work right either. Here is my code: forms.py class UpdateUserProfile(forms.ModelForm): first_name = forms.CharField( required=True, label='First Name', max_length=32, ) last_name = forms.CharField( required=True, label='Last Name', max_length=32, ) email = forms.EmailField( required=True, label='Email (You will login with this)', max_length=32, ) username = forms.CharField( required = True, label = 'Display Name', max_length = 32, ) class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name') def clean_email(self): email = self.cleaned_data.get('email') username = self.cleaned_data.get('username') if (User.objects.filter(username=username).exists() or User.objects.filter(email=email).exists()): raise forms.ValidationError('This email address is already in use.' 'Please supply a different email address.') return email def save(self, commit=True): user = super().save(commit=False) user.email = self.cleaned_data['email'] user.username = self.cleaned_data['username'] if commit: user.save() return user, user.username views.py def update_user_profile(request, username): args = {} if request.method == 'POST': form = UpdateUserProfile(request.POST, instance=request.user) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('user-profile', … -
How read information of mongodb on django environment
i have this 2 collection on mongodb airports routes I was searching how do that, i found djongo. After reading I understood the following. I must make models that matching those data, then only use queries. There are models only with few fields. Then I could use this methods e.g. Airports.objects.filter(name_airports__startswith='Goro') am I right? If anyone can guide me to right way , I'll be very grateful. If you have an example on the web, please share that with us, thanks in advance. -
Best way to Auto Fill CharField for token in Django
i need to generate a token for every user that will be created automatically -
Django objects.get matching query does not exist
I'm trying to get all attributes of a single object. I keep getting a "Devices matching query does not exist." I just cannot figure out my issue. Models.py `class Devices(models.Model): category_id = models.ForeignKey(Category, on_delete=models.CASCADE) device_description = models.CharField(max_length=100) device_status = models.CharField(max_length=50) device_date = models.DateTimeField() device_user = models.CharField(max_length=50)` Views.py def view_status(request, pk=None): device = Devices.objects.get(pk=pk) return render(request, 'homesite/device_status.html', device) urls.py url(r'^viewstatus/$', views.view_status, name='ViewStatus'), here is the url I use to call http://localhost:8000/homesite/viewstatus/?pk=1 There are 4 records in my able so I know there is a match for PK=1. -
How to enforce non empty on slugrelatedfield for many to many in serializer using Django Rest Framework?
Django version : 1.11 DRF version : 3 I have the following: class Shape(ProductVariantParent): art_numbers = models.ManyToManyField(Product, through='ShapeArtNumber') class ShapeSerializer(serializers.ModelSerializer): art_numbers = \ ArtNumberSlugRelatedField(queryset=Product.objects.all(), slug_field='art_number', many=True, required=True) class ArtNumberSlugRelatedField(serializers.SlugRelatedField): def to_internal_value(self, data): user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user try: new_or_found_object, created = \ self.get_queryset().get_or_create(**{self.slug_field: data}) if created and user is not None: new_or_found_object.created_by = user new_or_found_object.updated_by = user new_or_found_object.save() return new_or_found_object except ObjectDoesNotExist: self.fail('does_not_exist', slug_name=self.slug_field, value=smart_text(data)) except (TypeError, ValueError): self.fail('invalid') Shape and Product are many to many relation. Shape treats the related field So when I pass in Product.art_numbers as None, i will trigger a cannot be null error message. When I pass in Product.art_numbers as [], I will not trigger any error message. How do I ensure that Product.art_numbers cannot be empty so I can trigger the right error message about how the art_numbers cannot be empty error message? I also use internationalization so I prefer that the right cannot be empty error message can be shown when I change the browser language settings? -
I don't know if I am deploying right.. site doesn't work
So I have studied the book, how to tango with django 1.10 and I was trying to deploy here my project. The bash part worked perfectly, but when I deployed and I go to danielcirstea.pythonanywhere.com/rango the app doesn't show.This is my web configuration: https://i.imgur.com/5ZiOC8U.png I also changed DEBUG to FALSE and hosts as needed. Please help. -
Correct architecture for scaling a backend
I have 3 instance of my django app hosted on Google Compute Engine in 3 different locations around the world. I am autoscaling my app to set up more instances when the cpu is at 70%. I also have a loadbalancer set up to route traffic to a close and functioning instance. This all works fine however what I don't get is how my database is scaled along with my app, in my case I have one mysql instance that stores all the data from all instances but I am not sure how to scale it since I want the same data to be available for all instances. Having only one presents many problems such as high latency for instances accessing it from another part of the world as well as all requests going to this single mysql instance. How can I better my architecture? -
How to modify request.POST in django custom middleware?
I want to add client_id and client_secret to the django POST request. Here is how my middleware.py file looks like: class LoginMiddleware(object): def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # auth_header = get_authorization_header(request) # Code to be executed for each request before # the view (and later middleware) are called. #Add Django authentication app client data to the request request.POST = request.POST.copy() request.POST['client_id'] = '12345678' request.POST['client_secret'] = '12345678' response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response Middleware is being successfully processed when I check it with a debugger. Thought when a view is called the 'client_id' and 'client_secret' fields are missing in the request. What could be the problem? How to properly add such data to the request? -
Display from 2 tables in Django
my function in view return a context, in this context there is 2 tables this is my view : > def myfunction(request): > ......... > > context = { 'dst_link' : second, 'titles' : third } > return render(request,'mytestapp/result.html',context ) so in the result.html i want to display the 2 tables like that : <li > <a href="https:{{second}}" target=_blank > {{third}}</a> </li> the problem is that i have 2 tables and i don't know how to make a boucle in the 2 tables in the same time -
dlib and django. how to integrate and import dlib into django
I am trying to use dlib in my django project. I am using aws ubuntu, but I was not able to use pip dlib, so I compiled directly according davisking instruction to use this PR https://github.com/davisking/dlib/pull/1040. So I was success to install compile dlib and install in my ubuntu. Now is how to use dlib in django. I tried "import dlib" but its not recognized. This is how I install dlib and last part of the execution. $ python setup.py install ..... ..... Processing dlib-19.8.99-py2.7-linux-x86_64.egg creating /usr/local/lib/python2.7/dist-packages/dlib-19.8.99-py2.7-linux-x86_64.egg Extracting dlib-19.8.99-py2.7-linux-x86_64.egg to /usr/local/lib/python2.7/dist-packages Adding dlib 19.8.99 to easy-install.pth file Installed /usr/local/lib/python2.7/dist-packages/dlib-19.8.99-py2.7-linux-x86_64.egg Processing dependencies for dlib==19.8.99 Finished processing dependencies for dlib==19.8.99 settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... 'mapwidgets', 'dlib', ] but it came out with errors below. removing this it still does not recognize "import dlib" Traceback (most recent call last): File "manage.py", line 23, in <module> execute_from_command_line(sys.argv) File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/home/deploy/somedotcom/somedotcomenv/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File … -
Django Save multiple selections for the same input name to the database and getting it back in another view
I need to save several checkboxes values that have the same name. like: <input type="checkbox" name="eth_hisp" value="Mexican" id="eth1_hisp" class='chk-btn'/> <label for='eth1_hisp'>Mexican</label> <input type="checkbox" name="eth_hisp" value="Cuban" id="eth2_hisp" class='chk-btn'/> <label for='eth2_hisp'>Cuban</label> <input type="checkbox" name="eth_hisp" value="Puerto Rican" id="eth3_hisp" class='chk-btn'/> <label for='eth3_hisp'>Puerto Rican</label> I need to store values which will be selected (checked) to database as one value. (It is possible to be done as the string with the command: eth_hisp=''.join(form.getlist('eth_hisp')) Question: How to transfer these values back to the view (it will be another view as a variable name? In other words, There is another view where selected checkboxes has to be also selected if in the example above they were checked (1 view - is user view, 2 view is admin edit view) -
django import some fields by excel and some fields by default
My view code for importing data in the db is like this : def excel_import(request): uploadform=UploadFileForm(None) if request.method == 'POST' : uploadform = UploadFileForm(request.POST, request.FILES) if uploadform.is_valid(): file = uploadform.cleaned_data['docfile'] data = bytes() for chunk in file.chunks(): data += chunk dataset = XLS().create_dataset(data) result = ExportSpec().import_data(dataset,dry_run=False, raise_errors=True, user=request.user) return render(request, 'BallbearingSite/news.html',{'uploadform':uploadform}) and my models is like this : class Stocks(models.Model): docfile = models.FileField(blank=True,null=True,upload_to='documents/') user=models.ForeignKey(User, null=True) name=models.CharField(max_length=128,verbose_name=_('stockname')) number=models.CharField(max_length=64,verbose_name=_('number')) suffix=models.CharField(max_length=12,verbose_name=_('uffix')) brand=models.CharField(max_length=64, validators=[ RegexValidator(regex='^[A-Z]*$',message=_(u'brand must be in Capital letter'),)] ,verbose_name=_('brand')) comment=models.CharField(blank=True,null=True,max_length=264,verbose_name=_('comment')) price=models.PositiveIntegerField(blank=True,null=True,verbose_name=_('price')) date=models.DateTimeField(auto_now_add = True,verbose_name=_('date')) checking= ((_('pending'),_('pending')), (_('reject'),_('reject')), (_('approved'),_('approved')), (_('expired'),_('expired')), ) confirm=models.CharField(choices=checking,max_length=10,verbose_name=_('confirmation'), default=_('pending')) seller=models.BooleanField(verbose_name=_('seller'), default=1) I want to get some fields by excel file and some fields like date,confirm,user set by default also the id should set by default as latest id+1 for each row of the excel file Any advice is appreciated.