Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to trigger multiple submit buttons with one button outside the form?
I am new to Javascript/jQuery. I came to know that i can trigger multiple buttons for one submit button. But i want to submit multiple forms which is actually in a loop. If you don't understand the question. Please look at this question also. I need to submit all the forms at once. -
redirecting to two different view from a form input
I have a PostForm model form to create posts for my blog app. Now the user has two options after filling the post form he/she can publish it immediately or can put it into the drafts for later publishing. when published the user will be redirected to that post's detail view but when drafted it will redirect to user's draft list view. I don't want to create a detail view for the draft posts. But I am not able to implement how can I redirect a user to two different views with the two different submit option (Publish and draft) in the form. create view model = Post template_name = 'blog/post_form.html' form_class = PostForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'Create' return context def form_valid(self, form): form.instance.author = self.request.user form.save() return super().form_valid(form) post_form.html model = Post template_name = 'blog/post_form.html' form_class = PostForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'Create' return context def form_valid(self, form): form.instance.author = self.request.user form.save() return super().form_valid(form) -
Error "could not be changed because the data didn't validate"
I can't update extended user profile In views.py: views.py def profile(request, user_id): user = get_object_or_404(User, id=user_id) user_info = get_object_or_404(UserInfor, user_id=user.id) if request.method == "POST": user_form = UserForm(data=request.POST or None, instance=user) profile_form = ProfileForm(data=request.POST or None, instance=user_info) user = user_form.save(commit=True) user_info = profile_form.save(commit=True) user.save() user_info.save() return render(request, 'pages/profile.html', {'user': user_form, 'user_info': profile_form, 'user_id': user_id}) else: user_form = UserForm(instance=user) profile_form = ProfileForm(instance=user_info) return render(request, 'pages/profile.html', {'user': user_form, 'user_info': profile_form, 'user_id': user_id}) How can I fix error? -
Non_field_errors no data provided in django webapi
I am new in Django and python. Now I am trying to do web API with Django and python. I can get the get request but when I request the post method, this error is shown "non_field_errors": [ "No data provided" ] View.py=> from rest_framework.generics import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from .models import Allowance from .serializers import AllowanceSerializer # Create your views here. class AllowanceAPIView(APIView): def get(self,request,pk=None): if pk: allowance=get_object_or_404(Allowance.objects.all(),pk=pk) serializer = AllowanceSerializer(allowance) return Response({serializer.data}) allowance=Allowance.objects.all() serializer = AllowanceSerializer(allowance,many=True) return Response({"allowance":serializer.data}) def post(self,request): allowance = request.data.get('allowance') serializer = AllowanceSerializer(data=allowance) if serializer.is_valid(raise_exception=True): allowance_saved=serializer.save() return Response({"success":"Allowance '{}' created successfully".format(allowance_saved.AllowID)}) def put(self,request,pk): save_allowance = get_object_or_404(Allowance.objects.all(),pk=pk) data = request.data.get('allowance') serializer = AllowanceSerializer(instance=save_allowance,data=data,partial=True) if serializer.is_valid(raise_exception = True): allowance_saved=serializer.save() return Response({"sucess": "Allowance '{}' updated successfully".format(allowance_saved.AllowID)}) def delete(self,request,pk): #Get object with this pk allowance = get_object_or_404(Allowance.objects.all(),pk=pk) allowance.delete() return Response({"message":"Allowance with id '{}' has been deleted.".format(pk)},status=204) urls.py inside app => from django.conf.urls import url from .views import AllowanceAPIView urlpatterns = [ url(r'^$', AllowanceAPIView.as_view(), name='post-listcreate'), url(r'^(?P<pk>\d+)/$', AllowanceAPIView.as_view(), name='post-listcreate') ] urls.py inside project => from django.conf.urls import url, include from django.contrib import admin from rest_framework_jwt.views import obtain_jwt_token urlpatterns = [ url(r'^admin/', admin.site.urls), # url(r'^api/auth/login/$', obtain_jwt_token, name='api-login'), url(r'^api/allowances_mas/', include('tmswebapi.urls')), ] sample API request=> { "AllowID": "Allow1", … -
Raw query must include the primary key in custom posgresql function
i did this function with pg/sql languaje,for example: dinamico('some_string') and i am using this function in a simple django views: def detalle_fondo(request,fondo): det_fondos=f.objects.raw('select * from dinamico(%s)',[fondo]) return render(request,'sw/det-fondos.html',{'det_fondos':det_fondos}) the problem is django ask me for the primary key but i don now how to doit throught a custom function. Can you help me out? -
Django celery crontab every weekday between certain hours with 2 hour dela
Trying to achieve the title exactly. This is the crontab I have: 'schedule': crontab( minute='*/15', hour='9,10,11,12,13,14,15,16,17,18,19,20', day_of_week="1-5") Now, what I'm having trouble with is adding a 2 hour delay when scheduling. The idea is faking staff interaction for approvals. Person signs up I want to delay a task from the time they sign up to approve their account ~2 hours later but only run this between the weekdays during certain times (when staff would actually be working...) for a full "fake". So, any suggestions for the delay. To my understanding the tasks will just stall until they can be run by the beat schedule if someone signs up outside these hours, but I'm unclear how the delay works here. -
I have try to install pip install mysqlclient on mac give some error?
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/f4/f1/3bb6f64ca7a429729413e6556b7ba5976df06019a5245a43d36032f1061e/mysqlclient-1.4.2.post1.tar.gz ERROR: Complete output from command python setup.py egg_info: ERROR: sh: mysql_config: command not found Traceback (most recent call last): File "", line 1, in File "/private/var/folders/2b/1sy6xpk55qz87d1dx31qn92w0000gn/T/pip-install-ke4S5K/mysqlclient/setup.py", line 16, in metadata, options = get_config() File "setup_posix.py", line 51, in get_config libs = mysql_config("libs") File "setup_posix.py", line 29, in mysql_config raise EnvironmentError("%s not found" % (_mysql_config_path,)) EnvironmentError: mysql_config not found ---------------------------------------- ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/2b/1sy6xpk55qz87d1dx31qn92w0000gn/T/pip-install-ke4S5K/mysqlclient/ -
How to create a submit button for each field on a form that will create a model object and post it at the end of list in the view
I am trying to create submit buttons for each of the fields so when a user clicks the create button that is next to the field the input from that field will create a sub model object and that object will be placed at the end of the list on the same page under the correct main model object it was created for. I have tried using formsets but when using them my fields would go away so typing in any input was impossible. My most recent fix attempt was to try to manipulate the view to catch the id of the form but that was a fail. views.py def post(self,request,pk,context=context): rule_form = RuleForm(request.POST) arg_form = ArgumentForm(request.POST) if request.method=='POST' and 'RuleButton' in request.POST: if rule_form.is_valid(): print(rule_form.cleaned_data) Rule.rules.create_rule ( **rule_form.cleaned_data, Topic = context['topic'], created_by = context['user'], creation_date = context['creation_date'] ) TopicDetailView.get(self,request,pk,context=context) else: print(rule_form.errors) TopicDetailView.get(self,request,pk,context=context) elif request.method=='POST' and 'ArgButton' in request.POST: if arg_form.is_valid(): print(arg_form.cleaned_data) ruleList = [] for rule in context['topic_rules']: ruleList += [rule.id,] context['arg_rule'] = Rule.rules.all().get(id=rule.id) Argument.arguments.create_argument ( **arg_form.cleaned_data, created_by = context['user'], Rule = context['arg_rule'] ) TopicDetailView.get(self,request,pk,context=context) else: print(rule_form.errors) TopicDetailView.get(self,request,pk,context=context) return render(request,self.template_name, context=context) topic_detail.html <h1>{{ topic }}</h1> <p>Create a Rule</p> <form method="POST"> {% csrf_token %} {{ rule_form }} <input type="submit" name="RuleButton" … -
ValueError: invalid literal for int() with base 10: 'category'
I'm using python 3.7 django 2.2 django rest framework 3.9.4 After running: python manage.py migrate An error comes out: ValueError: invalid literal for int() with base 10: 'category' This is my model: class Category(models.Model): name = models.CharField(max_length=40, default='', verbose_name="类别名", help_text="类别名") # 分类名 class Meta: verbose_name = "分类" verbose_name_plural = verbose_name def __str__(self): return self.name class Article(models.Model): ...code... category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="cate", blank=True, verbose_name='分类', default='') ...code... class Meta: ordering = ['-add_time'] verbose_name = "新闻" verbose_name_plural = verbose_name def __str__(self): return self.title # 在后台中以文章标题显示 Any friend can help? -
DELETE request using fetch doesn't work in Safari, but works in Chrome
I want to send DELETE request from frontend (React) to backend (Django REST Framework) but it fails with very little info. It works ok in Chrome but fails in Safari. Also it works ok with GET and POST requests, the only thing is that POST requests works only on second attempt (only in Safari, again). I've tried different CORS configurations but no luck. Django CORS configuration: 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), } CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'localhost:3000', 'http://localhost:3000', ) CORS_TRUSTED_ORIGINS = ( 'localhost:3000', 'http://localhost:3000', '*' ) CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( '*', 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'access-control-allow-credentials', 'access-control-allow-headers', 'access-control-allow-methods', 'access-control-allow-origin', ) Frontend code: fetch('http://localhost:8000/api-v1/projects/'.concat(this.props.projectId), { method: 'DELETE', mode: 'cors', credentials: 'same-origin', body: {}, redirect: 'follow', referrer: 'no-referrer', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Access-Control-Allow-Headers': '*, Origin, X-Requested-With, Content-Type, Accept', 'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS', 'Access-Control-Allow-Credentials': true, 'Authorization': 'Basic ' + btoa('admin:pass'), },}).catch( e => console.error(e)); Django logs shows that DELETE request received and the response code is 301. Safari shows this in the console: [Error] The network connection was lost. [Error] Fetch API cannot load http://localhost:8000/api-v1/projects/54/ due to access control checks. [Error] Failed to load … -
How to get scheme from Django Response object?
I'm trying to determine whether a response is HTTP or HTTPS, but looking at dir(response) gives me no indication of such a possibility. I've looked at the Django docs here: https://docs.djangoproject.com/en/2.2/ref/request-response/ I'm trying to write a method to be called after each request. I would like to be able to call scheme on response, but obviously that is not possible. I want to achieve something like: def callback_after_request(self, response): if response.scheme == 'https': # do something to the headers How can I achieve this? -
Count more than one occurrence in a Django query
I have two models: Players and Tournaments. Players have also a type of game they play (dota, lol, magic, etc). They can participate in many tournaments at the same time (only once per Tournament). To manage the inscriptions, I use another model called TournamentMatch, that creates a new object for every inscription with the ID of the tournament and the player. I want to count the number of Players that have more than two inscription to tournaments and are, for example, dota players. I can easily achieve this with a for loop for every player, but for perfomance reasons, I want to achieve this using a Django query. For example, if I want to count the dota players that have one or more inscription, I will do: TournamentMatch.objects.filter( player__is_dota_player=True ).distinct( 'player' ).count() I'm sure is possible but I don't know how to count every ocurrence of distinct players on tournaments and only filter those that have more than one (and not only one). I will appreciate any help or pointers! -
What is proper way to link django-treebeard model with another django model as foreignkey?
I'm building a model which will show important facilities around stadium like depots,railway stations, hospitals, restaurants and bars etc and their distances. I've two models, one for Stadium and another for facilities around stadium. Facilities can be hierarchical if there are multiple options for the same. E.g. Stadium-1: -Hospital: - some hospital: 700 meters -Restaurant: - Chinese: - abc restaurant: 2km - Italian: - lmn restaurant: 300 meters - xyz restaurant: 1.2km The name of root node for each tree will be same as the name of stadium to which it'll be linked as foreign-key. Every stadium will have its own tree specifying important facilities around it and their distances from stadium. I am using Django-Treebeard for the purpose of creating facilities tree. My facilities model is MP_Node type. I'm using admin interface to add my data. When I try to link Stadium with facilities tree, it shows every node that was ever added in all tree models. This is messy. Imagine when data grows. It'll be a trouble. I've tried to link it as OneToOneField but nothing changed. class NearByFacilities(MP_Node): name = models.CharField(max_length=65, blank=True, null=True) distance = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) units = ( ('km', 'KiloMeters'), ('m', 'meters') ) … -
Parse a zip object using ast.literal_eval() or eval()
I have a zip object available in the Jinja template page, and when a user clicks some link I am sending that zip object as a request parameter. And then I try to parse the zip object using ast.literal_eval() but I am getting "Invalid syntax" error. I tried using eval() as literal_eval(). But both are giving me the same error. I searched for it but haven't found anything which describes how to parse a "" notation. data = request.GET movies,moviesindxs = zip(*literal_eval(data.get("movies"))) File "~/path/to/Django/app/views.py", line 198, in rate_movie movies, moviesindxs = zip(*literal_eval(data.get("movies"))) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py", line 48, in literal_eval node_or_string = parse(node_or_string, mode='eval') File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py", line 35, in parse return compile(source, filename, mode, PyCF_ONLY_AST) File "<unknown>", line 1 <zip object at 0x12d6549c8> -
How to filter integer timestamp field as choice of dates in django_filter
I have a working django-filter to filter later than a date, which is stored at the database level as an integer timestamp. Elsewhere I always represent that timestamp as a date in the template, but in the django_filter it shows the field value, which is a timestamp integer, of course. For example if my filter is: dispatch__gt = django_filters.NumberFilter(field_name='dispatch_time', lookup_expr='gt', label='Dispatched after') it would expect a timestamp input, which works fine but looks terrible. What I would like to do is have it display a choices filter based on a list of choices: newer than a year, newer than a month, newer than a week, etc. Can this be done with the django_filters.ChoiceFilter and a dynamically generated dictionary, or is there a better way? to be clear I am referring to this package: https://django-filter.readthedocs.io/en/master/index.html Thanks. -
How do I access the request params in order to authenticate an user
I would like to write a simple login form for my App. It is just a simple form, which sends data via post request to the django server. For authentification, I have to access the post request data, as mentioned in the django documentation but this doesn't work properly. This is my html form: <form method="POST" action="/login/">{% csrf_token %} <div class="form-group"> <label for="ID">User</label> <input type="text" class="form-control" id="ID" aria-describedby="User" placeholder="Username"> </div> <div class="form-group"> <label for="password">Passwort</label> <input type="password" class="form-control" id="password" laceholder="Passwort"> </div> <button type="submit" class="btn btn-primary">Einloggen</button> </form> This is my django code: def get_access(request): if request.method == 'POST': username = request.POST['ID'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) I get this Error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/login/ Django Version: 2.1.7 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'App', 'rest_framework', 'rest_framework.authtoken'] 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 "C:\Users\felix\DEV\my_env\lib\site-packages\django\utils\datastructures.py" in __getitem__ 77. list_ = super().__getitem__(key) During handling of the above exception ('ID'), another exception occurred: File "C:\Users\felix\DEV\my_env\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\felix\DEV\my_env\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\felix\DEV\my_env\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\felix\DEV\my_env\Animoo\App\views.py" in … -
int() argument must be a string, a bytes-like object or a number, not 'OrderItem'? Django
I am creating an E-commerce now when I try adding an Item into the cart it returns the error above? It is complaining about this line of code in the view: else: order.items.add(order_item) View def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item = OrderItem.objects.get_or_create( item=item, user = request.user, ordered = False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] #check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() else: order.items.add(order_item) else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, ordered_date=ordered_date) order.items.add(order_item) return redirect("core:product", slug=slug) Model class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.title}" class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add= True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username I need it to create a new item into the cart if it doesn't exist and if it exists inside the cart it increments the similar item by 1, instead of creating the same thing all over again. -
Django test setup fails when running single test file
The immediate symptoms: $ pytest …/apps/users/test/test_graph_permissions_command.py ============================= test session starts ============================== platform linux -- Python 3.6.8, pytest-4.6.2, py-1.8.0, pluggy-0.12.0 Django settings: dms.settings (from ini file) rootdir: /src/app, inifile: pytest.ini plugins: forked-1.0.2, celery-4.3.0, django-3.5.0, cov-2.7.1, xdist-1.28.0 collected 1 item …/apps/users/test/test_graph_permissions_command.py E ==================================== ERRORS ==================================== _ ERROR at setup of TestGraphPermissionsCommand.test_should_resolve_a_permission_hierarchy _ .venv/lib/python3.6/site-packages/pytest_django/plugin.py:519: in _django_setup_unittest request.getfixturevalue("django_db_setup") .venv/lib/python3.6/site-packages/pytest_django/fixtures.py:108: in django_db_setup **setup_databases_args .venv/lib/python3.6/site-packages/django/test/utils.py:174: in setup_databases serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True), .venv/lib/python3.6/site-packages/django/db/backends/base/creation.py:80: in create_test_db self.connection._test_serialized_contents = self.serialize_db_to_string() .venv/lib/python3.6/site-packages/django/db/backends/base/creation.py:123: in serialize_db_to_string serializers.serialize("json", get_objects(), indent=None, stream=out) .venv/lib/python3.6/site-packages/django/core/serializers/__init__.py:128: in serialize s.serialize(queryset, **options) .venv/lib/python3.6/site-packages/django/core/serializers/base.py:90: in serialize for count, obj in enumerate(queryset, start=1): .venv/lib/python3.6/site-packages/django/db/backends/base/creation.py:120: in get_objects yield from queryset.iterator() .venv/lib/python3.6/site-packages/django/db/models/query.py:341: in _iterator yield from self._iterable_class(self, chunked_fetch=use_chunked_fetch, chunk_size=chunk_size) .venv/lib/python3.6/site-packages/polymorphic/query.py:56: in _polymorphic_iterator o = next(base_iter) .venv/lib/python3.6/site-packages/django/db/models/query.py:55: in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) .venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:1087: in execute_sql sql, params = self.as_sql() .venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:474: in as_sql extra_select, order_by, group_by = self.pre_sql_setup() .venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:54: in pre_sql_setup self.setup_query() .venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:45: in setup_query self.select, self.klass_info, self.annotation_col_map = self.get_select() .venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:219: in get_select cols = self.get_default_columns() .venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:666: in get_default_columns column = field.get_col(alias) .venv/lib/python3.6/site-packages/django/db/models/fields/related.py:981: in get_col output_field = self.target_field .venv/lib/python3.6/site-packages/django/db/models/fields/related.py:878: in target_field return self.foreign_related_fields[0] .venv/lib/python3.6/site-packages/django/db/models/fields/related.py:632: in foreign_related_fields return tuple(rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field) .venv/lib/python3.6/site-packages/django/db/models/fields/related.py:619: in related_fields self._related_fields = self.resolve_related_fields() .venv/lib/python3.6/site-packages/django/db/models/fields/related.py:604: in resolve_related_fields raise ValueError('Related model %r cannot be resolved' % self.remote_field.model) E ValueError: … -
How to use PythonAnywhere SFTP to store uploaded files to get past file size limitations in Django Filer?
I am currently working on a Django website project in PythonAnywhere where users can upload files using Django Filer in the admin. I have successfully implemented it with the public Django filer settings. However, it seems I cannot upload files larger than 256 Mb. Is using the SFTP server provided to PythonAnywhere users an alternative way to store files? Or are there other ways to get past this size limitation? I am unsure how to write the server into my code. The SFTP address format and settings file for filer is provided below. SFTP Address and Hostname Format username@ssh.pythonanywhere.com filer.settings.py # -*- coding: utf-8 -*- from __future__ import absolute_import import logging import os from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.files.storage import get_storage_class from .utils.loader import load_object from .utils.recursive_dictionary import RecursiveDictionaryWithExcludes logger = logging.getLogger(__name__) # FILER_IMAGE_MODEL setting is used to swap Image model. # If such global setting does not exist, it will be created at this point (with default model name). # This is needed especially when using this setting in migrations. if not hasattr(settings, 'FILER_IMAGE_MODEL'): setattr(settings, 'FILER_IMAGE_MODEL', 'filer.Image') FILER_IMAGE_MODEL = settings.FILER_IMAGE_MODEL FILER_DEBUG = getattr(settings, 'FILER_DEBUG', False) # When True makes FILER_SUBJECT_LOCATION_IMAGE_DEBUG = getattr(settings, 'FILER_SUBJECT_LOCATION_IMAGE_DEBUG', False) FILER_WHITESPACE_COLOR … -
502 Bad Gateway: nginx - Log: upstream prematurely closed connection while reading... [Django 2.1 | gunicorn 19.7.1 | Google Cloud Platform]
I'm new in a company that have this project on Google Cloud PLatform, that I've never used. In my first day I've got this 502 Bad Gateway error. Lookin the log on the Google Cloud Platform I've got the following: [error] 33#33: *285 upstream prematurely closed connection while reading response header from upstream, client: 172.217.172.212, server: , request: "POST /product/fast_appraisal/result/ HTTP/1.1", upstream: "http://172.17.0.1:8080/product/fast_appraisal/result/", host: "avalieidjango.appspot.com", referrer: "https://avalieidjango.appspot.com/product/fast_appraisal/search/" I've tried to edit the app.yaml adding --timeout and --graceful-timeout parameters to it like the following: # [START runtime] runtime: python env: flex entrypoint: gunicorn -b :$PORT mysite.wsgi --timeout=90 --graceful-timeout=10 beta_settings: cloud_sql_instances: avalieidjango:southamerica-east1:avaliei runtime_config: python_version: 3 handlers: - url: /.* script: manage.py secure: always redirect_http_response_code: 301 # [END runtime] In the settings.py file DEBUG variable is setted to False Looking for answers on the internet I found a few cases, but no one looks like mine exactly. Locally I'm running the project on Windows 7, so the error only occurs when I deploy it to GCP. Since that I'm new on GCP and gunicorn, I would appreciate some advice to solve this issue that I'm stuck since June, 17th. Thanks in advance! -
How to display results from a database in a django web page?
I have a web page built in django that shows all rows of a sqlite table in bootstrap cards. Basically each card is a row of the table. I want to give the user the ability to filter these cards, so the page instead of showing every objects in the database's table should display only the objects relevant to the user. The result of the search can be displayed at another URL, it's irrelevant. I can build a html form to get info from the user and I can write a python function that search the database and print out specific rows based on an input keyword, but I can't make these things work together. Any hint or piece of code would be a great help, unfortunately I know nothing about php so if there's a way to do so without it would be great. Thanks all. # this is my view function, it shows all the objects in the table at a #specific URL def index_u(request): universities = University.objects.all() return render(request, 'index_uni.html', {'universities': universities}) /* this is index_uni.html */ {% block content %} <div class="row"> {% for university in universities %} <div class="col"> <div class="card" style="width: 18rem;"> <img src="{{ … -
Is there a way i can add a class or id to a form generated with UserCreationForm in CreateView
despite of the hours of struggle i am unable to bootstrap a django form created with UserCreationForm. i want to add bootstrap classes to the tag but due to my poor knowledge of django class based views i am unable to have a workaround. views.py class SignUp(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('accounts:login') template_name = 'accounts/signup.html' forms.py class CustomUserCreationForm(UserCreationForm): class Meta: fields = ('first_name', 'last_name', 'email', 'age', 'height', 'avatar', 'password1', 'password2') model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['password2'].label = "Confirm Password" Current Output enter image description here Output I want enter image description here -
Which would be the best way to convert a csv file to excel?
In order to become more familiar with django, I decided to build a website which is gonna let a user upload a csv file, which is then gonna be converted to excel and the user will be able to download it. In order to achieve that I created a modelform with one model FileField called csv_file as shown below: #models.py class CSVUpload(models.Model): csv_file = models.FileField(upload_to="csvupload/") def __str__(self): return self.csv_file #forms.py class CsvForm(forms.ModelForm): class Meta: model = CSVUpload fields = ('csv_file', ) and the corresponding view is: from django.shortcuts import render, redirect import pandas as pd import os #converts file from csv to excel def convertcsv2excel(filename): fpath = os.path.join(settings.MEDIA_ROOT + "\csvupload", filename) df = pd.read_csv(fpath) newfilename = str(filename) +".xlsx" newpathfile = os.path.join(settings.MEDIA_ROOT, newfilename) df.to_excel(newpathfile, encoding='utf-8', index=False) return newfilename def csvtoexcel(request): if request.method == 'POST': form = CsvForm(request.POST, request.FILES) if form.is_valid(): form.save() print(form.cleaned_data['csv_file'].name) convertcsv2excel(form.cleaned_data['csv_file'].name) return redirect('exceltocsv') else: form = CsvForm() return render(request, 'xmlconverter/csvtoexcel.html',{'form': form}) right now as you can see I am using Pandas in order to convert the csv file to excel inside the views.py file. My question is, is there a better way to do it (for instance in the form or model module) in order to make the excel … -
Selected options in Django variable
How to save the selected options from a multi select drop down in a Django variable as a list ? Is there anything to be imported from the .html to .py? -
Edit urls in wagtail (social-auth-app-django problems)
I want to add social-auth-app-django to my wagtail project to let normal users comment posts on blog. To make social-auth-app-django work, I need to add this urlpattern: urlpatterns = [ url(r'^auth/', include('social_django.urls', namespace='social')), ] How to do it? I didn't find any way to edit urls.py in wagtail, and I didn't find any social-auth-app-django wagtail equivalent.