Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to login in django with https/ssl at deploy server
I have django project. It works well on my Mac.But it's not work well on GCP(Ubuntu 17). When I try login from login page. I cant login and authorize. I return same login page. No thing happen. Just reload same page. This site uses Nginx with uWSGI I'm thinking this problem comes from https/ssl settings. If you know how to solve this problem, please let me know. This is my code: urls.py from django.conf.urls import url from django.contrib.auth.views import login, logout_then_login from django.urls import reverse_lazy from . import views from django.contrib.auth import views as auth_views app_name = 'invo' urlpatterns = [ # Login Logout url(r'^login/$', login, {'template_name': 'invo/login.html'}, name='login'), url(r'^logout/$', logout_then_login, name='logout'), ] nginx setting # the upstream component nginx needs to connect to upstream django { # server unix:///path/to/your/mysite/mysite.sock; # for a file socket server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 443 ssl; ssl_certificate /etc/letsencrypt/live/tekis.biz/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/tekis.biz/privkey.pem; # the domain name it will serve for server_name tekis.biz; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to … -
Django 2.0 Password Validation
By default in Django 2.0 we get AUTH_PASSWORD_VALIDATORS option with UserAttributeSimilarityValidator MinimumLengthValidator CommonPasswordValidator NumericPasswordValidator So is there any easy way to add extra VALIDATORS like minimum 1 uppercase, 1 symbol, 1 digit, etc. ? In python i can check Using regex import re userPass = 'HelloWorld*123' if re.search('[A-Z]', userPass)!=None and re.search('[0-9]', userPass)!=None and re.search('[^A-Za-z0-9]', userPass)!=None: print 'Strong Password' -
Mysql error while starting Django on eclipse
Hi i'm new to Django framework and want to connect MariaDB. So I added the code below on settings.py DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'ENGINE': 'django.db.backends.mysql', 'NAME': 'findworknear', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': '' } } However, whenever I tried to run server, all I could see were several lines of error messages. I tried some tips found on stackoverflow. (sudo pip install python-mysql, sudo pip install mysqlclient). But none of them worked. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x103ed91e0> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", … -
In Django how to decrypt the session id in database and in cookie with my SECRET_KEY?
I created one Django application with below settings - (for cookie base session) SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' Then I got a session id sessionid=.eJxrYJk6gwECaqdo9PDGJ5aWZMSXFqcWxWemTOlhMjSY0iOEJJiUmJydmgeU0UzJSsxLz9dLzs8rKcpM0gMp0YPKFuv55qek5jjB1PIjGZCRWJwxpUfDMNUk1STJ1MLc0tLczDLNyMg0ydDQzDTJzCjZ0jg50SLR3NDc3DzReEqpHgBcETf7:1eVt50:xtWtUp9mwcxusxtg6fZB_tHzlYw With another setting (for database-backed sesisons) SESSION_ENGINE = 'django.contrib.sessions.backends.db' SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer' I got below encrypted string in database: gzc9c9nwwraqhbdsk9xg935ypkqp7ecs|MmExZWI0NjZjYzIwNDYyZDhjNWVmODJlNmMwNjI0ZmJmMjQ4MTljNDp7Il9hdXRoX3VzZXJfaWQiOiIxMCIsIl9hdXRoX3VzZXJfYmFja2VuZCI6ImRqYW5nby5jb250cmliLmF1dGguYmFja2VuZHMuTW9kZWxCYWNrZW5kIiwiX2F1dGhfdXNlcl9oYXNoIjoiMWU0ZTRiNTg3OTk3NjlmMjI1YjExNjViNjJjOTNjYThhNzE3NzdhMyIsImxhc3RfbG9naW4iOjIyMjJ9 I want to know what is inside both the encrypted strings. How can I decrypt both? Which encryption algorithm django uses for encryption? Where can I set the encryption algorithms? It will be great, if anyone can give me a sample code. -
Implementing Django Form without Model
This is a continuation from last question here Coding mental block with specific Django task The answer was: A pure django solution would be: create a form with three integer fields (say, num1, num2 and result) in your view, populate num1 and num2 with the numbers to be added render the form in your template (num1 and num2 fields should be read only) the user enters the answer in the result field and submits the form in your view, determine whether num1 + num2 == result redirect to a success page if the answer is correct, otherwise redisplay the form However, as I am working through the steps, my form was not being rendered properly. views.py def post_question(request): form = QuestionForm(request.POST) if form.is_valid(): question = Question(question_text = form.cleaned_data['question_text'], MY_FIELD = form.cleaned_data['MY_FIELD'], exam = form.cleaned_data['exam']) question.save() return HttpResponseRedirect('/numbers/') forms.py class MyForm(forms.Form): a = forms.CharField(max_length=20) mat = forms.CharField(max_length=200) html file <form action="{% url 'form_handle' %}" method="POST">{% csrf_token %} {{form.as_p}} <button type="submit">Submit</button> </form> When I load the page all I see is a submit button. As pictured Can someone please advise me where I had gone wrong? -
Django Error Message
I have a case. Once the form is submitted, it has to make a query. If the query exists, it has to send an error message. If the query does not exist, it has to save the data. I have written view as below and it works. But the only issue is that the error message goes like a success message. I have tried placing the query before validating the form, still, it's same. How could I resolve this? def permissionFormView(request): r_form = forms.RoleForm() p_form = forms.PermissionForm() if request.method == 'POST': p_form = forms.PermissionForm(request.POST) if p_form.is_valid(): role = p_form.cleaned_data['role_name'] feature = p_form.cleaned_data['feature'] if models.PermissionModel.objects.filter(role_name=role,feature=feature).exists(): messages.error(request, 'Permission exists.') else: p_form.save() messages.success(request, 'Permission added successfully.') return render(request, 'company_profile.html', {'r_form': r_form, 'p_form': p_form}) return render(request,'company_profile.html',{'r_form':r_form,'p_form':p_form}) Client Side Form Code: <form action="{% url 'permission_form' %}" novalidate method="POST"> {% csrf_token %} <div class="row"> <div class="col"> <label for="r_name"><small><strong>{{ p_form.role_name.label }}</strong></small></label> <p>{{p_form.role_name}}</p> {% for error in p_form.role_name.errors %} <p><small class="alert-danger">{{ error }}</small></p> {% endfor %} </div> <div class="col"> <label for="r_feature"><small><strong>{{ p_form.feature.label }}</strong></small></label> <p>{{p_form.feature}}</p> {% for error in p_form.feature.errors %} <p><small class="alert-danger">{{ error }}</small></p> {% endfor %} </div> <div class="col"> <label for="permission"><small><strong>{{ p_form.permission.label }}</strong></small></label> <p><input type="checkbox" class="form-control" id="permission" name="permission" {% if r_form.role_name.value is not None %} value="{{ p_form.permission.value … -
Makefile for Running Django Backend and React Frontend
I am working on a project which is developed by Django REST Framework and served by React app. There is a partition between the back end and front end. The structure of the path is: Root ├── backend ├── frontend ├── makefile ├── readme.md ├── requirements.pip └── venv Currently, I run the project by opening two different terminals. Then I start the django server first and then start the react app. In terminal 1, I start the django server: cd backend python manage.py runserver In terminal 2, I start the react app: cd frontend npm start So, it is quite irritating to redo these commands each time to run the project. Recently, I have heard about makefile. I think this will reduce the number of commands to start the project. I have created the following makefile: run: python backend/manage.py runserver cd frontend npm start When I write make run it successfully starts the Django server but it does not start the React application. What am I missing here? Can I run the both commands in a single command using make? -
force-download with Django and Vue
I was trying use vue to download file from server when I director visit my backends API, it work well,and I can unzip my file normal. but when I try to download file by axios response, the file can not unzip,and also if I don't set link.download, the filename does not correct.like that here is my vue's api export function packMaterials (context, thesisId, filename) { context.$axios({ method: 'get', headers: getAuthHeader(), url: PACK_URL + thesisId }) .then(function (response) { console.log(response) let blob = new Blob([response.data], { type: 'application/force-download' }) let link = document.createElement('a') link.href = window.URL.createObjectURL(blob) link.download = filename link.click() }) .catch(function (error) { console.log(error) }) } here is my Django API if os.path.exists(file_path): # 返回file with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/force-download") response['Content-Disposition'] = "attachment; filename={}".format(escape_uri_path(filename)) return response and here is the response data in console. English not my native language, so if my description not clearly, you can contact me with lc960127@gmail.com I will send more detail. Thanks -
OperationalError at /app/top/ no such column: app_post.category_id
I got an error,OperationalError at /app/top/ no such column: app_post.category_id . I wrote codes in views.py from .models import POST from django.shortcuts import render def top(request): contents = POST.objects.order_by('-created_at') render(request, 'top.html', {'contents': contents} in models.py from django.db import models class Category(models.Model): name = models.CharField("CategoryName", max_length=100) def __str__(self): return self.name class POST(models.Model): title = models.CharField(max_length=100) text = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="Category") def __str__(self): return self.title First I made POST model and next I did Category model ,then I connected them by using ForeignKey.I think this process causes this error so I run command python manage.py flush --database=default and delete all migration file.However same error happens.I deleted db so I think it solve the error, but I am wrong.How should I fix this?What should I do to fix this? -
Python Django multiprocessing Error: "AttributeError: Can't pickle local object 'Command.handle.<locals>.f'"
I'm using python 3.6 django 1.11 windows10 and trying to send email using multiprocessing. recipients are connected to database(django model) and email contents form is html(by django get_template), also used get_connection to send multi-email. What I'm trying is to use multiprocessing to accelerate sending rate. My code is here from django.core.management.base import BaseCommand from django.core.mail import get_connection, EmailMessage from django.template.loader import get_template from multiprocessing import Pool from sending.models import Subscriber class Command(BaseCommand): def handle(self, *args, **options): connection = get_connection() recipients = [i.email for i in Subscriber.objects.all()] num = Subscriber.objects.count() subject = 'Multiprocessing trying 1' body = get_template('Newsletter20171229.html').render() from_email = 'info@modoodoc.com' def send(i): msg = EmailMessage(subject, body, from_email, [recipients[i]]) msg.content_subtype = 'html' print("Sending email to: " + recipients[i] + " No: " + str(i)) connection.send_messages([msg]) print("Complete.") pool = Pool(processes=2) pool.map(send, range(0, num)) print("Mail have just sent. The program is going to end.") connection.close() And I've got an error like this. File "c:\python36-32\Lib\multiprocessing\connection.py", line 206, in send self._send_bytes(_ForkingPickler.dumps(obj)) File "c:\python36-32\Lib\multiprocessing\reduction.py", line 51, in dumps cls(buf, protocol).dump(obj) AttributeError: Can't pickle local object 'Command.handle.<locals>.f' How to fix this? Thank you. -
ValueError at /app/top/
I got an error, ValueError at /app/top/ The view app.views.top didn't return an HttpResponse object. It returned None instead. I wrote codes in views.py from .models import POST from django.shortcuts import render def top(request): contents = POST.objects.order_by('-created_at') render(request, 'top.html', {'contents': contents}) in models.py from django.db import models class POST(models.Model): title = models.CharField(max_length=100) text = models.TextField() in html <body> <div> {% for content in contents.all %} <div> <h2>{{ content.title }}</h2> <p>{{ content.text }}</p> </div> {% endfor %} </div> </body> In model, several data of title&text is registed,so surely data is not empty.I think this is directory mistake, now my application structure is -mysite(parent app) -app(child app) -templates -top.html -models.py -views.py so I do not know what is wrong.How should I fix this?What is wrong in my codes? -
Is there a way to view word files locally using office web viewer
I have a word file, and I want to open up that word file for preview/viewing purposes only, not to edit. How could I go by this? I have a Django application and one of the main purpose of the application is to view documents that people upload on the site. However for testing purposes I cannot get to preview documents for reasons I do not know. I am using Microsoft office viewer to view the files. This is my html code in Django: <iframe src="https://view.officeapps.live.com/op/embed.aspx?src=http://127.0.0.1:8000/media/project/1/f73ab109-dcaa-4cc3-bbfc-7121eca10118.doc"> </iframe> And this is was the error displayed in the html: I am assuming that the office viewer is expecting a "real" internet directory and not something locally. -
nginx 502 bad gateway: upstream prematurely closed connection while reading response header from upstream
I have a Django app with which users can create video collages using multiple videos. Problem is, on production, when uploading videos to amazon s3, I get a 502 bad gateway (works fine locally). Does anyone know what could be wrong? I already set client_max_body_size 100M and fastcgi_buffers 8 16k; fastcgi_buffer_size 32k; fastcgi_connect_timeout 3000; fastcgi_send_timeout 3000; fastcgi_read_timeout 3000; Does anyone know what could be wrong? Thanks in advance -
How to enforce reads from read replica in Postgres using django and or flask?
Is enforcement of a reads from a read replica an application layer task? i.e. I have a Postgres database and I have set up a read replica. On the application side I have two connections one for the "write" database and one for the "read replica" database. In my code if I do a "read" action I use the connection to the read replica. But when I go to insert or update I use the connection to the "write" database a.k.a. master. Is there better with django or flask that this is managed automatically. i.e. I would prefer to avoid specifying directly in code the connection to use and just have django or flask figure it out on their own. -
Django: Creating my own field. AttributeError: 'NoneType' object has no attribute 'x'
I'm trying to create a custom field. It's based on postgres.JSONField. class CardiosField(JSONField): """Field representing a models.Cardios object""" def from_db_value(self, value, expression, connection): if value is None: return value return parse_cardios(value) def to_python(self, value): if isinstance(value, models.Cardios): return value if value is None: return value return parse_cardios(value) def get_prep_value(self, value): cardios_pre_json = [serie_object.pre_json() for serie_object in value.series] return json.dumps(cardios_pre_json) I've created a model that has this field: class Workout(models.Model): datetime = models.DateTimeField() user = models.ForeignKey(User, on_delete=models.CASCADE) lifts = fields.LiftsField(null=True) cardios = fields.CardiosField(null=True) def __str__(self): return str(self.datetime)+" "+self.user.email __repr__ = __str__ I make migrations without a problem, but when I try to migrate, this happens: (workout) Sahands-MBP:workout sahandzarrinkoub$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, workoutcal Running migrations: Applying workoutcal.0003_auto_20171231_2308...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) … -
Django Accepting AM/PM As Form Input
I am trying to figure out how to accept am/pm as a time format in Django using a DateTime field, but I am having some trouble. I have tried setting it like this in my forms.py file pickup_date_time_from = DateTimeField(input_formats=["%m/%d/%Y %I:%M %p"]) with the following data: 12/31/2017 02:40 pm However, I get a validation error when submitting the form: (Hidden field pickup_date_time_from) Enter a valid date/time. I have also tried setting a global variable in settings.py as the documentation states: DATETIME_INPUT_FORMATS = ['%m/%d/%y %I:%M %p'] What does work is if I submit the data without the am/pm, but the output is 2017-12-31 02:40:00+00:00 Any other options? -
django test - how to get response data for future use
I'm running a login test like so: def test_login_user(self): client = APIClient() url = reverse('rest_login') data = { 'username': 'test', 'password': 'Welcome2' } response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) client.logout() If I login to the app normally I see a json return like this: { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJ1c2VybmFtZSI6ImV2YW4iLCJleHAiOjE1MTQ2NzYzNTYsImVtYWlsIjoiZXZhbkAyOGJlYXR0eS5jb20iLCJvcmlnX2lhdCI6MTUxNDY3Mjc1Nn0.8CfhfgtMLkNjEaWBfNXbUWXQMZG4_LIru_y4pdLlmeI", "user": { "pk": 2, "username": "test", "email": "test@test.com", "first_name": "", "last_name": "" } } I want to be able to grab that token value for future use however the response does not seem to have a data value to grab. -
LookupError: App 'accounts' doesn't have a 'user' model --- "App '%s' doesn't have a '%s' model." % (self.label , model_name))
I am trying to create a custom signup form for which i have extended django inbuilt user model.I am also using django-postman for user to user messaging.Postman was working quite fine till i was using inbuilt user model,however when i used the custom user model it started showing me this Lookup error(only while creating messages).I have done some research to solve this but failed. the traceback error class MadeLookupChannel(LookupChannel): File "C:\Users\vishw\Envs\Vishwesh2_env\lib\site-pack ages\ajax_select\registry.py", line 104, in MadeLookupC hannel model = get_model(app_label, model_name) File "C:\Users\vishw\Envs\Vishwesh2_env\lib\site-pack ages\ajax_select\registry.py", line 123, in get_model return apps.get_model(app_label, model_name) File "C:\Users\vishw\Envs\Vishwesh2_env\lib\site-pack ages\django\apps\registry.py", line 205, in get_model return app_config.get_model(model_name, require_rea dy=require_ready) File "C:\Users\vishw\Envs\Vishwesh2_env\lib\site-pack ages\django\apps\config.py", line 172, in get_model "App '%s' doesn't have a '%s' model." % (self.label, model_name)) LookupError: App 'accounts' doesn't have a 'user' model However i have also added this in my settings.py file in order to solve this AUTH_USER_MODEL = 'accounts.Profile' then it shows this error File "C:\Users\vishw\OneDrive\Documents\Projects_2\si mple_social_clone\simplesocial\postman\apps.py", line 1 3, in ready setup() File "C:\Users\vishw\OneDrive\Documents\Projects_2\si mple_social_clone\simplesocial\postman\models.py", line 57, in setup name_user_as = getattr(settings, 'POSTMAN_NAME_USER _AS', get_user_model().USERNAME_FIELD) AttributeError: type object 'Profile' has no attribute 'USERNAME_FIELD' this is my accounts.models.py here my Profile model extending the built in user model from django.contrib.auth.models import User from django.db … -
ValueError: Fetch argument <tf.Operation 'init_8' type=NoOp> cannot be interpreted as a Tensor
I am trying to predict by using the InceptionV3 model as the baseline model. I create the model, load the weights and predict. However; I get the above ValueError even though I have implemented the Tenserflow thread-safe model load method. The error screenshot is as follows: My code is: K.set_learning_phase(0) def baseline_model(): base_model =InceptionV3(input_shape=(299, 299, 3), weights='imagenet', include_top=False) x = base_model.output # Create model instance predictions = Dense(1, activation='sigmoid')(x) model = Model(inputs=base_model.input, outputs=predictions) for layer in base_model.layers: layer.trainable = False return model model = baseline_model() model.load_weights('weight-file.h5') graph = tf.get_default_graph() def imgEval(request): #Re-load the model onto the current request thread. global graph with graph.as_default(): Image_path = 'website_train/hello.jpg' img = load_img (Image_path) img_array = img_to_array(img) img_array /=255 img_array = img_array.reshape(1,299,299,3) y = model.predict(img_array)[0][0] print(y) return render(request, 'index.html', {}) -
Previous search on django search
Is there a way to implement going back to a previous search on a page? Example: I have an index with a search form / filters and I perform a search -> click an item in index -> display "previous search" button on this items detail view. I looked into {{ request.META.HTTP_REFERRER }} but this didn't seem to be working for me for processing the old form data on the GET request (going back to the index page). I had multiple checkboxes able to be selected so these would be added as field=1&field=2& ..... for the different options, but these weren't showing up in the url - in HTTP_REFERRER. I'd also prefer to preserve POST method so I don't have "ugly" urls, but using GET is the only way I see this being feasible. -
Django letting user filter objects with form
So I have object instances in the model and I would like to allow users to filter through them based on certain characteristics. I setup a form and added some code to handle it in the view. When the form is submitted it returns the same template but with the object filters they set. However it is not working... I was wondering why/how I should go about doing this. From: class PropertySearchForm(forms.Form): beds = forms.CharField(widget=forms.Select(attrs={'class':'form-control mb-3'}, choices=BED_CHOICES)) baths = forms.CharField(widget=forms.Select(attrs={'class':'form-control mb-3'}, choices=BATH_CHOICES)) View: def UniversityHomePageView(request,name_initials): university = get_object_or_404(University,name_initials=name_initials) listings = Listing.objects.filter(l_university=university) form = PropertySearchForm(request.GET or None) company = Company.objects.filter(c_university=university) context = { 'listings':listings, 'university':university, 'company':company, 'form':form, } if form.is_valid(): beds = int(form.cleaned_data.get('beds')) baths = int(form.cleaned_data.get('baths')) listings = Listing.objects.filter(l_university=university,beds=beds,baths=baths) return render(request,'listings/university_homepage.html',context) return render(request,'listings/university_homepage.html',context) -
celery daeminization w/ Djnago - Please explain step-by-step like I'm 5
I'm new to Python and really trying to learn things as I go. I have a Python script that pulls data from different sites and displays it to the public via a website. I am using Django with Heroku distribution. I need to automatically run my scripts in the morning to update the information. I saw that celery was the best option to do this. I now have a working example of celery, and believe that I have it properly configured with Django. However, I need to also go through a process called Daemonization as per here: http://docs.celeryproject.org/en/latest/userguide/daemonizing.html so that my celery workers can operate in the background. This is where I'm stumped, and can't find any step-by-step tutorials for this one. I think I need all of these file for things to work: /etc/init.d/celeryd /etc/defaults/celery /etc/default/celerybeat /project/celery.py /project/__init__.py I have all of these files starting in the root directory, where manage.py is located I believe I have the celery.py and __init__.py files configured correctly. Here they are: celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') # Using a string … -
How to access deployed project in gcloud shell
Deployed a django project in gcloud in flexible environment. The changes are getting reflected in the live url. I am trying to access the deployed django project folder through gcloud shell, but not able to find it. What am i doing wrong ? -
BooleanField value return always false
I need get the value of Django form checkbox in the view.py I get the value is always False (also when its True). my code is: forms.py: class PointForm(forms.ModelForm): checkboxSGEquipTypeTagAll = forms.BooleanField(label='override', widget=forms.CheckboxInput(attrs={'id': 'checkboxSGEquipTypeTagAll'}) , required=False) View: logging.debug(form.cleaned_data['checkboxSGEquipTypeTagAll']) or: logging.debug(form['checkboxSGEquipTypeTagAll'].value()) -
Unable to get repr for class
I have 2 classes in models: class Services(models.Model): name = models.CharField(max_length=100, null=True) priority = models.IntegerField(default=1, null=True) active = models.BooleanField(default=True) def __str__(self): return self.name class MacRepairPrice(models.Model): mac_model = models.ForeignKey(MacModels, null=True) service = models.ForeignKey(Services, null=True) price = models.FloatField(default=0) active = models.BooleanField(default=True) def __str__(self): return self.mac_model Views: service_list = Services.objects.filter(active=True).order_by('-priority') for serv in service_list: price_list = MacRepairPrice.objects.filter(service_id=serv.id) here I got an error:"price_list: Unable to get repr for Don't know what's wrong? Can anyone help?