Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sys.exit() in django web application
While debugging a django application codebase I came across some pieces of code as below: try: ...some business logic... except Exception as e: logging.exception(...) sys.exit() I am not able to understand how this web API would behave in case of an exception? Our web app has more than 1 worker which I understand, are modeled as differed processes by django. Per sys.exit documentation, the process will only exit if called from the main thread. How would this behave when there are multiple workers and the workers spawn multiple threads? Does django replace the worker process with another process if the worker's main thread encountered sys.exit and the worker process was shut down? Is it even a good idea to have sys.exit in an exception block or anywhere in the app for that matter? -
Always empty aggregations django elasticsearch
I use django-elasticsearch-dsl and I have the problem that aggregations always return empty value to me. I need all the different publishers and the different authors of the search results. Document: @registry.register_document class BookDocument(Document): author = fields.ObjectField(properties={ 'name': fields.TextField(), 'name_reverse': fields.TextField(), 'pk': fields.IntegerField(), 'slug': fields.TextField(), }) editorial = fields.NestedField(properties={ 'name': fields.TextField(), 'slug': fields.TextField(), 'pk': fields.IntegerField(), }, include_in_root=True) class Index: name = 'books' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Book fields = [ 'title', 'isbn', ] related_models = [Author, Editorial] # para asegurarnos que cuando se actualice un author, se reindexa los libros def get_queryset(self): """Not mandatory but to improve performance we can select related in one sql request""" return super(BookDocument, self).get_queryset().select_related( 'author', 'editorial' ) def get_instances_from_related(self, related_instance): """If related_models is set, define how to retrieve the Book instance(s) from the related model. The related_models option should be used with caution because it can lead in the index to the updating of a lot of items. """ if isinstance(related_instance, Author): return related_instance.book_set.all() elif isinstance(related_instance, Editorial): return related_instance.book_set.all() Search: from elasticsearch import Elasticsearch from elasticsearch_dsl import Search from elasticsearch_dsl import Q from elasticsearch_dsl.query import MultiMatch, Match from elasticsearch_dsl import A s = Search(index='books') s = s.query("match", title="SECRET") s … -
Starting a django application during the unit test
I'm currently using python 2.7, django 1.6.5 and running unit tests on API files. Below is the file from which I'm trying to run all the unit test files Integration.py loader= unittest.TestLoader() start_dir='tp/pyfiles' suite=loader.discover(start_dir) runner = unittest.TextTestRunner() runner.run(suite) Below is the part of the code I've written for API testing test_file1.py class api_test(unittesting.TestCase): def setUp(self): print "SetUp Function called" command = 'gnome -terminal -e \'python manage.py runserver ' + 1585 + '\'' try: os.system(command) print "SetUp Done" except Exception as e: print e Is there is any other way to start the server rather than the above-mentioned command ?? Also, what is the correct way to run integration.py? 1.python -m unittest integration or 2.python integration.py If I'm running with the first one, I'm getting Ran 4 Tests OK Ran 0 Tests Ok else Ran 4 Tests OK Please suggest -
My view function is added to url on return render. How can I avoid this?
When a user does not fill in all information, they should be sent back to http://127.0.0.1:8000/content/readerpage/40, but instead they are sent to http://127.0.0.1:8000/content/readerpage/40/add_review How can I avoid this? def add_review(request, content_id): content = get_object_or_404(Content, pk=content_id) if request.POST['readability'] and request.POST['readability_rating'] and request.POST['actionability'] and request.POST['actionability_rating'] and request.POST['general_comments']: review = Review() review.readability = request.POST['readability'] review.readability_rating = request.POST['readability_rating'] review.actionability = request.POST['actionability'] review.actionability_rating = request.POST['actionability_rating'] review.general_comments = request.POST['general_comments'] review.save() return redirect('home') else: return render(request, 'content/readerpage.html', {'error': 'You need to fill in all information'}) urlpatterns = [ path('', views.home, name='home'), path('add/', views.add, name='add'), path('<int:content_id>', views.details, name='details'), path('link/<int:content_id>', views.link, name='link'), path('readerpage/<int:content_id>', views.readerpage, name='readerpage'), path('readerpage/<int:content_id>/add_review', views.add_review, name='add_review'), ] Thanks for reading this. -
How to filter/get second to last most recent record to update a field in Django?
I have a model that keeps track of enter/leave times. I am trying to add constraints to make the data more accurate. Currently, when someone "Enters", it creates a record, saves the time in timestamp and then redirects. If the person then tries to enter again, it creates a new record with a new timestamp. What I'm trying to add now is that, if the person has a previous entry without an exit timestamp then that record (which would be the second to last most recent entry), would be flagged by updating the time_exceptions field to 'N'. Currently, it changes all the fields to 'N', regardless of whether there's an exit or not, as shown below. class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in self.request.POST: form.save() EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now()) if EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num)).count() > 1: EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_exceptions='N') return HttpResponseRedirect(self.request.path_info) I tried the following, but I get a expected string or bytes-like object and while it still creates a new record before crashing, it does not update the time_exceptions of … -
Defined variable,says there is not 'n1',key
MultiValueDictKeyError at /home/ 'n1' Request Method: GET Request URL: http://127.0.0.1:8000/home/ Django Version: 2.2.6 Exception Type: MultiValueDictKeyError Exception Value: 'n1' Exception Location: /home/sanzu/anaconda3/lib/python3.7/site-packages/django/utils/datastructures.py in __getitem__, line 80 Python Executable: /home/sanzu/anaconda3/bin/python Python Version: 3.7.3 Python Path: ['/home/sanzu/PycharmProjects/django_site', '/home/sanzu/anaconda3/lib/python37.zip', '/home/sanzu/anaconda3/lib/python3.7', '/home/sanzu/anaconda3/lib/python3.7/lib-dynload', '/home/sanzu/anaconda3/lib/python3.7/site-packages'] Server time: Mon, 4 Nov 2019 18:29:40 +0000 Traceback Switch to copy-and-paste view /home/sanzu/anaconda3/lib/python3.7/site-packages/django/utils/datastructures.py in __getitem__ list_ = super().__getitem__(key) … ▼ Local vars Variable Value __class__ <class 'django.utils.datastructures.MultiValueDict'> key 'n1' self <QueryDict: {}> During handling of the above exception ('n1'), another exception occurred: /home/sanzu/anaconda3/lib/python3.7/site-packages/django/core/handlers/exception.py in inner response = get_response(request) … ▼ Local vars Variable Value exc MultiValueDictKeyError('n1') get_response <bound method BaseHandler._get_response of <django.core.handlers.wsgi.WSGIHandler object at 0x7f2e177ac208>> request <WSGIRequest: GET '/home/'> /home/sanzu/anaconda3/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▼ Local vars Variable Value callback <function page at 0x7f2e16974048> callback_args () callback_kwargs {} middleware_method <bound method CsrfViewMiddleware.process_view of <django.middleware.csrf.CsrfViewMiddleware object at 0x7f2e1687c080>> request <WSGIRequest: GET '/home/'> resolver <URLResolver 'django_site.urls' (None:None) '^/'> resolver_match ResolverMatch(func=san.views.page, args=(), kwargs={}, url_name=None, app_names=[], namespaces=[], route=home/) response None self <django.core.handlers.wsgi.WSGIHandler object at 0x7f2e177ac208> wrapped_callback <function page at 0x7f2e16974048> /home/sanzu/anaconda3/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▼ Local vars Variable Value callback <function page at 0x7f2e16974048> callback_args () callback_kwargs {} middleware_method <bound method CsrfViewMiddleware.process_view of <django.middleware.csrf.CsrfViewMiddleware object at … -
How do I display the result on the current page? Django, Ajax
On the main page I have a text box. When I type text into it, after clicking the button I want to display that text below. With ajax I get the text entered and pass it to views.py. When rendering, the result I need is displayed on /localhost:8000/vk_u/ How do I display the result on the current page (localhost: 8000/)? Thanks //forms.py from django import forms from .models import * class VK_LINK_Form(forms.Form): enter_link = forms.CharField(widget = forms.TextInput(attrs={'id':'link_vk_enter'})) //urls.py from django.urls import path, include from . import views from django.http import HttpResponse urlpatterns = [ path('', views.index, name = 'index'), path('vk_u/', views.vk_u, name = 'vk_u'), ] //js $(document).on('submit','#vkht_form', function(e){ e.preventDefault(); var link_post_input = $(document.getElementById("link_vk_enter")).val() $.ajax({ type: 'POST', url: '/vk_u/', data:{ link_post_input: link_post_input, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, }); }); ] //views.py def vk_u(request): link_post_input = request.POST.get('link_post_input') return render(request, "mainApp/homePage.html", {"link_post_input": link_post_input,}) <!-- html --> <body> <div> <form action="" method="GET" id="vkht_form"> {% csrf_token %} {{ form }} text: {{ text_post_input }} <input type="submit" value="CLICK"> </form> </div> </body> -
Django giving 500 instead of 404 for unknown URLs when debug is false
Django = 2.1.x Python = 3.7.x If Debug is True - it returns a 404. If Debug is False - it gives a 500 error. My project.urls file looks like this: urlpatterns = [ path("admin/", admin.site.urls), path("", app1.views.log_in, name="log_in"), path("log_in/", app1.views.log_in, name="log_in"), path("logout/", app1.views.log_out, name="logout"), path("launcher/", app1.views.launcher, name="launcher"), path("app2/", include("app2.urls")), path("app3/", include("app3.urls")), ] My directory structure looks like this: Project_directory static_directory ...js files and css files and such... templates_directory 400.html 403.html 404.html 500.html base.html (all apps extend this page, which works great) project_directory urls.py settings.py ...other files... app1_directory views.py models.py templates_directory app1 ...template files... ...other app1 files/directories... app2_directory ...app2 directories and files... app3_directory ...app3 directories and files... When I python manage.py runserver and I hit a URL I know doesn't exist (like http://project/randomtrash.php) it gives an appropriate 404 if DEBUG = True If DEBUG = False then hitting that same URL will give a 500 and the 500.html displays. Important parts of my settings.py look like this: # These two settings are only for testing purposes and are different # In production DEBUG = False ALLOWED_HOSTS = ["*"] ROOT_URLCONF = "project.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", # DIRS lets the apps extend base.html "DIRS": [os.path.join(BASE_DIR, "templates")], "APP_DIRS": True, "OPTIONS": … -
Multiple Apps in play , something similar to multiple apps in django
In Django we can develop multiple apps(own models, view etc) grouped logically with same database and common setting files but different uri. Is there something similar in play. e.g in django we can have two apps books and author with apis like abc.com/v1/book/1, abc/com/v1/author/peter -
Import Statements Inside Functions in Python
I have been trying to solve (in my own way) the problem of making configurations sane and 12-factor compliant for a Django app I am working on. The following was my idea. As you can see, I wanted to fully isolate the specification of environment to, well, environment. Prior to this, I had to re-specify the entry-level settings file inside the manage.py for each new environment, despite already having separate settings files for each environment. settings.py (to which manage.py would point) import environ env = environ.Env() environ.Env.read_env() DJANGO_ENV = env('DJANGO_ENV') def production(): import production def development(): from .development import * def testing(): import testing def staging(): import staging options = {'production': production, 'development': development, 'testing': testing, 'staging': staging} print(options[DJANGO_ENV]()) However, I got complaints (errors) from Python 3.7 that import statements are only allowed at the module level. My question is two-fold: how sane is this approach overall and is there a way to do imports at the function level? -
Is there any advantage on using jwt vs knox on django rest framework
Planning to implement token authentication but I am not sure which one to use -
How to dynamically set value to MoneyField in djmoney?
Currently i am using djmoney to store money info in my database. Right now i need to manually set values in my form, so i use class MyForm(forms.Form): money = MoneyField() ... def view(request): form = MyForm(initial={ 'money' : Money(0.5, 'USD')}) But that's not working, because, as I later found out, MoneyField uses default_amount and default_currency kwargs to set it. But how do i set the form field dynamically? -
Why are my Django model images not being output
Here is my code views.py def search(request): if request.method == 'GET': try: q = request.GET.get('search_box', None) posts = Listing.objects.filter(title__contains=q, is_live=1) | \ Listing.objects.filter(street_address__contains=q, is_live=1) | \ Listing.objects.filter(city__contains=q, is_live=1) | \ Listing.objects.filter(state=q, is_live=1) | \ Listing.objects.filter(property_class__contains=q, is_live=1) | \ Listing.objects.filter(sale_or_lease__contains=q, is_live=1) return render_to_response('search/results.html', {'posts': posts, 'q': q}) except KeyError: return redirect('home') results.html: <div class="container" style="width:20%; float:right; text-align:center; overflow:auto;"> {% for Listing in posts %} <a href="{% url 'post_view' Listing.pk %}"><img style="width: 384px; height: 216px;" alt="Thumbnail" src="{{ MEDIA_URL }}{{ Listing.thumbnail }}"/></a> <p style="color:black;">{{ Listing.title }}</p> <p style="color:black;">Sale or Lease: {{ Listing.sale_or_lease }}</p> <p style="color:black;">Class: {{ Listing.property_class }}</p> <p style="color:black;">Square Feet: {{ Listing.square_feet }}</p> {% if Listing.price %} <p style="color:black;">Price: ${{ Listing.price|linebreaksbr }}</p> {% endif %} {% if Listing.price_per_square_foot_per_year %} <p style="color:black;">Price per SqFt/yr: ${{ Listing.price_per_square_foot_per_year|linebreaksbr }}</p> {% endif %} <p style="color:black;"> City: {{ Listing.city }}, {{ Listing.state }}</p> <hr> {% endfor %} </div> For the above code, Listing.thumbnail is not being output, only the placeholder text is. Here is an example of code I have that is working. views.py def preview(request, pk): posts = Listing.objects.all().filter(is_live=1) preview = get_object_or_404(Listing, pk=pk) attorneys = Attorneys.objects.all().filter(state=preview.state) | \ Attorneys.objects.all().filter(city=preview.city) lenders = Lenders.objects.all().filter(state=preview.state) | \ Lenders.objects.all().filter(city=preview.city) developers = Developers.objects.all().filter(state=preview.state) | \ Developers.objects.all().filter(city=preview.city) context = {'posts': posts, 'preview': … -
AttributeError: module 'socket' has no attribute 'AF_UNIX' when connecting google cloud store with django
I am connecting google cloudstore mysql with django using official documentation on app engine environment, given as: https://cloud.google.com/python/django/appengine Firstly, I got the error that mysqlclient 1.3.13 or newer is required. To resolve this issue, I used the solution given on Django - installing mysqlclient error: mysqlclient 1.3.13 or newer is required; you have 0.9.3, but when I do this it gives me the error "AttributeError: module 'socket' has no attribute 'AFX_UNIT'". -
How can i add more table fields on already developed Django User table Database
I want to add more fields in User Data table so Please Explain the right method to done this. -
Django forms : Edit image field (delete and show existing)
I am trying to have a Django Model form with an image field but I have the two problems: I don't know how to show the current name of the image in the input I don't know how to provide a way to remove the image forms: class CityLogoForm(forms.ModelForm): logo = forms.ImageField(widget=forms.FileInput(attrs={'class': 'custom-file-input'}), required=False) class Meta: model = City fields = ['logo'] views: def management_form_general(request, city_slug): city = City.objects.get(slug=city_slug) if request.method == 'POST': logo_form = CityLogoForm(request.POST, request.FILES, instance=city) if logo_form.is_valid(): logo_form.save() else: logo_form = CityLogoForm(instance=city) return render(request, 'management/form/city_general.html', {'city': city, 'logo_form': logo_form}) html: <form action="" enctype="multipart/form-data" method="post"> <div class="form-group row"> <label for="id_city" class="col-sm-2 col-form-label form_title">{{ logo_form.logo.label }}</label> <div class="custom-file"> {{ logo_form.logo }} <label class="custom-file-label" for="{{ logo_form.logo.id_for_label }}" data-browse="Choisir Image">{{ logo_form.logo.label }}</label> </div> </div> </form> I have a script changing the label when the user is uploading something but I cannot find a way to get the current value for the image fields (for the normal ones it's properly prepopulated). As it seems to not prepopulate the input, it seems to be ignoring when the input is empty and therefore never deletes the current logo. -
Django template inheritance // how to use multiple css files?
I would like to find a solution to have multiple CSS files for different templates using Django template inheritance. So far I could extend my base.html template with another apps template. Now I would like to use a seperate css files for the apps html templates (one app = 1x html, 1x js, 1x css). But when I include the template into the template tag it replaces the css file from the base.html and crashes the site. How can someone implement a second css file into a extended html template that only refers to the extended part and doesn't "touch" the base.html? Thank you for your guidance in advance. extended html template which crashes site because of replacement of base.css file: {% extends 'templates/base.html' %} {% load static %} {% block head_css_site %} <link href="{% static 'Quotes_app.css' %}" rel="stylesheet" type="text/css"> {% endblock head_css_site %} {% block content %} <h1>Test</h1> {% endblock %} {% block footer_javascript_site %} <script src="{% static 'Quotes_app.js' %}"></script> {% endblock footer_javascript_site %} base.html: {# HTML5 declaration #} <!DOCTYPE html> {% load static %} <html> {# Make modifiable head elements #} <head> <title>{% block title %} {% endblock title %} DASHEX </title> {% block head_favicon %} <link rel="icon" … -
getting error while installing psycopg2 in vscode on windows
I am trying the following command in vscode cmd on windows 8.1 pip install psycopg2 error I am getting after using the above command: ERROR: Command errored out with exit status 1: command: 'c:\users\rock\envs\demo\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\rock\\AppData\\Local\\Temp\\pip-install-fczxt3cu\\psycopg2\\setup.py'"'"'; __file__='"'"'C:\\Users\\rock\\AppData\\Local\\Temp\\pip-install-fczxt3cu\\psycopg2\\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 'C:\Users\rock\AppData\Local\Temp\pip-wheel-i_fkxw14' --python-tag cp38 cwd: C:\Users\rock\AppData\Local\Temp\pip-install-fczxt3cu\psycopg2\ Complete output (22 lines): running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.8 creating build\lib.win-amd64-3.8\psycopg2 copying lib\compat.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\errorcodes.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\errors.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\extensions.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\extras.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\pool.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\sql.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\tz.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\_ipaddress.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\_json.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\_lru_cache.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\_range.py -> build\lib.win-amd64-3.8\psycopg2 copying lib\__init__.py -> build\lib.win-amd64-3.8\psycopg2 running build_ext building 'psycopg2._psycopg' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ -
How to properly render a field from a database in a page without refreshing?
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page, for example, they enter their # and then after they click/tab onto the next field, it renders the name on top, so the user knows they've entered the correct info. This name is also stored in a separate model, so I try to retrieve it using the "id/number". I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered. models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False) station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.employee_number This is the model where the name is stored alldata/models.py class Salesman(models.Model): slsmn_name = models.CharField(max_length=25) id = models.IntegerField(db_column='number', primary_key=True) forms.py class WarehouseForm(AppsModelForm): class Meta: model = … -
How to subclass Media to override render_js method?
How to create Media class with custom render in Django 2.X? I want to render widget with custom js module (script type is not text/javascript as in parent Media class) class TypedScriptMedia(forms.widgets.Media): def render_js(self): # This never got called, instead parent method will be called return [format_html( f'<script type="{script_type}" src="{script_path}"></script>', self.absolute_path(script_path) ) for script_type, script_path in self._js] class CustomWidget(forms.Widget): template_name = 'geo/widgets/display_map.html' # media = TypedScriptMedia( # js=( # ('module', 'module.js'), # ( # 'text/javascript', # 'https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/2.3.0/' # 'webcomponents-bundle.js' # ) # ) # ) # class Media(TypedScriptMedia): # extend = False # js = ( # ('module', 'module.js'), # ( # 'text/javascript', # 'https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/2.3.0/' # 'webcomponents-bundle.js' # ) # ) # @property # def media(self): # return TypedScriptMedia(js=( # ('module', 'module.js'), # ( # 'text/javascript', # 'https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/2.3.0/' # 'webcomponents-bundle.js' # ) # ) # ) @property def media(self): # this is called media = super().media media += TypedScriptMedia( js=( ('module', 'module.js'), ( 'text/javascript', 'https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/2.3.0/' 'webcomponents-bundle.js' ) ) ) return media All commented code has no effect I also tried creating custom Media class like: class ModuleScriptMedia(forms.widgets.Media): def __init__(self, *args, modules: Optional[Tuple[str, ...]] = None, **kwargs): super().__init__(*args, **kwargs) if not modules: modules = [] self._modules_lists = [modules] @property def _modules(self): … -
redirect() not passing arguments to view Django
I'm having trouble with redirect() in my Django views. I have two views defined as follows: # view for managing a user's account @login_required @require_http_methods(['GET']) def view_account(request, updated=False): context = { 'user': request.user, 'cart_items': ShoppingCartItem.objects.filter(user_key=request.user), 'updated': updated, } print("DEBUG: view_account: %s" % updated) # debug return render(request, 'registration/view_account.html', context) and # view for updating information about a user's account @login_required @require_http_methods(['GET', 'POST']) def update_account_info(request): if request.method == 'POST': # if this is a POST, user has submitted updated information form = UpdateUserInfoForm(request.POST, instance=request.user) if form.is_valid(): # if valid, redirect to view_account form.save() # return render(request, 'registration/view_account.html', context) return redirect('/view_account', updated=True) My url's for these functions look like so: path('view_account', views.view_account, name='view_account'), path('update_account', views.update_account_info, name='update_account'), In the second function, I'm trying to redirect the user to the view_account() view and pass in the updated=True argument to notify the user on the page that their information has been updated. For some reason when I run this, it does not seem to be changing the default value of updated. As you can see, I've got a debug statement in the view_account() view. Output is as follows: [04/Nov/2019 16:51:33] "POST /update_account HTTP/1.1" 302 0 DEBUG: view_account: False [04/Nov/2019 16:51:33] "GET /view_account HTTP/1.1" 200 1247 … -
Django error (1054, "Unknown column 'models_author.user' in 'field list'")
good In models.py I changed the name of the field "login" to "user" and added others. Even having executed: Python3 manage.py makemigrations models python3 manage.py sqlmigrate models 0001 python3 manage.py migrate I still get an error (1054, "Unknown column 'models_author.user' in 'field list'"). If I change the field back to "login" it works perfectly Versions Python 3.5.2 django.VERSION (2, 2, 6, "final", 0) the database is in MYSQL. Code:Models.py class Autor(models.Model): nombre = models.CharField(max_length=30) apellidos = models.CharField(max_length=50) usuario=models.CharField(max_length=50) class Post(models.Model): author = models.ForeignKey('auth.User', ) titulo = models.CharField(max_length=100) comentario = models.CharField(max_length=1000) Regards -
How to sanity check if public ssh key passed from html form is valid?
Im using django to create website and want sanity check ssh keys. The user enters a public ssh key in a html form to add it to his account for later use. Before saving the key I want to check if the public key is valid, i.e. the string passed has the correct form etc. to be a real ssh key. There are some similar questions I found like this: https://serverfault.com/questions/453296/how-do-i-validate-an-rsa-ssh-public-key-file-id-rsa-pub But they use ssh-keygen, which needs a saved file to read from. What would be a more elegant way to implement this in python? -
How to choose model fields to be displayed in the generic ListView
I would like to create a table using some of the model fields names. As you can see below, model has defined 8 fields but I just want to display on the table 3 of them. After you click on the contractor name in the table you will be forward to the detail view where you will see all the models fields. I don't want to hardcode the table column names. So how can I display only these 3 model fields in the table? views.py class ListView(generic.ListView): model = Contractor template_name = 'contractors/list.html' context_object_name = "all_contractors" fields = ['company_name', 'email', 'website'] models.py class Contractor(models.Model): company_name = models.CharField(max_length=200) phone_number = models.CharField(max_length=50) email = models.EmailField() website = models.URLField() city = models.CharField(max_length=100) street = models.CharField(max_length=100) postal_code = models.CharField(max_length=50) notes = models.TextField() def __str__(self): return self.company_name -
Nginx not service static file in django project
In django project I used Js and Css files and this files not downloading. after installation to server nginx is not service django static files, but it service pictures. Web site is working but style and js files not service, why it happen which component not working? Nginx file: location /static/ { alias /var/www/project.com/project/static/; } location /media/ { alias /var/www/project.com/project/media/; } Setting.py file: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static') ] MEDIA_URL = 'media/' MEDIAFILES_DIR = [os.path.join(BASE_DIR, 'media') ] Index.html file: <script type="text/javascript" src="{% static 'js/functions.js'%}"> </script> When I checked by browser console, it give me like this error: http://someurl/static/js/functions.js net::ERR_ABORTED 403 (Forbidden)