Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
django call related model queryset like rails activerecord merge scope
Say we have two models Employer and Department: class Profile < ApplicationRecord belongs_to :account scope :age_upper, ->(age) { where("age > ?", age) } end class Account < ApplicationRecord has_one :profile end Then we can have a query on Department model in Rails like this: >>> Account.joins(:profile).merge(Profile.age_upper(18)) But with Django: class ProfileQuerySet(models.QuertSet): def age_upper(age): return self.filter(age__gt=age) class Profile(models.Model): account = models.ForiegnKey('Account', on_delete=models.CASCADE) objects = models.Manager.from_queryset(ProfileQuerySet)() class Account(models.Model): pass My question is can we query from Account using filter age_upper of Profile instead of rewrite another one for Account like below class AccountQuerySet(models.QuertSet): def age_upper(age): return self.filter(profile__age__gt=age) class Account(models.Model): objects = models.Manager.from_queryset(AccountQuerySet)() -
django-rest-framework multiple lookup_fields
The code below try's to lookup the Car Object based on the url of: example.com/<user>/<slug>/. The error i'm receiving is: invalid literal for int() with base 10: 'exampleUsername' from the url of : example.com/exampleUsername/exampleCarSlug/. The code below is able to lookup the Car Object if i use the userID instead of the user's username, e.g example.com/<user_id>/<slug>/ = example.com/20/exampleCarSlug/ that is if i replace all instances of user with user_id in the code below. What i would like to know, is how can i lookup the Car Object using the user's username (string) instead of the user's ID (integer). Url urlpatterns = [ url(r'^car/(?P<user>\w+)/(?P<slug>[\w-]+)/$', CarAPIView.as_view(), name='car'), ] View from django.shortcuts import get_object_or_404 class MultipleFieldLookupMixin(object): """ Apply this mixin to any view or viewset to get multiple field filtering based on a `lookup_fields` attribute, instead of the default single field filtering. """ def get_object(self): queryset = self.get_queryset() # Get the base queryset queryset = self.filter_queryset(queryset) # Apply any filter backends filter = {} for field in self.lookup_fields: if self.kwargs[field]: # Ignore empty fields. filter[field] = self.kwargs[field] obj = get_object_or_404(queryset, **filter) # Lookup the object self.check_object_permissions(self.request, obj) return obj class CarAPIView(MultipleFieldLookupMixin, RetrieveAPIView): queryset = Car.objects.all() serializer_class = CarSerializer permission_classes = [IsAuthenticatedOrReadOnly] lookup_fields = … -
Python3, re.match with list
I read this : https://stackoverflow.com/a/17090205/6426449 And I made a list that cannot be used on username in django. list : FORBIDDEN_USERNAME_LIST = ['admin', 'master', 'owner'] So I made a code like this : views.py def username_choice(request): if request.method == "POST": username = request.POST['username'] for item in forbidden.FORBIDDEN_USERNAME_LIST: match = re.search("r'\b"+item+"\b'", username) if match: return JsonResponse({'result': item + 'banned username'}) But It seems that it does not work. Maybe I think, match = re.search("r'\b"+item+"\b'", username) Here is problem. How can I fix that? -
how to save PDF file generate by WeasyPrint django in a folder directory
I'm trying save a .pdf file in a folder using WeasyPrint with django==1.11 with python3.4, but I don't found nothing about this issue. file_location = '%s/uploads/cartas/%s.pdf' % (settings.MEDIA_ROOT, car_key) html_string = render_to_string('tpl-export-pdf.html', context) html = HTML(string=html_string, base_url=request.build_absolute_uri()) #html.write_pdf(target=file_location, stylesheets=[CSS(settings.STATIC_ROOT + '/app/css/table.css')]) result = html.write_pdf(target=file_location, stylesheets=[CSS(settings.STATIC_ROOT + '/app/css/table.css')]) response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = 'attachment; filename=%s.pdf' % car_key response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'rb') response.write(output.read()) I'm getting this error on Debug Mode Request Method: GET Request URL: http://127.0.0.200/admin/cartafrete/export/pdf/240531/ Django Version: 1.11 Exception Type: TypeError Exception Value: 'NoneType' does not support the buffer interface Exception Location: /usr/lib/python3.4/tempfile.py in func_wrapper, line 538 Python Executable: /usr/bin/python3 Python Version: 3.4.3 -
I never granted the permission I'm checking for, yet the view works as if I granted the permission
I implemented a permission check but it doesn't hold. Here is the CBV using a PermissionRequiredMixin: class PreferenceUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView): form_class = PreferenceUpdateForm model = Profile template_name = 'user_profile/preference_edit.html' permission_required = ('user_profile.change_profile', 'user_profile.can_change_profile', 'user_profile.can_change') I'm visiting the view by changing the pk in the URL. My current user should not be allowed to see this preference update page, as it does not belong to the request.user. However even after listing the permission_required, I am allowed to view the page. Shouldn't the page only show if I user.user_permissions.add(permission)? -
Django oracle its not working
I already install oracle client 12.2 also i installed pip instal cx_Oracle but this error seeing. I given my database connection settings to settings.py im sure its completely true but whats the error exactly mean ? Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 128, in inner_run web_1 | self.check_migrations() web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 422, in check_migrations web_1 | executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 20, in __init__ web_1 | self.loader = MigrationLoader(self.connection) web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 52, in __init__ web_1 | self.build_graph() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 209, in build_graph web_1 | self.applied_migrations = recorder.applied_migrations() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations web_1 | self.ensure_schema() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema web_1 | if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 254, in cursor web_1 | return self._cursor() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 229, in _cursor web_1 | self.ensure_connection() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection web_1 | self.connect() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__ web_1 | six.reraise(dj_exc_type, dj_exc_value, traceback) web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise web_1 | raise value.with_traceback(tb) web_1 | … -
Get a tuple value in a tuple by index
for a Django Model i needed an extra field to set a special month. This was done with the choices attribute an a tuple set: class Timeline(models.Model): MONTHS = ( (1, _("January")), (2, _("February")), (3, _("March")), (4, _("April")), (5, _("May")), (6, _("June")), (7, _("July")), (8, _("August")), (9, _("September")), (10, _("October")), (11, _("November")), (12, _("December")), ) tldate_mth = models.IntegerField(_("Month"), choices=MONTHS, default=1) In admin section this works fantastic. Now i want to output the month in my template: # ... def to_string(self): return "%s (%s / %d)" % (self.title, self.MONTHS.index(self.tldate_mth), self.tldate_yr) But then i got the message "tuple.index(x): x not in tuple". What did i wrong? -
python-docx document-styles font failed to the Heading style
I have used python-docx in my django project to MS-word report, and I modified the Normal content style successfully, I have got the '宋体' font: document.styles['Normal'].font.name = u'宋体' report.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') document.styles['Normal'].font.size = Pt(9) But when I use it to the Heading content, the Heading font did not change. no any failed shows.Curiously, the Heading size was changed. Why this happened, how to solve this? document.add_paragraph('1.清单', 'Heading 1') document.add_paragraph('设备:', 'Heading 2') document.styles['Heading 1'].font.name = u'宋体' document.styles['Heading 1']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') document.styles['Heading 1'].font.size = Pt(12) document.styles['Heading 2'].font.name = u'宋体' document.styles['Heading 2']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') document.styles['Heading 2'].font.size = Pt(10.5) And I want to konw how to modify Chinese and English fonts respectively? Thanks! -
Manage image uploaded in a form: copy paste to another model when POST and dropdown display in Django
The project I'm working on is an application made to facilitate the creation of PDF technical sheets via a big form. In order to be able to erase or edit the values without any impact the already created PDF sheets, I duplicated my models so that 1 is linked to a main model with fk or m2m and the other is independent. I make the form from the main model. Until I submit the form, the data comes from my independent models (so I don't use Form nor modelForm). When I POST, I want it to be copied and pasted on the equivalent model (the one linked to the main model). I have dropdown lists to choose the information. If the data I need doesn't exist yet, I have a modal "create new ..." that allows me to create a new one that is dynamically added to the dropdown list. Everything works well, except for the ImageField. The new images and their information are well stocked into the independent model but not transferred into the equivalent one and the line in the dropdown list displays "undefined" values. I've read about non compatibility between JSON and imagefields, that's why I indicated … -
How can I serialize the OneToOneField to be list in Django-Rest-Framework?
How can I serialize the OneToOneField to be list? I have two Model: class SwitchesPort(models.Model): """ SwitchesPort """ name = models.CharField(max_length=32) profile = models.CharField(max_length=256) class Server(models.Model): ... switchesport = models.OneToOneField(to=SwitchesPort, related_name="server", on_delete=models.DO_NOTHING, null=True) You see, they are OneToOne relationship. In the SwitchesPortSerializer, I only can set the physical_server many=False: class SwitchesPortSerializer(ModelSerializer): """ SwitchesPort """ physical_server = ServerSerializer(many=False, read_only=True) class Meta: ... If I set True there will reports error, because they are one to one relationship. The result will be like this: [ { "name": "switches_port01", "profile":"", "physical_server": { "name": "server01", ... } }, ... ] But, I want to get the physical_server as a JSON list, not the JSON object, how can I do that in Django-Rest-Framework? My requirement data is like this: [ { "name": "switches_port01", "profile":"", "physical_server": [ { "name": "server01", ... } ] }, ... ] Although the relationship is one-to-one, I still want to get the list, not the object. Is it feasible to get that? -
python.manage.py runserver got many Importing xxx_ImagePlugin
After I update django version to 2.0 and begin to work with virtual environment when run the command: python manage.py runserver my log got many lines with info related Importing xxx_ImagePlugin. All work OK but I do not understand why its appear each time and how to remove its from the log? log: 2017-12-27 09:05:49, Importing BmpImagePlugin 2017-12-27 09:05:49, Importing BufrStubImagePlugin 2017-12-27 09:05:49, Importing CurImagePlugin 2017-12-27 09:05:49, Importing DcxImagePlugin 2017-12-27 09:05:49, Importing DdsImagePlugin 2017-12-27 09:05:49, Importing EpsImagePlugin 2017-12-27 09:05:49, Importing FitsStubImagePlugin 2017-12-27 09:05:49, Importing FliImagePlugin 2017-12-27 09:05:49, Importing FpxImagePlugin 2017-12-27 09:05:49, Importing FtexImagePlugin 2017-12-27 09:05:49, Importing GbrImagePlugin 2017-12-27 09:05:49, Importing GifImagePlugin 2017-12-27 09:05:49, Importing GribStubImagePlugin 2017-12-27 09:05:49, Importing Hdf5StubImagePlugin 2017-12-27 09:05:49, Importing IcnsImagePlugin 2017-12-27 09:05:49, Importing IcoImagePlugin 2017-12-27 09:05:49, Importing ImImagePlugin 2017-12-27 09:05:49, Importing ImtImagePlugin 2017-12-27 09:05:49, Importing IptcImagePlugin 2017-12-27 09:05:49, Importing JpegImagePlugin 2017-12-27 09:05:49, Importing Jpeg2KImagePlugin 2017-12-27 09:05:49, Importing McIdasImagePlugin 2017-12-27 09:05:49, Importing MicImagePlugin 2017-12-27 09:05:49, Importing MpegImagePlugin 2017-12-27 09:05:49, Importing MpoImagePlugin 2017-12-27 09:05:49, Importing MspImagePlugin 2017-12-27 09:05:49, Importing PalmImagePlugin 2017-12-27 09:05:49, Importing PcdImagePlugin 2017-12-27 09:05:49, Importing PcxImagePlugin 2017-12-27 09:05:49, Importing PdfImagePlugin 2017-12-27 09:05:49, Importing PixarImagePlugin 2017-12-27 09:05:49, Importing PngImagePlugin 2017-12-27 09:05:49, Importing PpmImagePlugin 2017-12-27 09:05:49, Importing PsdImagePlugin 2017-12-27 09:05:49, Importing SgiImagePlugin 2017-12-27 09:05:49, Importing SpiderImagePlugin 2017-12-27 09:05:49, Importing … -
Print Dates range if they are available in Database
from below code i am going to print date ranges that's fine but what the problem is i need to print the date ranges , those available in database only [this image shows the created_at date field which is in look model . I need these dated to be printed if user select the date rage between dec 1 to dec 30 ]1 while (current_date >= from_date): r = r + 1 ws.write(0,r,current_date,style) current_date -= timedelta(days = 1) -
500 Internal Server Error: Python 3.5, Django and mod_wsgi
I'm trying to deploy a Python/Django application on DigitalOcean and getting the following error: apache error.log [wsgi:error] [pid 17060] from django.core.wsgi import get_wsgi_application [wsgi:error] [pid 17060] ImportError: No module named 'django' [wsgi:error] [pid 17060] mod_wsgi (pid=17060): Target WSGI script '/var/www/demo-app/src/demo/demo/wsgi.py' cannot be loaded as Python module. [wsgi:error] [pid 17060] mod_wsgi (pid=17060): Exception occurred processing WSGI script '/var/www/demo-app/src/demo/demo/wsgi.py'. [wsgi:error] [pid 17060] Traceback (most recent call last): [wsgi:error] [pid 17060] File "/var/www/demo-app/src/demo/demo/wsgi.py", line 12, in <module> [wsgi:error] [pid 17060] from django.core.wsgi import get_wsgi_application [wsgi:error] [pid 17060] ImportError: No module named 'django' [wsgi:error] [pid 17060] mod_wsgi (pid=17060): Target WSGI script '/var/www/demo-app/src/demo/demo/wsgi.py' cannot be loaded as Python module. [wsgi:error] [pid 17060] mod_wsgi (pid=17060): Exception occurred processing WSGI script '/var/www/demo-app/src/demo/demo/wsgi.py'. [wsgi:error] [pid 17060] Traceback (most recent call last): [wsgi:error] [pid 17060] File "/var/www/demo-app/src/demo/demo/wsgi.py", line 12, in <module> [wsgi:error] [pid 17060] from django.core.wsgi import get_wsgi_application [wsgi:error] [pid 17060] ImportError: No module named 'django' My setup is as follows: Ubuntu==16.04 django==1.11.4 apache==2.4.18 mod-wsgi==4.5.22 python 3.5(virtualenv) libapache2-mod-wsgi-py3 Any ideas on what I'm missing?