Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
source-detail error Django
We are running into this issue on tables that have foreign key constraints. For the table creating this issue, we copied the table data exactly with no constraints, just the data to a new table and everything worked fine. However, we want to use the table with the relationships and real constraints. Our models.py class NewsSerialiser(serializers.HyperlinkedModelSerializer): class Meta: model = News fields = ('news_id', 'news_source', 'news_title', 'news_description', 'news_publication_date', 'news_link') class NewsViewSet(viewsets.ModelViewSet): queryset = News.objects.all() serializer_class = NewsSerialiser Our URlS.py from django.conf.urls import url, include from django.contrib import admin from rest_framework import routers from note.note_api import NewsViewSet # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r'notes', NewsViewSet, 'news') urlpatterns = router.urls The issue: Could not resolve URL for hyperlinked relationship using view name "source-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. This error seems to be persistent on tables with foreign key constraints. Any advice or support is greatly appreciated. -
Number of queries executed over psycopg2 connection
I would like to know the number of sql queries which were executed on a psycopg2 connection. Is there a way to get this number? I would like to warn if a http request produces too many statements. I am running a django application. If DEBUG is True, then I have connection.queries. But I would like to get this value from a production server -
Reverse for 'favorite' with arguments '('',)' not found, following Bucky's Django tutorial on YouTube
I keep getting NoReverseMatch at /music/2/ error, and it's pointing me to the parent template that i'm inheriting from, base.html, but i can't find anything wrong with it. I know it's probably annoying when someone asks you to search for errors, but maybe someone can easily see what i'm unable to see {% extends "music/base.html" %} {% block content %} <p> Album : {{one_album}} </p> <p> Song list : </p> {% if somethings_wrong %} <p> {{ somethings_wrong }} </p> {% endif %} <form action = "{% url 'music:favorite' album.id %}" method="post" > {% csrf_token %} {% for song in album_entries %} <input type="radio" id="song{{forloop.counter}}" name="song" value="{{ song.id }}"> <label for="song{{ forloop.counter }}"> {{ song.song_title }} {% if song.is_favorite %} #afterwards, set this explicitly to true, for learning purposes <img src="https://i.imgur.com/olM72b8.png"/> #check if this slash is necessary later {% endif %} </label><br> {% endfor %} <input type="submit" value="Favorite"> </form> {% endblock content %} Here's the base.html <p> <a href="{% url 'music:index' %}"> Link to the homepage </a> </p> {% block content %} {% endblock content %} Here's the Views.py : from django.shortcuts import render from django.http import HttpResponse from .models import Album, Song def index(request): albums = Album.objects.all() context = {'albums': … -
AttributeError: 'NoneType' object has no attribute 'startswith' while makemigrations with manage.py in django
I am using Django 1.9.13 with python 2.7.5 When i make migrations i get below error. I checked the database settings, all fine working with other app. I couldn't figure out the solution. I am using mysql DB at the backend. I am using one app that is carried from test environment. Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/root/projects/misque/lib/python2.7/site- packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/root/projects/misque/lib/python2.7/site-p Packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/projects/misque/lib/python2.7/site- packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/root/projects/misque/lib/python2.7/site- packages/django/core/management/base.py", line 398, in execute self.check() File "/root/projects/misque/lib/python2.7/site- packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/root/projects/misque/lib/python2.7/site- packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/root/projects/misque/lib/python2.7/site- packages/django/core/checks/model_checks.py", line 28, in check_all_models errors.extend(model.check(**kwargs)) File "/root/projects/misque/lib/python2.7/site- packages/django/db/models/base.py", line 1178, in check errors.extend(cls._check_fields(**kwargs)) File "/root/projects/misque/lib/python2.7/site- packages/django/db/models/base.py", line 1255, in _check_fields errors.extend(field.check(**kwargs)) File "/root/projects/misque/lib/python2.7/site- packages/django/db/models/fields/__init__.py", line 925, in check errors = super(AutoField, self).check(**kwargs) File "/root/projects/misque/lib/python2.7/site- packages/django/db/models/fields/__init__.py", line 208, in check errors.extend(self._check_backend_specific_checks(**kwargs)) File "/root/projects/misque/lib/python2.7/site- packages/django/db/models/fields/__init__.py", line 317, in _check_backend_specific_checks return connections[db].validation.check_field(self, **kwargs) File "/root/projects/misque/lib/python2.7/site- packages/django/db/backends/mysql/validation.py", line 18, in check_field field_type = field.db_type(connection) File "/root/projects/misque/lib/python2.7/site- packages/django/db/models/fields/__init__.py", line 625, in db_type return connection.data_types[self.get_internal_type()] % data File "/root/projects/misque/lib/python2.7/site- packages/django/db/__init__.py", line 36, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File … -
How to add custom object-tool that populates Tabular Inline fields in Django Admin?
So far i've extend object-tool block and created my own custom but dont have an action yet. {% extends "admin/change_form.html" %} {% block object-tools-items %} <li> <a href="<your-action-url>"class="historylink">ComputeDepreciation</a> </li> {{ block.super }} {% endblock %} Here is my models.py have two models. Depreciation foreignkey to Asset # models.py class Asset(models.Model): gross_value = models.FloatField() salvage_value = models.FloatField() life = models.IntegerField() class Depreciation(models.Model): asset_id = models.ForeignKey('Asset',on_delete=models.SET_NULL, null=True,) depreciation_value = models.CharField(verbose_name='Depreciation Value',max_length=255,) annual_depreciation = models.CharField(verbose_name='Annual Depreciation',max_length=255,) Here is my admin.py # admin.py class AssetDepreciationInline(admin.TabularInline): model = Depreciation extra = 0 class AssetAdmin(admin.ModelAdmin): inlines = [AssetDepreciationInline] I'd like to populate the Depreciation fields using custom object-tool. Please help, thanks. -
Django tests not validating null=False constraint
I have a model with various fields. One of them is a CharField field = models.CharField(max_length=100, blank=False, null=False) Now when I create an object without this field in django tests class function 'setUpTestData', it doesnt give any error. If I add minLengthValidator to it then too it doesn't give any models.CharField(blank=False, null=False, max_length=100, validators=[MinLengthValidator(1)]) When I print it after the object is created it gives an empty string. I have another field: field2 = models.DateTimeField(blank=False, null=False) Now if I dont provide this data while creating the object, the test fails correctly. -
Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it
while installing anything through pip i m getting this error , Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it. I was installing django through pip command i.e pip install django and i got this error : Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x04135910>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))': /simple/django/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x04135850>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))': /simple/django/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x04135930>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))': /simple/django/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x04135770>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine … -
Is this csrf failure expected?
Given the following series of events anonymous user opens home page, which contains a form (with a valid csrf token) the user opens a secondary tab and logs in. the user returns to the original tab and submits the form. Is the resulting csrf failure expected, and if so, are there any solutions that will give the user a better experience? -
Connect Celery (Django) to RabbitMQ using SSL/TLS
This question is related to 49320158, I'll try to provide more details. I am trying to follow the tutorial First Step with Django but I need to add TLS/SSL to be able to connect to my RabbitMQ server v3.7.4. I have tested my certificates with pika 11.2 and I am able to connect. But celery is not able to connect, and rabbitmq says 'no peer certificate'. How do I specify or make sure that celery sends out the certificates? My settings.py celery settings only (django): # celery settings SSL_DIR = os.path.normpath(os.path.join(BASE_DIR, '../../ssl/client')) CELERY_BROKER_USE_SSL = { 'keyfile': SSL_DIR + '/user-key.pem', 'certfile': SSL_DIR + '/user-cert.pem', 'ca_certs': SSL_DIR + '/default_cacert.pem', 'cert_reqs': ssl.CERT_REQUIRED } CELERY_BROKER_LOGIN_METHOD = "EXTERNAL" CELERY_BROKER_URL = 'amqps://user@rabbitmqserver/vhost' My celery.py: from __future__ import absolute_import, unicode_literals import os import ssl from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webui.settings') app = Celery('webui') app.config_from_object('django.conf:settings', silent=False, force=True, namespace='CELERY') PROJ_DIR = os.path.dirname(os.path.dirname(__file__)) BASE_DIR = os.path.normpath(os.path.join(PROJ_DIR, '../../ssl/client')) cert_conf = { "ca_certs": BASE_DIR + "default-cacert.pem", "certfile": BASE_DIR + "bkmk_user-cert.pem", "keyfile": BASE_DIR + "bkmk_user-key.pem", "cert_reqs": ssl.CERT_REQUIRED } # try manually setting the BROKER_USE_SSL app.conf.update(BROKER_USE_SSL=cert_conf) # try enabling message signing, too app.conf.update( security_key=BASE_DIR+'bkmk_user-key.pm', security_certificate=BASE_DIR+'bkmk_user-cert.pem', security_cert_store=BASE_DIR+'*.pem', ) app.setup_security() # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) … -
Django, one file but field is several, How to save it?
forms.py: class TestPicForm(forms.ModelForm): x = forms.FloatField(widget=forms.HiddenInput()) class Meta: from .models import TestPic model = TestPic fields = ('file', 'file_50', 'x', ) def save(self): user_photo = super(TestPicForm, self).save() x = self.cleaned_data.get('x') image = Image.open(user_photo.file) # image_50 = Image.open(user_photo.file_50) cropped_image = image.crop((x, 2x, x + 10, y + 10)).resize((300, 300), Image.ANTIALIAS) cropped_50_image = image.crop((x, 2x, x + 50, y + 50)).resize((10, 150), Image.ANTIALIAS) cropped_image.save(user_photo.file.path) cropped_50_image.save(user_photo.file_50.path) return user_photo I asked abstract question before, But now I can make a question more concretely. On this code, I uploads only one file but save it into several fields.(in this case, file, file_50) models.py: class TestPic(models.Model): file = models.ImageField(null=True, blank=True, default=None) file_50 = models.ImageField(null=True, blank=True, default=None) jquery-ajax.html: <form method="post" enctype="multipart/form-data" id="form_upload"> <input type="file" name="file" required id="input_file"></form> <script> $("#upload_btn").click(function () { var x = 1 var form_file = _form_upload.find('#form_upload')[0]; var form_data = new FormData(form_file); form_data.append('x', x); $.ajax({ url:'/ajax/', type:'post', dataType:'json', cache:false, processData: false, contentType: false, data:form_data, success:function (data) { } }); }); </script> views.py: if request.is_ajax(): testpic = TestPic.objects.get(pk=1) form = TestPicForm(request.POST, request.FILES, instance=testpic) if form.is_valid(): form.save() return JsonResponse({'success': 'file_uploaded'}) return JsonResponse({'success': 'file_uploaded with: ' + 'failed form_valid'}) It returns, The 'file_50' attribute has no file associated with it. I think, in forms.py, cropped_50_image.save(user_photo.file_50.path) is the problem. … -
Django app deployment digitalocean stuck at nginx home page
I have followed the DigitalOcean tutorial to deploy a django app at DigitalOcean, the guide is: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-local-django-app-to-a-vps Question: The problem is that when I go to the IP with the browser, I see the Welcome to nginx page and not my django app. Tutorial important points Respect the tutorial, I have not seen the following error as tutorial says: server_names_hash, you should increase server_names_hash_bucket_size: 32 Another important difference between what I did and tutorial is that gunicorn_django --bind yourdomainorip.com:8001 did not work for me. I use this statement to start gunicorn: web: gunicorn --chdir code/computationalMarketing computationalMarketing.wsgi --log-file - My configuration At /etc/nginx/sites-enabled I have symlink called computationalMarketing that refers to /etc/nginx/sites-available/computationalMarketing This files has the following lines: server { listen 127.0.0.1; server_name 159.65.18.211; error_log /var/log/nginx/localhost.error_log info; root /var/www/localhost/htdocs; location /static/ { alias /opt/computationalMarketing/static/; } location / { proxy_pass http://127.0.0.1:8001; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } } I have a virtualenv at /opt/computationalMarketing and inside this I have another computationalMarketing folder with the Git repo file. This repo has the following structure: My installations are: sudo pip3 install numpy==1.13.3 sudo pip3 install pandas==0.22.0 sudo pip3 install scikit-learn==0.19.1 … -
How to show specific subcategory for a selected category in django
Recently I'm working on a blog. where a post has category and subcategory. This is my models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone from ckeditor_uploader.fields import RichTextUploadingField class Category(models.Model): title = models.CharField(max_length=50, unique=True) def __str__(self): return f"{self.title}" class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=50, unique=True) def __str__(self): return f"{self.title}" class Author(models.Model): name = models.CharField(max_length=100) email = models.EmailField(max_length=100) phone_no = models.CharField(max_length=14) details = models.TextField(null=True,blank=True) def __str__(self): return f"{self.name}" class Post(models.Model): author = models.ForeignKey(Author, default=1,blank=True, null=True, on_delete=models.SET_DEFAULT) category = models.ForeignKey(Category,on_delete=models.CASCADE, null=True) sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=250) featured_image = models.ImageField( upload_to="post_featured_image",null=False ) content = RichTextUploadingField() podcast = models.FileField(upload_to="post_podcast", blank=True,null=True) uploaded_on = models.DateTimeField(default=timezone.now) viewed = models.IntegerField(default=0,editable=False) def __str__(self): return f"{self.title}" Now I can choose category and subcategory for a post from Django admin panel. But the problem is I can choose one category and any subcategory even the subcategory is not the child of the selected category. So a post has a category and a subcategory. But the subcategory's parent category is not same as post's category. So I want that I can only choose those subcategories which is the child of selected categories that I choose for the post. Like next … -
How to write django custom command to create model
I have a old schema which contains some models. Without disturbing it I would like add one more model into the same schema using django custom commands. That custom command should be able to create a new model in the database. I studied the django documentation about custom commands and understood that model fields can be changed or added but couldn't figure out how to create custom commands to create models. -
Django Elastic Beanstalk deploy issue: wsgi.py cannot be loaded as Python module
I´m trying to deploy a Django app in Elastic Beanstalk from AWS. I am able to deploy it but get a 500 Internal Server Error. In the log I see: mod_wsgi (pid=3640): Target WSGI script '/opt/python/current/app/locallibrary/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=3640): Exception occurred processing WSGI script '/opt/python/current/app/locallibrary/wsgi.py'. I didn´t din any usefull info around. Do anyone has any idea? Thanks! -
Error when using ffprobe with Django
I use Django and ffprobe to get duration of video thanks to this instruction but it have some issues. Hope your guys help me fix it. My Code: def getLength(filename): result = subprocess.Popen(['ffprobe', filename], stdout = subprocess.PIPE, stderr = subprocess.STDOUT) return [x for x in result.stdout.readlines() if "Duration" in x] class VideoListSerializer(ModelSerializer): class Meta: model = Video fields = [ 'id', 'user', 'video_file', 'video_name', ] def get_duration(self, obj): // print video_file --> '/users/2/videos/9.mp4' result = getLength(obj.video_file) return result Error I get: CreateProcess() argument 2 must be string without null bytes or None, not str Traceback error: Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "C:\Python27\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch 489. response = self.handle_exception(exc) File "C:\Python27\lib\site-packages\rest_framework\views.py" in handle_exception 449. self.raise_uncaught_exception(exc) File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch 486. response = handler(request, *args, **kwargs) File "C:\Python27\lib\site-packages\rest_framework\generics.py" in get 201. return self.list(request, *args, **kwargs) File "C:\Python27\lib\site-packages\rest_framework\mixins.py" in list 45. return self.get_paginated_response(serializer.data) File "C:\Python27\lib\site-packages\rest_framework\serializers.py" in data 739. ret = super(ListSerializer, self).data File "C:\Python27\lib\site-packages\rest_framework\serializers.py" in data 263. self._data = self.to_representation(self.instance) File "C:\Python27\lib\site-packages\rest_framework\serializers.py" … -
How do I overwrite the default managers get_queryset method in django?
I want to filter users on is_active status in the models. def get_queryset(self): return super().get_queryset().filter(is_active=True) This did not work for me! Thank You -
Django Query return nothing
I simply want to implement a search view into my Django app. But when i try to search something on my App i simply get back nothing... In the end i want that my Query is a combination of category and searchword. So that the user can filter specific categories (Just like Amazon.com searchfield) e.g.: http://127.0.0.1:8000/search/?category=1&q=hallo base.html ... <div class="globalsearch"> <form id="searchform" action="{% url 'search' %}" method="get" accept-charset="utf-8"> <label for="{{ categorysearch_form.category.id_for_label }}">In category: </label> {{ categorysearch_form.category }} <input class="searchfield" id="searchbox" name="q" type="text" placeholder="Search for ..."> <button class="searchbutton" type="submit"> <i class="fa fa-search"></i> </button> </form> </div> </div> ... categorysearch_form is a dropdown selector that gets his ID from the Database. views.py ... from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.views.generic import ListView class globalsearch(ListView): """ Display a Post List page filtered by the search query. """ model = Post paginate_by = 10 def get_queryset(self): qs = Post.objects.all() keywords = self.request.GET.get('q') if keywords: query = SearchQuery(keywords) title_vector = SearchVector('title', weight='A') content_vector = SearchVector('content', weight='B') tag_vector = SearchVector('tag', weight='C') vectors = title_vector + content_vector + tag_vector qs = qs.annotate(search=vectors).filter(search=query) qs = qs.annotate(rank=SearchRank(vectors, query)).order_by('-rank') return qs ... urls.py ... url(r'^search/$', views.globalsearch.as_view(), name='search'), ... Search.html results are getting displayd here: {% extends 'quickblog/base.html' %} {% block … -
Pytest celery: cleaned up database after task call
I want to test celery task using pytest in Django. If I use celery_worker parameter in test function then I get an error: {OperationalError}database table is locked(sqllite). If I run worker before tests and do not use celery_worker parameter then task run seccesfully but I can't locate changes in the test database (pytestmark = pytest.mark.django_db) as all updates links to the original database. I try to run the test in Docker (postgresql db) but with parameter celery_worker I get error psycopg2.InterfaceError: connection already closed. -
Django] Saving multiple images by formset doesn't work
Thanks for always helping me. I've come again to ask you some basic questions.. I'm trying to save multiple Images and his parent's data together on the same template. I have one parent's model(to save normal data) and child's model(to save images). In this case, saving parent's data is working very well. but images are not work. There isn't any error message. //model class QuotationPanchok(models.Model): whose = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=50, help_text='', default='') many = models.IntegerField(default='1', help_text='') design = models.CharField(max_length=3, choices=(('yes', 'yes'), ('no', 'no'),)) sian = models.CharField(max_length=3, choices=(('yes','yes'), ('no', 'no'),)) havefile = models.CharField(max_length=3, choices=(('yes','yes'), ('no', 'no'),)) deadline = models.DateField(blank=True) addressto = models.CharField(max_length=50, default='', help_text='') fulltext = models.TextField(max_length=150, blank=True) status = models.CharField(max_length=7, choices=(('not','not'), ('finish', 'finish'),), default='not') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class ImagesForQuotation(models.Model): whose = models.ForeignKey(QuotationPanchok, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/', blank=True, null=True) def __str__(self): return self.whose.title + " Image" // views def quotation_create(request): ImageFormset = modelformset_factory(ImagesForQuotation, fields=('image',), extra=4) if request.method == 'POST': form = QuotationCreateForm(request.POST) formset = ImageFormset(request.POST or None, request.FILES or None) if form.is_valid() and formset.is_valid(): post = form.save(commit=False) post.whose = request.user post.save() for f in formset: try: photo = ImagesForQuotation(whose=post, image=f.cleaned_date['image']) photo.save() except Exception as e: break return redirect('index') else: form = QuotationCreateForm() … -
the current path ,About.html didn't match any of these in django
from django.conf.urls import url from .import views urlpatterns = [ url(r'^$', views.index,name='index'), url(r'^About/', views.About,name='About'), url(r'^checkout/', views.checkout,name='checkout'), url(r'^contact', views.contact,name='contact'), url(r'^faqs', views.faqs,name='faqs'), url(r'^help', views.help,name='help'), url(r'^icons', views.icons,name='icons'), url(r'^payment', views.payment,name='payment'), url(r'^privacy', views.privacy,name='privacy'), ] strong text Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/About.html Using the URLconf defined in shop.urls, Django tried these URL patterns, in this order: admin/ ^$ [name='index'] ^about/$ [name='about'] ^checkout/$ [name='checkout'] ^contact/$ [name='contact'] ^static/(?P.*)$ The current path, About.html, didn't match any of these. -
Django 2.0 - KeyError on View Test for Login
I'm having some problems testing my Django application. I have a view that gets information from a login form and then validate / authenticate the user, therefore redirecting him to a home view that displays various informations. I also put a control so that when the user is not logged in and he tries to insert the URL "/home" it redirects him to a errorpage view that displays an error template. This is the getLogin view, called when the form in the "login.html" page is submitted. I won't show the showLoginTemplate view because it basically does only that. def getLogin(request): if request.user.is_authenticated: ... # operations and context creation ... return render(request, 'myapp:home', context) else: if request.method == "POST": email = request.POST['mail'] password = request.POST['psw'] user = authenticate(request, username=email, password=password) if user is not None: auth_login(request, user) #the Django login renamed as auth_login ... # operations and context creation ... return redirect("/home", context) else: return redirect('/login/error', errorLogin='error') # shows the same page but with a login error message else: return redirect("myapp:errorpage") The home view: def home(request): if request.user.is_authenticated: # operations and context creation return render(request, 'users/home.html', context) else: return redirect("myapp:errorpage") #goes into a error page This is the test I'm trying … -
django : makemigrations process does not end
when i run python manage.py makemigrations and migrate every thing is ok and changes are made but process does not end and I must press control+z to end process why this happend?? is it normal? -
Django and ajax, How to update with django form?
jquery-ajax.html: <form method="post" enctype="multipart/form-data" id="form_upload"> <input type="file" name="file" required id="input_file"></form> <script> $("#upload_btn").click(function () { var some_data = 1 var form_file = _form_upload.find('#form_upload')[0]; var form_data = new FormData(form_file); form_data.append('some_data', some_data); $.ajax({ url:'/ajax/', type:'post', dataType:'json', cache:false, processData: false, contentType: false, data:form_data, success:function (data) { } }); }); </script> models.py: class UserPhoto(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) file_300 = models.ImageField(null=True, blank=True, default=None) file_50 = models.ImageField(null=True, blank=True, default=None) views.py: def upload_user_photo(request): if request.method == "POST": if request.is_ajax(): # UserPhoto object does already exist. user_photo = UserPhoto.objects.get(user=request.user) form = UserPhotoForm(request.POST or None, request.FILES or None, instance=user_photo) if form.is_valid(): print('form_is_valid') form.save() return JsonResponse({'suc': 'ok'}) return JsonResponse({'suc': 'ok', 'message': 'error'}) forms.py: class UserPhotoForm(forms.ModelForm): some_data = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = UserPhoto fields = ('file', 'file_50', 'file_300', 'some_data', ) def save(self): user_photo = super(UserPhotoForm, self).save() image = Image.open(user_photo.file) cropped_image = image.crop((1, 1, 21, 21)) resized_50_image = cropped_image.resize((50, 50), Image.ANTIALIAS) resized_300_image = cropped_image.resize((300, 300), Image.ANTIALIAS) resized_50_image.save(user_photo.file_50.path) resized_300_image.save(user_photo.file_300.path) return user_photo Sorry for newbie question. Now I want to update my UserPhoto model object using django forms. But when I update that, cause of the reason that I don't know, print('form_is_valid') line is not be printed. In my case, UserPhoto object is already exist, so just wanna this object to be updated … -
How to handle immediate login and logout
I am developing and API in django. My problem is when Some user logins (I am using token based authentication) it makes few requests to fetch some data . But when user logins and logout before the request are completed It throws not authenticated message ( Typical message on making requests without authorization). I can understand that this happens because requested are made after token is destroyed. I need to handle this scenario. Any help would be appreciated. Backend Django rest framework ,front end angular 4 -
Django createview permissions
I have a createview for a model. The object it creates is based on a previous model having been entered. How can I query the existence of that previous model prior to allowing the createview to be available please? Many thanks