Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
wagtail - How to get all pages in footer with slug in all pages
HI Tried with template tag register = template.Library() @register.simple_tag(takes_context=True) def get_all_pages(context): context['all_page'] = Page.objects.live() return context and in my template {% get_all_pages as queries %} {% for each in queries %} {{each.page_title}} {% endfor %} All pages are not passed in my templates , i want to add all pages in footer please help -
Django-filter | Boolean fields
I'm using django-filter package and I have many boolean fields. Is there a way to filter only when field is True? And show all other posibilities? For example if I have 3 fields: True, False, False... Render objects that have 1st field equal True but doesn't matter about de rest, don't consider it False. -
Django HTML drop-down list does not show the selected option
I have had this code working before, but now it does not show the selected option in the drop-down list. I just need an extra pair of eyes to look over this and let me know what is hiding in plain sight <form action="" method="GET" id="global_project"> {% csrf_token %} <select name="project_selector" id="ps" class="" autofocus onChange="this.form.submit();"> {% if project %} {% for project_name in projects_names %} <option value="{{ project_name|replace_space_with_underscore|replace_apostrophe_with_star }}" {% if project_name == project %} selected="selected" {% endif %} > {{project_name.name}} </option> {% endfor %} {% else %} <option name="project" value="setup">Setup a Project</option> {% endif %} </select> </form> -
IntegrityError when delete model instance
I have two models like class A(models.Model): title = models.CharField(max_length=255) class B(models.Model): recommendation = models.ForeignKey(A, related_name="+") title = models.CharField(max_length=255) When I remove the A model instance, I get something like: IntegrityError: update or delete on table "myapp_a" violates foreign key constraint "myapp_relate_recommendation_id_4a7c5340_fk_myapp_a_id" on table "myapp_b" Detail: Key (id)=(27527) is still referenced from table "myapp_b". I can't figure out why it happens, I thought FKs should be deleted by default. -
How to hide fields for specific record in django-admin?
How to hide field for specific record in djano-admin? For example if I have a model class Book(models.Model): title = models.CharField(..., null=True) author = models.CharField(...) I want to hide an author in admin panel for record with pk = 1. I found the solution as class BookAdmin(admin.ModelAdmin): list_display = ("pk", "get_title_or_nothing") def get_form(self, request, obj=None, **kwargs): if obj.pk == "1": self.exclude = ("author", ) form = super(BookAdmin, self).get_form(request, obj, **kwargs) return form It works well untill I am coming back from record with pk == 1 to other records, in this case all records in table have hided author field. -
javascript template for showing table body
I am using ajax for updating/refreshing the cart when an item is removed from the cart table to show the updated items. ajax functionality and logic is working but could not show the following template inside <tbody class="cart-body"> {% for furniture in cart.furnitures.all %} <tr class="cart-products"> <td class="action"> {% include 'includes/carts/remove-furniture.html' with furniture_id=furniture.id%} </td> <td class="cart_product_img"> {% if furniture.first_image %} <a href="#"> <img src="/media/{{ furniture.first_image.url }}" alt="" class="img-responsive"> </a> {% else %} <a href="#"> <img src={% static 'img/default.jpg' %} alt="" class="img-responsive"> </a> {% endif %} </td> <td class="cart_product_desc"> <h5>{{ furniture.name }}</h5> </td> <td class="price"> <span>Rs. {{ furniture.price }}</span></td> <td class="qty"> <div class="quantity"> <span class="qty-minus" <i class="ion-ios-minus-outline" aria-hidden="true"></i> </span> <input type="number" class="qty-text" id="qty" step="1" min="1" max="99" name="quantity" value="1"> <span class="qty-plus" <i class="ion-ios-plus-outline" aria-hidden="true"></i> </span> </div> </td> <td class="total_price"> <span>Rs 49.88</span></td> </tr> {% endfor %} </tbody> the following template is shown when user is routed to /carts page but when the update part is done, ajax is used and the template i tried is as following success: function(data) { var hiddenCartItemRemoveForm = $(".cart-item-remove-form") if (data.products.length > 0){ productRows.html(" ") $.each(data.products, function(index, value){ var newCartItemRemove = hiddenCartItemRemoveForm.clone() newCartItemRemove.css("display", "block") newCartItemRemove.find(".cart-item-product-id").val(value.id) cartBody.prepend( "<tr><td class='action'>" + newCartItemRemove.html() +"</td><td class='cart_product_img'><a href=""><img src="media/"+data.image class='img-responsive'></a></td><td class='cart_product_desc'><h5>"+value.name+"</h5></td><td class='price'>"+value.price+"</tr>" ) … -
why admin panel of django appears different in production version?
first of all, I don't know whether it's only my issue or someone else have it too. my production version of django admin (which I use it in my website) looks different from what I see, when I lunch a project on my personal computer. you can see the difference In two pictures : local version (127.0.0.1:8000) production version (mywebsite) something that I want to mention: I did not edited the admin template I used collectstatic command in production version Checked it with different browsers Version of django is 1.11 in both server and local So do I have to do something else after doing collectstatic ? -
SMTPServerDisconnected: Connection unexpectedly closed, django, celery?
hello i want to sending email activation this is my settings EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'email' EMAIL_HOST_PASSWORD = 'pass' EMAIL_PORT = 587 EMAIL_USE_TLS = True when i try to send email by celery i get this error, on local server sending email is work, but not work registration, how to solve? maybe because i have ssl, and i use all tls? Traceback (most recent call last): File "/webapps/theband/lib/python3.5/site-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/webapps/theband/lib/python3.5/site-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "/webapps/theband/src/accounts/tasks.py", line 22, in send_some_email_task msg.content_subtype = 'html' File "/webapps/theband/lib/python3.5/site-packages/django/core/mail/message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "/webapps/theband/lib/python3.5/site-packages/django/core/mail/backends/smtp.py", line 104, in send_messages new_conn_created = self.open() File "/webapps/theband/lib/python3.5/site-packages/django/core/mail/backends/smtp.py", line 64, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/usr/lib/python3.5/smtplib.py", line 251, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python3.5/smtplib.py", line 337, in connect (code, msg) = self.getreply() File "/usr/lib/python3.5/smtplib.py", line 393, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed -
Django service on gunicorn POST request is recieved as GET?
I have a Django rest service running on virutal environment on gunicorn server with the following .wsgi file: import os, sys import site site.addsitedir('/opt/valuation/env/lib/python2.7/site-packages') sys.stdout = sys.stderr os.environ['DJANGO_SETTINGS_MODULE'] = 'valuation.valuationcont.valuation.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() When I do curl POST call the service works perfectly: curl -H "Content-Type: application/json" -X POST -d '{...}' -u username:password http://localhost:8000/valuation/predict/ But when I do the same request on API gateway using axios, Django service responds my custom GET response ("GET not supported, try POST"). axios({ method: 'post', url:'http://localhost:8000/valuation/predict', headers:{ "Content-Type":"application/json", "Authorization":"Basic [BASE64 ENCODING]" }, data:{ ... } }).then(response=>{ console.log(response.data) }).catch(err=>{ console.log(err.toString()) }) The request is transformed from GET to POST. This only happens with the django/gunicorn service. Since I am new to django/gunicorn I think there is something wrong with the .wsgi file. But how come the curl call then works? Any help appreciated, been struggling with this for a week now. -
Spaces and special characters in URL - django
My URL is as follows: test/One%20**&**%20Two/edit django URLs: r'^(?P<test>[\w\-]+)/(?P<text>[\w\s]+)/edit/$' Can anyoen tell me why django is not able to display page ? ( I see Page not found (404) ) -
How much data can be serialized by Django
For instance i have millions of users and i want to serialize all users data and return it when client requests, so client can get list of all users. Also is this a is a good approach? performance wise. -
could not connect to server, django, celery, sqlite3, how to solve?
when i send register tast, email sending, like register is successes, but it's not, email is correct, but it's cannot to work, beacuse user have no in a database. redis, celery is runnig, sending on email tasks is executing! P.S. i'm using sqlite3 database! raised unexpected: OperationalError('could not connect to server: Connection refused (0x0000274D/10061)\n\tIs the server running on host "localhost" (::1) and accepting\n\tTCP/IP connections on port 5432?\ncould not connect to server: Connection refused (0x0000274D/10061)\n\tIs the server running on host "localhost" (127.0.0.1) and accepting\n\tTCP/IP connections on port 5432?\n',) Traceback (most recent call last): File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\celery\app\trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\celery\app\trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\Dev\Deploy__\theband\src\accounts\tasks.py", line 34, in register_task email=email File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\contrib\auth\models.py", line 159, in create_user return self._create_user(username, email, password, **extra_fields) File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\contrib\auth\models.py", line 153, in _create_user user.save(using=self._db) File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\contrib\auth\base_user.py", line 80, in save super(AbstractBaseUser, self).save(*args, **kwargs) File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\db\models\base.py", line 808, in save force_update=force_update, update_fields=update_fields) File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\db\models\base.py", line 835, in save_base with transaction.atomic(using=using, savepoint=False): File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\db\transaction.py", line 158, in __enter__ if not connection.get_autocommit(): File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\db\backends\base\base.py", line 385, in get_autocommit self.ensure_connection() File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\db\backends\base\base.py", line 213, in ensure_connection self.connect() File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\db\utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\utils\six.py", line 685, … -
Django-filter | How to render boolean field
I'm using django-filter package and I want to filter by many boolean fields, but django renders it as . I try to declare the fields as: django_filters.BooleanFilter() and put it into class Meta fields, but it has always been displayed in template as . How do I have to do it? -
What should I override in a FormView to insert my permissions checking?
Of its available methods, which is the ideal place to place permission checking? If get(), should it also be in the post()? The code lives in its own permissions.py and looks like this: def has_perm_or_is_owner(user_object, permission, instance=None): if instance is not None: if user_object == instance.user: return True return user_object.has_perm( permission ) It checks whether the request.user is the rightful owner of the form instance. This particular form should not be viewable to anyone else. The code I am trying to find a place to insert within the CBV, is here: can_edit = has_perm_or_is_owner( self.request.user, 'profile.fill_form', instance=obj, ) if not can_edit: raise Http404 This is usually an easy choice with, say, an UpdateView, as I'll just stick it inside the get_object(). With FormViews, this is a bit more ambiguous. Thoughts? -
django-rest-auth installition error
im trying to install django -rest- auth with in my application in (venv) pip install django-rest-auth but i get this error. why? note: ** django and djangorestframwork are already installed pip install django-rest-auth Collecting django-rest-auth Using cached django-rest-auth-0.9.2.tar.gz Requirement already satisfied: Django>=1.8.0 in ./venv/lib/python3.5/site-packages (from django-rest-auth) Requirement already satisfied: djangorestframework>=3.1.0 in ./venv/lib/python3.5/site-packages (from django-rest-auth) Requirement already satisfied: six>=1.9.0 in ./venv/lib/python3.5/site-packages (from django-rest-auth) Requirement already satisfied: pytz in ./venv/lib/python3.5/site-packages (from Django>=1.8.0->django-rest-auth) Building wheels for collected packages: django-rest-auth Running setup.py bdist_wheel for django-rest-auth ... error Complete output from command /home/mohammadreza/PycharmProjects/mohammadrezaDjangoApp/Django/venv/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-xl9ds058/django-rest-auth/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/tmp5sk4s13wpip-wheel- --python-tag cp35: usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help error: invalid command 'bdist_wheel' ---------------------------------------- Failed building wheel for django-rest-auth Running setup.py clean for django-rest-auth Failed to build django-rest-auth Installing collected packages: django-rest-auth Running setup.py install for django-rest-auth ... done Successfully installed django-rest-auth-0.9.2 -
raised unexpected: OperationalError, celery django?
when i try create an user, celery give me this error, how to fix this? when i register, email sending, like register is successes but, it's not, email right, correct, but it's cannot to work, beacuse user have in a database. raised unexpected: OperationalError('could not connect to server: Connection refused (0x0000274D/10061)\n\tIs the server running on host "localhost" (::1) and accepting\n\tTCP/IP connections on port 5432?\ncould not connect to server: Connection refused (0x0000274D/10061)\n\tIs the server running on host "localhost" (127.0.0.1) and accepting\n\tTCP/IP connections on port 5432?\n',) Traceback (most recent call last): File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\celery\app\trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\celery\app\trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\Dev\Deploy__\theband\src\accounts\tasks.py", line 34, in register_task email=email File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\contrib\auth\models.py", line 159, in create_user return self._create_user(username, email, password, **extra_fields) File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\contrib\auth\models.py", line 153, in _create_user user.save(using=self._db) File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\contrib\auth\base_user.py", line 80, in save super(AbstractBaseUser, self).save(*args, **kwargs) File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\db\models\base.py", line 808, in save force_update=force_update, update_fields=update_fields) File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\db\models\base.py", line 835, in save_base with transaction.atomic(using=using, savepoint=False): File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\db\transaction.py", line 158, in __enter__ if not connection.get_autocommit(): File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\db\backends\base\base.py", line 385, in get_autocommit self.ensure_connection() File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\db\backends\base\base.py", line 213, in ensure_connection self.connect() File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\db\utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "c:\users\p.a.n.d.e.m.i.c\desktop\dev\theband\lib\site-packages\django\utils\six.py", line 685, in reraise raise … -
How to use MongoDB with Django?
I'm trying to use MongoDB with Django, I searched for solutions and found these two options. https://github.com/MongoEngine/mongoengine https://github.com/django-nonrel/mongodb-engine but i'm not sure to use which one. If anyone has used one of them please suggest one for me, or if there is any other solutions please let me know. -
Page is loading no result no error
code is created = UserQuickLook.objects.filter(created_at__isnull=False).values() while (current_date >= from_date): for i,key in enumerate(created): if key == current_date: r = r + 1 ws.write(0,r,current_date,style) current_date -= timedelta(days = 1) please help me is there any wrong with this code because it is not showing the error nor output what i a doing is checking the date range weather exits in my database or not if exits print that date if not skip that date -
django ambiguous foreign key error on makemigrations
I am trying to create a many-to-many field in my Django model but I am getting Ambiguous Foreign Keys error. My code: class Organization(AbstractOrganization): users = models.ManyToManyField(USER_MODEL, through="OrganizationUser") class OrganizationUser(AbstractOrganizationUser): user = models.ForeignKey(USER_MODEL, related_name="organization_users_user", on_delete=models.SET_NULL, null=True) organization = models.ForeignKey(Organization, related_name="organization_users_organization", on_delete=models.SET_NULL, null=True) class OrganizationOwner(AbstractOrganizationOwner): organization = models.OneToOneField(Organization, related_name="organization_owner_organization", on_delete=models.SET_NULL, null=True) organization_user = models.OneToOneField(OrganizationUser, related_name="organization_owner_organization_user", on_delete=models.SET_NULL, null=True) The error I am getting on running python manage.py makemigrations: companies_users.Organization.users: (fields.E335) The model is used as an intermediate model by 'companies_users.Organization.users', but it has more than one foreign key to 'User', which is ambiguous. You must specify which foreign key Django should use via the through_fields keyword argument. HINT: If you want to create a recursive relationship, use ForeignKey("self", symmetrical=False, through="OrganizationUser"). I am stuck at this part. how can I solve this? -
Different models in django-template
I'm very new in Django and couldn't find solution for this. How can I pass 2 querysets from different models in 1 template? I use mptt categories and stack with it for awhile. I know that I have to make something with views.py but how can I combine these querysets? Here is my Models.py from __future__ import unicode_literals from django.db import models from django.core.urlresolvers import reverse from mptt.models import MPTTModel, TreeForeignKey class Variant(MPTTModel): category = models.CharField(max_length=500) logo = models.ImageField(upload_to='images/', null=True, blank=True) slug = models.SlugField(max_length=160, blank=True, null=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE) class MPTTMeta: order_insertion_by = ['category'] class Meta: verbose_name = 'категория' verbose_name_plural = 'категории' def get_absolute_url(self): return reverse('cosmetics:details', kwargs={'pk': self.pk}) def __str__(self): return self.category def is_second_node(self): return True if (self.get_ancestors().count() == 1) else False class Pic_Discription(models.Model): variant = TreeForeignKey('Variant', null=True, blank=True) model = models.CharField(max_length=500) pic_title = models.ImageField(upload_to='images/', null=True, blank=True) description = models.TextField(default='') price = models.DecimalField(max_digits=10, decimal_places=2, default=0) slug = models.SlugField(max_length=160,blank=True, null=True) available = models.BooleanField(default=True) class Meta: verbose_name = 'Продукт' verbose_name_plural = 'Продукты' def __str__(self): return self.model def get_absolute_url(self): return reverse('cosmetics:details', kwargs={'pk': self.pk}) Views.py class CategoryView(generic.ListView): model = Variant template_name = 'cosmetics/homepage.html' def get_context_data(self, *, object_list=None, **kwargs): """Get the context for this view.""" queryset = object_list if object_list … -
Internal Server Error, cannot use celery, to create and send anything, django nginx, how to solve?
My celery not working, not sending email on email, not register people, nothing, but on local server email is sending, but still not register people, also, i can not to create files, i can not, do everythong, which i can on local server on windows this one of the error which was send on admin email(my email) Internal Server Error: /purchase_tickets/ TypeError at /purchase_tickets/ super(type, obj): obj must be an instance or subtype of type Request Method: POST Request URL: https://therockband.tk/purchase_tickets/ Django Version: 1.11.6 Python Executable: /webapps/theband/bin/python3 Python Version: 3.5.2 Python Path: ['/webapps/theband/src', ‘/webapps/theband/bin’, ‘/webapps/theband/src’, ‘/webapps/theband/lib/python35.zip’, ‘/webapps/theband/lib/python3.5’, ‘/webapps/theband/lib/python3.5/plat-x86_64-linux-gnu’, ‘/webapps/theband/lib/python3.5/lib-dynload’, ‘/usr/lib/python3.5’, ‘/usr/lib/python3.5/plat-x86_64-linux-gnu’, ‘/webapps/theband/lib/python3.5/site-packages’, ‘/webapps/theband/src’] Server time: Wed, 27 Dec 2017 09:01:02 +0000 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'TheBand'] Installed 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'] Traceback: File “/webapps/theband/lib/python3.5/site-packages/django/db/models/query.py” in get_or_create 464. return self.get(**lookup), False File “/webapps/theband/lib/python3.5/site-packages/django/db/models/query.py” in get 380. self.model._meta.object_name During handling of the above exception (QRCode matching query does not exist.), another exception occurred: File “/webapps/theband/lib/python3.5/site-packages/django/core/handlers/exception.py” in inner 41. response = get_response(request) File “/webapps/theband/lib/python3.5/site-packages/django/core/handlers/base.py” in _get_response 187. response = self.process_exception_by_middleware(e, request) File “/webapps/theband/lib/python3.5/site-packages/django/core/handlers/base.py” in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File “/webapps/theband/src/TheBand/views.py” in purchase_tickets 112. qr_img = qr_code_generator(hex_code, username, __show__id, q, price) File … -
logout not working, caching on nginx and clodflare, how to allow logout?
I have everything cached, if I logged into my account, you will not be able to log out any more) how do you get out when you quit? the cache is on the nginx and clodflare there in the rules I prescribed, so that it does not cache the admin panel and everything that is connected to it P.S. i clean cache on nginx and cloudflare, still have cache) nginx conf "/etc/nginx/nginx.conf" ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AES:!ADH:!AECDH:!MD5:!DSS; ssl_session_cache shared:SSL:100m; ssl_session_timeout 3m; ssl_buffer_size 16k; spdy_headers_comp 6; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; proxy_connect_timeout 5; proxy_send_timeout 10; proxy_read_timeout 10; proxy_buffering on; proxy_buffer_size 16k; proxy_buffers 24 16k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; proxy_temp_path /tmp/nginx/proxy_temp; add_header X-Cache-Status $upstream_cache_status; proxy_cache_path /tmp/nginx/cache levels=1:2 keys_zone=one:100m; proxy_cache_path /tmp/nginx/cache2 levels=1:2 keys_zone=two:100m; proxy_cache one; proxy_cache_valid any 30d; proxy_cache_key $scheme$proxy_host$request_uri$cookie_US; my server conf upstream theband { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a … -
django template <select> box is not selecting value
Django template my select box is not selecting value i have the following code. template_name.html <select name="class_id" > {% for object in classes %} <option value="{{ object.id }}" {% if object.id == class_id %} selected="selected" {% endif %}> {{ object.name }} </option> {% endfor %} </select> view.py class_id = request.POST.get('class_id', 0) context_data = {'class_id':class_id} return render(request, "template_name.html",context_data) -
Need to save estimate model in Django
I have below models.py and admin.py files in Django. I wanted to do 2 things Merge specs field of Environment and ItemObject and store into specs of Environment which I managed to do because I was able to figure out where to place the logic. (class AddEnvironmentDetailsInlineForm(forms.ModelForm)) I need to do the same for Estimate. I need to fetch the Environment.specs and Estimate.specs, merge the two and save in Estimate.specs The merge is like ItemObject -> Environment -> Estimate The challenge is that I cannot figure out where to put that logic for Estimate and Environment. Do I need to create a ModelForm for Estimate to achieve a merge? I am not clear on the logic here for the files (I am still learning the concepts in Django). If anyone could make me understand, it would be great. models.py class CommonModel(models.Model): author = models.ForeignKey('auth.User',) title = models.CharField(max_length=400) comments = models.TextField(blank=True) requirements = JSONField(default = {}) specs = JSONField(default= {}) created_date = models.DateTimeField(default=timezone.now) updated_date = models.DateTimeField(blank=True, null=True) class Meta: abstract = True def update(self): self.updated_date = timezone.now() self.save() def __str__(self): return self.title class Estimate(CommonModel): gp_code = models.TextField(default='Unknown') inputs = models.TextField(blank=True) @property def otc_price(self): environments=Environment.objects.filter(estimate=self) sum = defaultdict(list) for env in environments: … -
logout not working, caching on nginx and clodflare, how to allow logout?
I have everything cached, if I logged into my account, you will not be able to log out any more) how do you get out when you quit? the cache is on the nginx and clodflare there in the rules I prescribed, so that it does not cache the admin panel and everything that is connected to it P.S. i clean cache on nginx and cloudflare, still have cache) nginx conf "/etc/nginx/nginx.conf" ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AES:!ADH:!AECDH:!MD5:!DSS; ssl_session_cache shared:SSL:100m; ssl_session_timeout 3m; ssl_buffer_size 16k; spdy_headers_comp 6; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; proxy_connect_timeout 5; proxy_send_timeout 10; proxy_read_timeout 10; proxy_buffering on; proxy_buffer_size 16k; proxy_buffers 24 16k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; proxy_temp_path /tmp/nginx/proxy_temp; add_header X-Cache-Status $upstream_cache_status; proxy_cache_path /tmp/nginx/cache levels=1:2 keys_zone=one:100m; proxy_cache_path /tmp/nginx/cache2 levels=1:2 keys_zone=two:100m; proxy_cache one; proxy_cache_valid any 30d; proxy_cache_key $scheme$proxy_host$request_uri$cookie_US; my server conf upstream theband { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a …