Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form style using css
I created login and registrations. In the first one there was no problem to implement the changes in appearance using css. In the second case, when I use django forms, there was a problem with html editing. I can't get the focus effect and change the position of the inscription as in the first case.Here is a sample of both situations. Login view: a)html {% extends 'computer_science_in_medicine/main.html' %} {% load staticfiles %} {% block body_block %} <link rel="stylesheet" type="text/css" href="{% static 'css/login_user.css' %} "/> <div class="jumbotron"> <div class="container"> <h1>PLEASE LOGIN</h1> <form action="{% url 'accounts:user_login' %}" method="POST"> {% csrf_token %} <div class="inputBox"> <input type="text" name="username" placeholder="" required=""> <label for="username">Username</label> </div> <div class="inputBox"> <input type="password" name="password" required=""> <label for="password">Password:</label> </div> <input class="btn btn-primary btn-lg" type="submit" name="" value="Login"> </form> </div> </div> {% endblock %} b) css .jumbotron { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 600px; padding: 70px; background: rgba(0, 0, 0, .8); box-sizing: border-box; box-shadow: 0 15px 25px rgba(0, 0, 0, .6); border-radius: 30px; } .jumbotron h1 { margin: 0 0 30px; padding: 0; color: #fbfbfb; text-align: center; font-weight: bold; } .jumbotron .inputBox { position: relative; } .jumbotron .inputBox input { width: 100%; padding: 10px 0; font-size: 22px; color: … -
UrlGatewayLogin didn't return an HttpResponse object. It returned None instead
I'm need some help, because I'm a bit confused, I'm trying to login over url: url(r'^auth/login/', UrlGatewayLogin.as_view(), name='auth-login'), and the view is, class UrlGatewayLogin(View): def get(self, request, **kwargs): page_group = kwargs.get('page_group') token = request.GET.get('token') try: user = MyUser.objects.get(token=token) except MyUser.DoesNotExist: return None user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) return render(request, 'dashboard', {'page_group': page_group}) So I'm passing a toke to my url like so http://localhost:8000/auth/login/?token=95384449e505a54b60a3842c8db304bd2f3e14b6 but in the end after the request I've got this error, so can someone please explain why is this happening, thanks -
How can I get data from Django headers
I'm facing problem to get data from Django Headers. My API using CURL:- curl -X POST \ https://xyx.com \ -H 'Cache-Control: no-cache' \ -H 'Content-Type: application/json' \ -H 'xyzId: 3223' \ -H 'abcData: ABC-123' \ -d '{ "name": "xyz", "dob": "xyz", "user_info": "xyz", }' In my API I need to get xyzId and abcData I tried request.META['abcData'] but got error KeyError. How do I get Both data in my view? Please help me to out this problem. Thanks in advance. -
Access to Image blocked by CORS - Django
I have a issues with CORS in Django in GOOGLE CHROME. This error is just with IMAGE, not Json URL. I've get image in frontEnd by using .onload function: let base_image = new Image() base_image.setAttribute('crossOrigin', 'anonymous') base_image.src = data.url base_image.onload = function () { this.context.drawImage(base_image, data.x, data.y, data.width, data.height) } My settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', ] LOGIN_REDIRECT_URL = ('..') CSRF_COOKIE_NAME = "XSRF-TOKEN" REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ), 'DEFAULT_FILTER_BACKENDS': ( 'rest_framework.filters.SearchFilter', 'django_filters.rest_framework.DjangoFilterBackend', ), } # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] # Media Config from unipath import Path PROJECT_DIR = Path(__file__).parent STATIC_ROOT = PROJECT_DIR.parent.child('staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( PROJECT_DIR.child('static'), ) MEDIA_ROOT = PROJECT_DIR.parent.child('media') MEDIA_URL = '/media/' MIDDLEWARE = [ #API 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.BrokenLinkEmailsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'conf.middleware.AuthenticationMiddlewareJWT' ] #Allow Access API CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'localhost:3000', 'http://localhost:3000/', 'http://localhost:3000', ) # CORS_ORIGIN_REGEX_WHITELIST = ( # 'localhost:3000', # 'http://localhost:3000/', # 'http://localhost:3000' # ) ROOT_URLCONF = 'conf.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', #'DIRS': [], … -
How to get Headers data in Django,
I'm facing trouble get data from Django Headers. My API:) curl -X POST \ https://xyx.com \ -H 'Cache-Control: no-cache' \ -H 'Content-Type: application/json' \ -H 'xyzId: 3223' \ -H 'abcData: ABC-123' \ -d '{ "name": "xyz", "dob": "xyz", "user_info": "xyz", }' In my API I need get xyzData and abcData I tried request.META['xyzDara'] but got error KeyError How do I get Both data in my view? -
Django: Checkout page work-flow
I am currently working on a platform to sell tickets for events. Visiting the event page, there will be a form to select tickets (example): Currently, our plan is to create a unique session_id, while clicking on "Continue" and save the selection in a model ReservedItems. The reason for that approach is to make sure, while in the checkout process, tickets can't be bought twice. Therefore each "reserved item" is not in stock anymore for 15min. The next page will be the checkout page, where the chosen tickets will be retrieved from the database by calling the session_id which was transmitted via the form (POST method). My question now is, if in your opinion, that approach is the recommended one, or if there is a better way I haven't thought about. I appreciate your help. -
Django update/create architecture
I have worked out a way for myself how to create and update my Django models. But I am wondering if this is the correct way. Let's say we have two models A and B, where one A can have many B's. Here B has two user inputs b1, b2 and "b3" is defined as: b3 = b1 + b2 Here A also has two user input fields a1, a2 and "a3" is defined as: a3 = a1 + a2 + b[0].b3 + b[1].b3 + ... + b[N].b3 Here A depends on the zero or more B's. If one of the B's changes, than A will need to recalculate it's a3 field. The A and B models are therefore defined as: class A(models.Model): a1 = models.FloatField(default=0) a2 = models.FloatField(default=0) a3 = models.FloatField(default=0) @classmethod def create( cls, a1, a2): a = cls(a1 = a1, a2 = a2) return a def set_a(self, a): a.a3 = a.a1 + a.a2 bs = B.objects.filter(a=a) for b in bs: a.a3 += b.b3 a.save() return a class B(models.Model): a = models.ForeignKey('a.A', related_name='bs', on_delete=models.CASCADE) b1 = models.FloatField(default=0) b2 = models.FloatField(default=0) b3 = models.FloatField(default=0) @classmethod def create( cls, a, b1, b2): b = cls( a = a, b1 = … -
How to extract and split Video using input string and VTT file in Node.js?
I am working on the Express.js server API to extract the certain word from Youtube video. I have downloaded example Video and VTT file from Youtube, but I have no idea how to extract the video frame which is including the input string and split it out as a separated video file. For instance, let's say that my Video includes the word 'student' 4 times so I can extract 4 video snippets including the 4 'student' words. I am using youtube-dl package for downloading the Youtube Video and VTT file. I am open to using any advanced libraries and packages for this problem. Kindly help me to get the solution. Thank you in advance. -
django.db.utils.ProgrammingError: relation "django_site_domain_v2339b81_uniq" already exists
I'm getting this error when I try to migrate. I tried to solve a Site does not exist error but doing this: python manage.py migrate --fake sites zero python manage.py showmigrations sites [ ] 0001_initial python manage.py migrate --fake-initial However this did not fix the problem. Any idea how I can fix this error: django.db.utils.ProgrammingError: relation "django_site_domain_v2339b81_uniq" already exists -
Adding extra field in admin for custom user in Django
I have a custom user model which is subclassed by AbstractUser with an added custom field. # model.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): ADM = 'admin' MEMBER = 'member' ROLE_CH = ((ADM, 'Administrator'), (MEMBER, 'Member')) role = models.CharField(max_length=20, choices=ROLE_CH, blank=True) This model is also registered as the default auth model in settings.py # settings.py AUTH_USER_MODEL = "main.CustomUser" Then in admin.py as per the documentation, I create a custom form which extends UserCreationForm and then register it to the custom user. # admin.py from django.contrib import admin from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser fields = UserCreationForm.Meta.fields + ('role',) class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm admin.site.register(CustomUser, CustomUserAdmin) However, it does not work as expected. The Add User form remains the default one i.e. only username, password and password confirmation fields are present. The role field does not appear. -
Create folder and save file into that folder and then extract zip file
I have this code which creates a folder base on the logged in user and saves the file they are uploading into that folder. The file the user is uploading is a zip file which I want to have extracted upon upload. The problem is that this code doesn't work because it exits the folder after creation, so it comes up with an IO error saying it couldnt find the file. How would I go on fixing this problem? def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> zip = ZipFile(filename) return 'user_{0}/{1}'.format(instance.user, filename) and zip.extract() Exception Value: [Errno 2] No such file or directory: 'UploadedFile.zip' -
`_get_page` to instantiate the Page class
I am learning the coding style through reading the Django source code: In the pagination.py Pagination, the source code define a private method to instantiate the class Page. def page(self, number): """ Returns a Page object for the given 1-based page number. """ number = self.validate_number(number) bottom = (number - 1) * self.per_page top = bottom + self.per_page if top + self.orphans >= self.count: top = self.count return self._get_page(self.object_list[bottom:top], number, self) def _get_page(self, *args, **kwargs): """ Returns an instance of a single page. This hook can be used by subclasses to use an alternative to the standard :cls:`Page` object. """ return Page(*args, **kwargs) I think it more readable if instantiate it with method page as def page(self, number): """ Returns a Page object for the given 1-based page number. """ number = self.validate_number(number) bottom = (number - 1) * self.per_page top = bottom + self.per_page if top + self.orphans >= self.count: top = self.count return Page(self.object_list[bottom:top], number, self) What's the advantage to define separate _get_page method in extra step? -
Django rest framework - return image as response
I am calling a django rest framework get api to create a barcode. Its working fine when I tried to save it as an image. @api_view(['GET']) def mybarcode(request): from elaphe import barcode code = barcode('datamatrix', "sampletext", encoding='utf-8', scale=2, options=dict(columns=24, rows=24), margin=2, data_mode='50bits') code.save("mybarcode.jpg") return Response({'status': True}) This working fine when I call this API as "http://127.0.0.1:9999/api/v1/testbarcode". An image will be created with the name "mybarcode.jpg" and the api return its status as True. But I would like to return the image as the result of this api call. Because I have to include this in a image tag. <img src='http://127.0.0.1:9999/api/v1/testbarcode' /> Is there any way to do this? -
Gunicorn Setup with Django
I've setup a gunicorn service like so [Unit] Description=gunicorn daemon After=network.target [Service] User=muiruri_samuel Group=www-data WorkingDirectory=/home/muiruri_samuel/webapp/chatsys ExecStart=/home/muiruri_samuel/webapp/djangoenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/muiruri_samuel/webapp/chatsys/chatsys.sock chatsys.wsgi:application [Install] WantedBy=multi-user.target for a django app called chatsys with the virtualenv djangoenv in the shown folder. This is on a Ubuntu server and after starting gunicorn and checking for a bug got this error back. muiruri_samuel@train:~/webapp/chatsys$ sudo systemctl status gunicorn gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Tue 2018-05-29 10:20:19 UTC; 2min 46s ago Main PID: 4862 (code=exited, status=1/FAILURE) May 29 10:20:19 train gunicorn[4862]: self.stop() May 29 10:20:19 train gunicorn[4862]: File "/home/muiruri_samuel/webapp/djangoenv/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 393, in stop May 29 10:20:19 train gunicorn[4862]: time.sleep(0.1) May 29 10:20:19 train gunicorn[4862]: File "/home/muiruri_samuel/webapp/djangoenv/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 245, in handle_ May 29 10:20:19 train gunicorn[4862]: self.reap_workers() May 29 10:20:19 train gunicorn[4862]: File "/home/muiruri_samuel/webapp/djangoenv/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 525, in reap_wo May 29 10:20:19 train gunicorn[4862]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) May 29 10:20:19 train gunicorn[4862]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> May 29 10:20:19 train systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE May 29 10:20:19 train systemd[1]: gunicorn.service: Failed with result 'exit-code'. -
Pre-selection of data for migration to the database
Is there any way in Django to populate the database with multiple records during the migration, or after it, except for the manual method, or restore the backup. For example: I have a model with services, which after the creation of the database should already have 3 entries, because it is a binder. How do I implement this in Django 2.x? -
create a filter based on the user choice in drop down list , django
here is my HTML where I have a simple select form and simple view for a list from the database {% extends 'fostan/base.html' %} {% block content %} {% load static %} <br> <div class="well well-small" dir="rtl" style="border-color: #f89406"> <form action="PageObjects" method="GET"> <select name="town_select"> <option selected="selected" disabled>قم بإختيار المحافظة</option> {% for town in all_towns %} <option value="10">{{ town }}</option> {% endfor %} </select> <br> <input class ="btn btn-success" type="submit" value="موافق"> </form> <h2 style="color: #f89406;"> فساتين {{ current_name }} </h2> <hr class="soften"/> <div class="row-fluid"> <ul class="thumbnails" > {% for dress in selected_dress_list %} <li class="span4"> <div class="thumbnail"> <a class="zoomTool" href="{% url 'dress_details' dress.pk%}" title="add to cart"><span class="icon-search"></span>{{ dress.dress_action }}</a> <a href="{% url 'dress_details' dress.pk%}"><img class="main" src="{{ dress.dress_image1.url }}" alt=""></a> <div class="caption"> <h5> فستان {{ dress.dress_name }} </h5> <h4> <a class="defaultBtn" href="{% url 'dress_details' dress.pk%}" title="إضفط لمشاهدة الفستان"><span class="icon-zoom-in"></span></a> <span class="pull-left">{{ dress.dress_price }} جنيه </span> </h4> </div> </div> </li> {% endfor %} </ul> </div> </div> {% endblock %} now I need to use the form in the HTML to filter up to the viewed items here are my Views.py def category(request, pk): all_name = Name.objects.all() current_user = request.user all_good = Item.objects.all().filter(dress_special=True) current_name = get_object_or_404(Name, pk=pk) selected_dress_list = Item.objects.all().filter(dress_name=current_name) dress_need = Item.objects.filter(dress_active=False).order_by('-created_at') dress_need_count … -
how to execute the management call_command pragmatically in django
in my terminal i can execute 1)first command python manage.py tenant_command rebuild_index 2)second command. the terminal will ask which schema shall i execute for the i enter my schema name Enter Tenant Schema ('?' to list schemas): xxx This is working fine so how to achieve this in pragmatically using management call_command pragmatically in django management.call_command('python manage.py tenant_command rebuild_index', 'xxx') but it giving error like File "/home/hi/venv/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 94, in call_command raise CommandError("Unknown command: %r" % name) CommandError: Unknown command: 'python manage.py tenant_command rebuild_index' so please any body tell me is it possible to achieve this kind of interactive terminal commands to run pragmatically in django -
When I am Trying to run this script I am getting this errror "django.core.exceptions.FieldDoesNotExist: No_Address has no field named 'False' "
import os from django.contrib.gis.utils import LayerMapping from .models import No_Address no_address_mapping = { 'id' : 'ID', 'address' : 'Address', 'city' : 'City', 'zip' : 'ZIP', 'state' : 'State', 'primpgon' : 'PrimPgon', 'numpgons' : 'NumPgons', 'x' : 'X', 'y' : 'Y', 'censusbloc' : 'CensusBloc', 'objectid' : 'ObjectID', } no_address_shp = os.path.abspath( os.path.join(os.path.dirname(__file__), 'building/WestDV_CA_BF_NoAddress_region.shp'), ) def run(verbose=True): lm = LayerMapping( No_Address,no_address_shp,no_address_mapping,transform=False, encoding='iso-8859-1', ) lm.save(strict=True, verbose=verbose) When I am trying to run this script Iam getting this Field Doesnot exist error. I Am confused why i am getting this error. Can anyone suggest me. Please give me the suggestion to solve this issue -
Django Queryset Filter where will be 3 month in 7 days
I have queryset filtered user that created 3 month ago. User.objects.filter( create_date__range=( datetime.now()-timedelta(90),datetime.now() ) ) that above return all the user within date range 3 month ago to now. but i don't need return it all since its to many. I need return all the acticle that will be 3 month in 7 days from datetime.now(). example. now = 2018-05-29 create_date = 2018-04-20 will now show since its more than 7 days till 3 month. create_date = 2018-03-04 <-- this will show since in 6 days will be 3 month. -
How can I reduce the number DB calls Django makes when querying child model properties?
I am having a hard time figuring out basic optimization and would appreciate some insight or somebody pointing me to the right direction. Simplified models: class TimeStampedModel(models.Model): created = models.DateTimeField(auto_now_add=True, db_index=True) modified = models.DateTimeField(auto_now=True) class Meta: abstract = True class Venue(TimeStampedModel): name = models.CharField(unique=True, max_length=200, db_index=True) class Offer(TimeStampedModel): venue_associated = models.ForeignKey(Venue, on_delete=models.CASCADE, db_index=True) content = models.TextField(max_length=500, db_index=True) Simplified view: class MapView(ListView): fields = ["name"] model = Venue template_name = "venues/venue_map.html" Simplified template: {% for venue in venue_list %} {{ venue.name }} {{ venue.offer_set.latest.created }} {{ venue.offer_set.latest.content }} {% endfor %} This creates a huge volume of DB calls (~400). Going through the whole venue_list only creates a single call (+1 not associated) yet the two offer_set calls create new calls (each 200). Thus I assumed creating a separate property "latest" for the Venue model would help since it would at least deal with doubling of the "latest" call but no. I also tried playing around with overriding the generic ListView methods which didn't get me anywhere. There is probably a way of doing this that I am not seeing. Currently, all I can think of is just adding additional fields to the Venue model to just duplicate the information and … -
Not able to refer static files of Django project from Heroku
I am unable to load static files in production, whereas they work on local machine. I have followed the steps in https://devcenter.heroku.com/articles/django-assets as well as the existing answers but I am not able to make it run. I am overlooking something and would like the community's assistance. Here is the partial settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ALLOWED_HOSTS = ['tryml.herokuapp.com','localhost'] # Application definition INSTALLED_APPS = [ 'web.apps.WebConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'tryml.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 = 'tryml.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/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/2.0/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', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' Here is the wsgi.py file: import … -
Django: overriding form's method to set queryset not working?
I want the queryset of my coin field to change when a user selects "Sell" in the "BuySell" dropdown option with jquery. Once the dropdown is changed I send a Get Request with AJAX, pick that request up in my view and then reload the form, which is where I override the default coin field queryset in my TransactionForm's init method. This isn't working as expected, nothing happens to change the coin dropdown options and I get no errors (including in the Network tab when I inspect element). I wonder if this is something to do with the way I'm calling my form here: form = TransactionForm(user = request.user, coin_price = GetCoin("Bitcoin").price) and the form init method: def __init__(self, coin_price = None, user = None, *args, **kwargs): super(TransactionForm, self).__init__(*args, **kwargs) if user: self.user = user qs_coin = Portfolio.objects.filter(user = self.user).values('coin').distinct() print("qs_coin test: {}".format(qs_coin)) self.fields['coin'].queryset = qs_coin FULL CODE: Forms class TransactionForm(forms.ModelForm): CHOICES = (('Buy', 'Buy'), ('Sell', 'Sell'),) coin = forms.ModelChoiceField(queryset = Coin.objects.all()) buysell = forms.ChoiceField(choices = CHOICES) field_order = ['buysell', 'coin', 'amount', 'trade_price'] class Meta: model = Transaction fields = {'buysell', 'coin', 'amount', 'trade_price'} def __init__(self, coin_price = None, user = None, *args, **kwargs): super(TransactionForm, self).__init__(*args, **kwargs) print("Transaction form init: … -
Error in installing MySQL-python==1.2.5
I am trying to install MySQL-python==1.2.5 in my virtualenv on Mac using pip install MySQL-python==1.2.5 Getting the below error. MySQL-python==1.2.5 Collecting MySQL-python==1.2.5 From cffi callback : Traceback (most recent call last): File "/Users/harshit.jain/Documents/workspace/venv/lib/python2.7/site-packages/OpenSSL/SSL.py", line 309, in wrapper _lib.X509_up_ref(x509) AttributeError: 'module' object has no attribute 'X509_up_ref' Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),)': /simple/mysql-python/ From cffi callback : Traceback (most recent call last): File "/Users/harshit.jain/Documents/workspace/venv/lib/python2.7/site-packages/OpenSSL/SSL.py", line 309, in wrapper _lib.X509_up_ref(x509) AttributeError: 'module' object has no attribute 'X509_up_ref' Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),)': /simple/mysql-python/ From cffi callback : Traceback (most recent call last): File "/Users/harshit.jain/Documents/workspace/venv/lib/python2.7/site-packages/OpenSSL/SSL.py", line 309, in wrapper _lib.X509_up_ref(x509) AttributeError: 'module' object has no attribute 'X509_up_ref' Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),)': /simple/mysql-python/ From cffi callback : Traceback (most recent call last): File "/Users/harshit.jain/Documents/workspace/venv/lib/python2.7/site-packages/OpenSSL/SSL.py", line 309, in wrapper _lib.X509_up_ref(x509) AttributeError: 'module' object has no attribute 'X509_up_ref' Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),)': /simple/mysql-python/ From cffi callback : Traceback (most recent call last): File … -
django not renders after POST request
I have a js code that on click event sends POST requeset to /productionFloor/wip/ I have a view that receives those requests (also printing to the console all the arguments that were passed correctly). I'm trying to render a template with the data received from the POST request, but django won't render the view. here is my view: def wip_view(request): if request.method == "POST": print(request.POST['id']) print(request.POST['process']) return render(request, 'wip.html', {'nbar': 'production_floor'}) here is the js: $(".clickable-schedule-row").dblclick(function() { id=$(this).children('td')[6].innerHTML; process=$(this).children('td')[7].innerHTML; $.post("/productionFloor/wip/", {'csrfmiddlewaretoken': $("[name=csrfmiddlewaretoken]").val(), 'id': id, 'process': process}); }); as I mentioned, the server gets the request correctly and prints the right data, but it won't change the page on the browser. -
Django Create and Update views: foreign key field
Suppose I have the two following classes : class Parcel(models.Model): name = models.CharField(max_length=NAME_MAX_LENGTH) garden = models.ForeignKey(Garden, on_delete=models.CASCADE) def __str__(self): return self.name class Bed(models.Model): parcel = models.ForeignKey(Parcel, on_delete=models.CASCADE) name = models.CharField(max_length=NAME_MAX_LENGTH) length = models.IntegerField() width = models.IntegerField() I'm using Django's generic views to Create and Update new beds. As parcel is a Foreign Key, Django automatically create a select input with all existing parcels in the database. However, I would like to tell Django to put only parcels with a certain garden_id. I looked at the function get_initial(self), but I don't want to specify an initial value for the parcel, just narrow the choices of parcels. If anyone has an idea, it would help me a lot. Thank you.