Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Exited too quickly (process log may have details)
When adding my application written in Django to Digitalocean, it gets the following code (on the step Configure Supervisor). urban-train FATAL Exited too quickly (process log may have details) Why does it receive such an error when running the command 'sudo supervisorctl status urban-train'? My Supervisor configuration was as follows. touch logs/gunicorn-error.log sudo vim /etc/supervisor/conf.d/urban-train.conf [program:urban-train] command=/home/urban/bin/gunicorn_start directory = /home/urban/urban-train user=urban autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/urban/logs/gunicorn-error.log ('directory = /home/urban/urban-train ' is my directory in which the file is manage.py) sudo supervisorctl reread sudo supervisorctl update sudo supervisorctl status urban-train And I receives: urban-train FATAL Exited too quickly (process log may have details) Why I not receive urban-train RUNNING pid 23381, uptime 0:00:15? Any help will be appreciated. -
django-celery task has error when added django-impersonate plugin
I'm using celery and celery-beat to run schedule job for a year. And I run celery and celery-beat as daemon. I'm using python3.6 & django2 Recently, I added "django-impersonate" which allow admin users to login as other account. The "django-impersonate" is working fine now. However, all my celery task has error now. Traceback (most recent call last): File "/opt/python3/lib/python3.4/site-packages/celery/app/trace.py", > line 374, in trace_task R = retval = fun(*args, **kwargs) File "/opt/python3/lib/python3.4/site-packages/celery/app/trace.py", line 629, in __protected_call__ return self.run(*args, **kwargs) File "/opt/project/tracker/tasks.py", line 591, in commission from tracker.models import TrueConversion File "/opt/project/tracker/models.py", line 4, in <module> from panel import models as panel_models File "/opt/project/panel/models.py", line 5, in <module> from django.contrib.auth.models import User File "/opt/python3/lib/python3.4/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/opt/python3/lib/python3.4/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/opt/python3/lib/python3.4/site-packages/django/db/models/base.py", line 100, in __new__ app_config = apps.get_containing_app_config(module) File "/opt/python3/lib/python3.4/site-packages/django/apps/registry.py", line 244, in get_containing_app_config self.check_apps_ready() File "/opt/python3/lib/python3.4/site-packages/django/apps/registry.py", line 127, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I have tried to update both plugins, it still has the same error. However, when I run celery task directly by the script, it working fine! celery --app=project.celeryconf:app worker --beat Here is my celery configure file import os … -
Django Model field read only for a MySql generated column
I want to add a generated column to a MySql database and am looking for a way to be able to read that column from a a Django model object, but not have it ever try to write a value for that column on an insert/update and MySql will throw an error on that. I know that you can easily set a field to be readonly on a form for the admin site, but is there a way to set this at the model/field level? -
Defined an ajax function in my urls.py file, but getting a 404 when invoking it in a test
I'm using Django and Python 3.7. I have this in my urls.py file urlpatterns = [ path(r'^ajax/calculate_taxes/$', post, name='calculate_taxes'), ] However, I'm getting a 404 when I try and invoke the logic in my test_views.py class ... # Basic test to verify we can get valid return data def test_calculate_tax(self): state = 'MN' gross = 100000 salary = 75000 json_data = json.dumps({'state': state, 'gross': gross, 'salary': salary}) response = self.client.post('/ajax/calculate_taxes/', json_data, content_type='application/json', HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 302) # this is OK. print(response.content) self.assertEqual(response.content, 2) The view contains a simple post function def post(request): state = request.GET.get('state', None) gross_income = request.GET.get('gross', None) owner_salary = request.GET.get('salary', None) data = { 'sole_pr_taxes': TaxCalculatorService.calc_sole_pr_taxes(state, gross_income), 's_corp_taxes': TaxCalculatorService.calc_s_corp_taxes(state, gross_income, owner_salary), } What am I doing wrong that is causing the 404 in my test? -
FactoryBoy - nested factories / max depth?
I am writing tests for a large Django application, as part of this process I am gradually creating factories for all models of the different apps within the Django project. However, I've run into some confusing behavior with FactoryBoy where it almost seems like SubFactories have an max depth beyond which no instances are generated. The error occurs when I try to run the following test: def test_subfactories(self): """ Verify that the factory is able to initialize """ user = UserFactory() self.assertTrue(user) self.assertTrue(user.profile) self.assertTrue(user.profile.tenant) order = OrderFactory() self.assertTrue(order) self.assertTrue(order.user.profile.tenant) The last line will fail (AssertionError: None is not true), running this test through a debugger reveals that indeed order.user.profile.tenant returns None instead of the expected Tenant instance. There are quite a few factories / models involved here, but the layout is relatively simple. The User (django default) and the Profile model are linked through a OneToOneField, which (after some trouble) is represented by the UserFactory and ProfileFactory @factory.django.mute_signals(post_save) class ProfileFactory(factory.django.DjangoModelFactory): class Meta: model = yuza_models.Profile django_get_or_create = ('user',) user = factory.SubFactory('yuza.factories.UserFactory') birth_date = factory.Faker('date_of_birth') street = factory.Faker('street_name') house_number = factory.Faker('building_number') city = factory.Faker('city') country = factory.Faker('country') avatar_file = factory.django.ImageField(color='blue') tenant = factory.SubFactory(TenantFactory) @factory.django.mute_signals(post_save) class UserFactory(factory.django.DjangoModelFactory): class Meta: model = auth_models.User … -
Configure Supervisor to take care to running the gunicorn server
I'm implementing my django app for the first time on Digital Ocean. It does this with this tutorial. However, at the configuration Supervisor stage there is an error with which I do not know how to deal with it. I want to do configure Supervisor to take care of running the gunicorn server. Thus i write in PuTTY: mkdir logs touch logs/gunicorn-error.log sudo vim /etc/supervisor/conf.d/urban-train.conf Creates a file (urban-train.conf) with such content [program:urban-train] command=/home/urban/bin/gunicorn_start user=urban autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/urban/logs/gunicorn-error.log And now I Reread Supervisor configuration files and make the new program available: root@urban-train:~# sudo supervisorctl reread ERROR: CANT_REREAD: File contains no section headers. file: /etc/supervisor/conf.d/urban-train.conf, line: 1 'n-train]\n' root@urban-train:~# root@urban-train:~# sudo supervisorctl update error: <class 'xmlrpclib.Fault'>, <Fault 92: "CANT_REREAD: File contains no section headers.\nfile: /etc/supervisor/conf.d/urban-train.conf, line: 1\n'n-train]\\n'">: file: /usr/lib/python2.7/xmlrpclib.py line: 800 root@urban-train:~# When i check the status i see: root@urban-train:~# sudo supervisorctl status urban-train urban-train: ERROR (no such process) Why am I getting errors after? sudo supervisorctl reread sudo supervisorctl update Haw to configure Supervisor to take care of running the gunicorn server (In my situation). Any help will be appreciated. -
Django and Bootstrap relationship
I'm working on a development road map for a django project. My choosen IDE is pycharm pro and mock up tool is bootstrap studio. One of my criteria is a calendar and I have discovered that none of the existing public projects will meet my needs so I will have to create one from scratch (no problem). My typical approach would have been that the UI and the django project would be done in near parallel periodically merging and diverging the two. However, given the ability of the two software tools, I'm starting to think that that a better approach may be to do the UI first in BSS, next import the templates into the django project and finally perform the django dev to meet the needs of the UI. The specific calendar functionality is not the issue here, this is a methodology question. While I know that there is a subjective answer to this question (which is not the "answer" I'm looking for here), there also has to be an objective answer as to why this would not work, or be the incorrect approach. -
How can I define the date format in models in django?
I'm defining a date variable inside my model 'AccessRecord' using DateField attribute and I've tried every possible thing to define it. But every time a new error arises. Sometimes it says "Date is not defined" sometimes "Date should be in YYYY-MM-DD format" during migration. Can someone give me a permanent solution for this? I'm using django 2.1.7. I've tried default='' and default=blank and quite of few others from django.db import models from datetime import date class AccessRecord(models.Model): name = models.ForeignKey(Webpage, on_delete=models.PROTECT) date = models.DateField(_("Date"), default=date.today) def __str__(self): return str(self.date) -
How to send app_name,method_name url namespaces in Django
I'm trying to get the hang of Django URL namespaces. But I can't find any examples or documentation. Here is what I have tried. foo.urls from django.urls import path, include from Foo.Views import FooView app_name ="Foo" urlpatterns = [ path('', referansView.referans_listele , name="foo"), path('create/', olusturView.referans_olustur, name="foo_create"), ] foo.html <a class="btn btn-success" href="{% url '{{foo}}:{{foo_create}}' %}?r=Foo: {{request.resolver_match.url_name}}"> fooview.py from django.shortcuts import render from Foo.models import FooModels def foo_create(request): result ={"Foo":"Foo"} return render(request,"referanslar.html", result) What I want is to be able to browse to /foo/X -
Cannot register a U2F key
I'm trying to implement U2F authentication devices in my django app. The primary issue now is, all of my front-end registration calls fail. I'm using the u2f-api.js script and the python-u2flib-server python script to implement this. I am following this pattern: 1) Generate a key/challenge with the u2flib from u2flib_server import u2f app_id = 'https://127.0.0.1' reg = u2f.begin_registration(app_id) print reg # {'registeredKeys': [], 'registerRequests': [{'challenge': u'pLzGmABMwBzQkco6INeFNuPsAG6KhgfVeYFeV0QBf1g', version': 'U2F_V2'}], 'appId': 'https://127.0.0.1'} 2) Register the key from browser var reg_data = {'registeredKeys': [], 'registerRequests': [{'challenge': 'pLzGmABMwBzQkco6INeFNuPsAG6KhgfVeYFeV0QBf1g', 'version': 'U2F_V2'}], 'appId': 'https://127.0.0.1'} u2f.register(reg_data['appId'], reg_data['registerRequests'], [], function(resp) { console.log(resp) }); This consistently returns a {errorCode: 2} response, which essentially means bad request. However, I'm unable to determine what part of this request is invalid. I am using runserver_plus --cert certname to run my local webserver so the site is served via HTTPS. I've also tried using NGROK to access my site over HTTPS and attempted the same code. I consistently get the same response. I would appreciate any help, pointers or guidance on my implementation as I've been struggling for a few days and the existing documentation around U2F libraries and implementations is pretty thin. -
Custom logger is not being triggered when DEBUG=False
I have the following piece of code in settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, 'kodular': { 'level': 'WARNING', 'class': 'account.reporter.KodularExceptionHandler', }, }, 'loggers': { 'django': { 'handlers': ['console', 'kodular'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), }, }, } The KodularExceptionHandler class looks like this: from copy import copy import json import logging import requests from django.conf import settings from django.utils.log import AdminEmailHandler from django.views.debug import ExceptionReporter class KodularExceptionHandler(AdminEmailHandler): def emit(self, record, *args, **kwargs): print("Triggered") try: request = record.request subject = record.getMessage() except Exception: return if record.exc_info: exc_info = record.exc_info else: exc_info = (None, record.getMessage(), None) reporter = ExceptionReporter(request, is_email=True, *exc_info) message = "%s\n\n%s" % (self.format(copy(record)), reporter.get_traceback_text()) text = "**Error Level**: *%s* | **Status Code**: `%s`\n\n\n" % (record.levelname, record.status_code) url = 'https://api.github.com/repos/'+settings.GITHUB_ORG+'/'+settings.GITHUB_REPO+'/issues' session = requests.Session() session.auth = (settings.GITHUB_USERNAME, settings.GITHUB_PASSWORD) issue = {'title': subject, 'body': text+message.replace('*', '\*').replace('_', '\_'), 'labels': ["error"]} r = session.post(url, json.dumps(issue)) if r.status_code != 201: return github_issue_url = json.loads(r.content)['html_url'] if record.levelname == "WARNING": return attachments = [{ 'title': subject, 'color': 'danger', 'actions': [{ 'type': 'button', 'text': 'Github Issue', 'url': github_issue_url, 'style': 'primary', }], 'fields': [{ "title": "Level", "value": record.levelname, "short": True },{ "title": … -
First Name and Last name are not visable in admin panel
I'm using Django-Registration and why the last name and second name is empty in admin panel?If I write all gap and click register and then I go to the admin panel there are username password and email but the first name and last name is empty and I don't know why. lass UserRegistrationForm(forms.Form): firstname = forms.CharField(label='First Name',max_length=50) lastname = forms.CharField(label='Last Name',max_length=50) username = forms.CharField(label='Username',max_length=50) email = forms.EmailField() password1=forms.CharField(label='Password',max_length=50,min_length=5) password2 = forms.CharField(label='Confirm Password',max_length=50,min_length=5) views.py def user_registration(request): form = UserRegistrationForm() if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password1'] firstname = form.cleaned_data['firstname'] lastname = form.cleaned_data['lastname'] email = form.cleaned_data['email'] user = User.objects.create_user(username,email=email, password=password) user.firstname = firstname user.lastname = lastname user.save() messages.success(request,'Thaks for registering {} .Enjoy unlimited access to our recipes .'.format(user.username)) return HttpResponseRedirect(reverse('accounts:login')) else: form = UserRegistrationForm() return render(request,'accounts/register.html',{'form': form}) -
Django ModelChoiceField initial value not working
I've got the following form: class AddGameForm(forms.ModelForm): notes = forms.CharField(widget=forms.Textarea) shelf = forms.ModelChoiceField(queryset=Shelf.objects.all()) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(AddGameForm, self).__init__(*args, **kwargs) self.fields['shelf'].queryset = Shelf.objects.filter(owner=self.user) class Meta: model = Game fields = ['name', 'status', 'hours', 'minutes', 'platform', 'notes', 'shelf'] and I want to set the initial value of shelf. I've tried this, but it doesn't work, at all. shelf = GameShelfJunction.objects.filter(game_id=game).first() form = AddGameForm(instance=game, initial={'shelf': shelf.pk}, user=request.user) I can't find anything online with a solution other than using the initial kwarg, so I'm kind of lost. Does this have to do with me using the __init__ function to filter the queryset? -
How to make a readonly field that can not be edited by user in a Django forms?
I'm trying to create my first own project in python django. What I'v done so far is a simple shop. When I click this: item_details.html <a href="{% url 'buy_item' pk=item.pk %}" class="submit">Kup teraz</a> I will be redirected urls.py path('buy/<int:pk>', ItemCreate.as_view(), name='buy_item') To this form: form.py class BuyForm(forms.ModelForm): class Meta: model = Order fields = ( 'item', 'delivery', 'price', 'buyer',) With this view: views.py class ItemCreate(CreateView): model = Order fields = ['item', 'price', 'buyer', 'delivery'] def get_initial(self): item = get_object_or_404(Item, pk=self.kwargs['pk']) self.initial.update({ 'buyer': self.request.user, 'price': item.price, 'item': item.pk, }) return super(ItemCreate, self).get_initial() models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Category(models.Model): title = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.title class Item(models.Model): seller = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=100) price = models.FloatField(null=False, blank=False) img = models.ImageField(blank=True, null=True, upload_to='covers/%Y/%m/%D/') published_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title class Supplier(models.Model): title = models.CharField(max_length=100) def __str__(self): return self.title class Delivery(models.Model): title = models.ForeignKey(Supplier, on_delete=models.CASCADE) price_of_delivery = models.FloatField(null=False, blank=False) def __str__(self): return self.title class Order(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) delivery = models.ForeignKey(Delivery, on_delete=models.CASCADE) order_date = models.DateTimeField(default=timezone.now) buyer = models.ForeignKey(User, on_delete=models.CASCADE) price = models.FloatField(null=False, blank=False) def __str__(self): return self.item Because the initial data shouldn't be edited … -
Deleting Django migrations file before running 'migrate' command?
Say I have this model which has already has a few prior migrations that have been implemented: from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): account = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default = 'default.jpg', upload_to='profile_pics') user_level = models.IntegerField(default = 1) def __str__(self): return '%s Profile' % self.account.username I decide to make a change to the model, changing the user_level field to level_rank and specifying a relationship to a field in a different model: from django.db import models from django.contrib.auth.models import User from level_system.models import UserLevel from PIL import Image class Profile(models.Model): account = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default = 'default.jpg', upload_to='profile_pics') level_rank = models.ForeignKey(UserLevel, on_delete = models.SET_NULL, null = True) def __str__(self): return '%s Profile' % self.account.username I then run the makemigrations command, but afterwards decide I want to change something else about the Profile model. What are the consequences of just deleting the migrations file that was created when I ran the makemigrations command? Essentially, my question is will this confuse the migrations system and corrupt the database, or can you freely delete a migrations file which has NOT yet been migrated? I'm currently using Django v2.0.13 Thanks! -
Model Choices Field return null value on template
My model form has a coices field class cekler(models.Model): bankalar = ( ('Ziraat Bankası', 'Ziraat Bankası'), ('YapıKredi Bankası', 'YapıKredi Bankası'), ('Vakıflar Bankası', 'Vakıflar Bankası'), ('Teb', 'TEB'), ) banka=models.CharField(max_length=20, choices=bankalar, verbose_name="Banka Adı:") And my form; class CekForm(forms.ModelForm): class Meta: model=cekler fields=[ 'banka', ] And my view like that; def cekEkle (request): form = CekForm(request.POST or None) if form.is_valid(): form.save() context ={ 'form':form, } return render(request,'cek/form.html',context) How can I use this coices field on my template with HTML/Select-Option tag? -
Issues in choices field when deployed to heroku
I have a model with django-multipleselectfield. It works fine on localhost but when I deploy it to heroku and migrate. It collapses. added release: python manage.py migrate to Procfile but doesn't seem to help. class Skill(models.Model): SKILL_CHOICES = ( ('html5', 'HTML5'), ('css3-alt', 'CSS3'), ('js-square', 'Javascript'), ) skills = MultiSelectField(choices=SKILL_CHOICES) error ProgrammingError at / relation "myself_skill" does not exist LINE 1: ..."myself_skill"."id", "myself_skill"."skills" FROM "myself_sk... Exception Type: ProgrammingError Exception Value: relation "myself_skill" does not exist LINE 1: ..."myself_skill"."id", "myself_skill"."skills" FROM "myself_sk... -
Need a small advice on the DB query optimization
Question is about code optimization, to be exact -DB query optimization: … … … filter1 = Comment.objects.filter(foreignkey_to_model1__author=self.request.user, is_active=True) filter2 = Comment.objects.filter(foreignkey_to_model2__author=self.request.user, is_active=True) context["comments_by_user"] = filter1.union(filter2)[: 5] return context I feel like this code is suck as it consist of the 2 queries + slice instead of filter on a DB level. Question – is it any chance to pack it in 1 query nicely in order to decrease load on the DB? ( and make this code less suck…) Thanks -
name 'IntegrityError' is not defined - why can't I used 'except: IntegrityError' on this script?
I'm running a script from inside a django application at the very root of the app_name folder; as in app_name>app_name. At the top of the script I have this: import os import sys os.environ.setdefault('DJANGO_SETTINGS_MODULE','versal.settings') import django django.setup() I'm trying to handle an integrity error - my slugs need to be unique, so when one isn't unique, I want to handle the integrity error by adding a '1' to the slug. try: podcast_instance.slug = slugify(parsed_podcast.title) podcast_instance.save() podcast_saves += 1 except IntegrityError: podcast_instance.slug = slugify(parsed_podcast.title + '1') podcast_instance.save() podcast_saves += 1 When I run this code, I get this: Traceback (most recent call last): File "podcasts.py", line 166, in <module> podcasty() File "podcasts.py", line 159, in podcasty submit(podcast_objects,podcast_rss) File "podcasts.py", line 73, in submit except IntegrityError as e: NameError: name 'IntegrityError' is not defined -
How can i use the upgraded version of Sqlit3 for my Django project?
I am trying to create a django application on a server running on Centos 7. When i tried to migrate the application, i got the error:"SQLite 3.8.3 or later required (found 3.7.17)." Thereafter I installed the latest-version of Sqlite3. When i run sqlite3 --version, it showns 3.28.0 which is the latest version. Howevere, when I tried my migrate the project I got the same error i.e "SQLite 3.8.3 or later required (found 3.7.17)." Can someone please suggest how to ensure that python/django is configured with the latest version of sqlite3 rather than the older one which came along with the OS? -
It's to make a form that take input from user and matches it with the answer as stored in database
I have a three tables named Question, Answer and Profile in the database ,each question has a answer which the user must enter as input if answer matches user should be awarded 10 points(Points should be changed in Profile named table ) else a message 'please try again' should be displayed. I have made the tables and added question and answer class UserProfile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) points=models.IntegerField(default=0) status=models.IntegerField(default=0) image=models.ImageField(upload_to='',blank=True) def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) # Create your models here. class Question(models.Model): question_id = models.IntegerField(default=0, unique=True) question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer_text = models.CharField(max_length=200) def __str__(self): return self.answer_text I expect increase in points in database for the correct answer and simply display 'try again' if answer is wrong. -
'tuple' object is not callable when trying to set permissions for Django Rest API Viewsets
I am trying to set up permissions for my User model API. My goal is to let anyone create, list and get users, but only let the user partially update him or herself. However, when I try to make a call to my API i get: TypeError: 'tuple' object is not callable views.py class UserViewSet(viewsets.ViewSet): def get_permissions(self): if self.action == 'partial_update': self.permission_classes = (IsAuthenticated, IsUpdateUser,) #Also tried with [isAuthenticated, isUpdateUser], the same goes for the other if statements if self.action in ('list','retrieve'): self.permission_classes = (SAFE_METHODS,) if self.action == 'create': self.permission_classes = (AllowAny,) return super(self.__class__, self).get_permissions() def list(self, request): queryset = User.objects.all() serializer = UserSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = User.objects.all() user = get_object_or_404(queryset, pk=pk) serializer = UserSerializer(user) return Response(serializer.data) def create(self, request, format='json'): serializer = UserCreateSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: token = Token.objects.create(user=user) json = serializer.data json['token'] = token.key return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def partial_update(self, request, *args, **kwargs): instance = self.queryset.get(pk=kwargs.get('pk')) serializer = self.UserSerializer(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) permissions.py class IsUpdateUser(permissions.BasePermission): def has_permission(self, request, view): # can write custom code print (view.kwargs) try: user = User.objects.get( pk=view.kwargs['pk']) except: return False if request.user == user: return True return False The … -
Django IPRestrict Middleware raises PermissionDenied
I'm using Django-iprestrict and the docs are as given in here: https://django-iprestrict.readthedocs.io/en/latest/ And here are the middlewares: MIDDLEWARE = [ 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'accounts.middleware.ActiveUserMiddleware', 'iprestrict.middleware.IPRestrictMiddleware' ] At first as it was given in docs I tried putting IPRestrictMiddleware at right before SecurityMiddleware, but I have added my own additional context for templates where I needed to use request.user.is_authenticated and when IPRestrictMiddleware was at top, it used to give error 'WSGIRequest' object has no attribute 'user' so I moved it to end of middlewares. At the end in both cases it gave PermissionDenied error and the traceback is this: [18/Apr/2019 11:32:34] "GET / HTTP/1.1" 403 268006 Forbidden (Permission denied): /favicon.ico Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/utils/deprecation.py", line 90, in __call__ response = self.process_request(request) File "/usr/local/lib/python3.6/dist-packages/iprestrict/middleware.py", line 44, in process_request raise exceptions.PermissionDenied django.core.exceptions.PermissionDenied I do see that it's showing Forbidden (Permission denied): /favicon.ico but I have already added a shortcut icon on my html so I'm not sure if it's showing the right thing. And also when I use runserver on my local windows pc no such error is shown, but I wanted to try deployment so created … -
Django How to add user info to Sentry's report when an error happened?
I use the django-restful framework and I want to add user info to Sentry's report when an error happened in the ModelViewSet. I find this doc of Sentry: https://docs.sentry.io/enriching-error-data/context/?_ga=1.219964441.1220115692.1472094716%3F_ga&platform=python#capturing-the-user It gives some code as follows: from sentry_sdk import configure_scope with configure_scope() as scope: scope.user = {"email": "john.doe@example.com"} But I can not figure out how to properly use it. I think there exists a better way than the following: @list_route() def fun_xxx(self, request, *args, **kwargs): user = request.user with configure_scope() as scope: scope.user = {"id": user.id,......} ...some code may cause an error... return Response({...}) Can anyone give me some suggestions? :) -
django with apache getting RuntimeError: populate() isn't reentrant error
i get this eror : RuntimeError: populate() isn't reentrant, i am working with ubuntu 16.0.4 apache2 and nod_wsgi on AWS EC2, start to get up project that is working (not a new project) the full log : # tail /var/log/apache2/error.log [Thu Apr 18 11:18:59.899019 2019] [wsgi:error] [client 81.218.184.134:19087] Traceback (most recent call last):, referer: https://ec2-**.com/accunts/login [Thu Apr 18 11:18:59.899034 2019] [wsgi:error] [client 81.218.184.134:19087] File "/home/ubuntu/work/trunk/***/wsgi.py", line 12, in <module>, referer: https://ec2-***.compute-1.amazonaws.com/accunts/login [Thu Apr 18 11:18:59.899059 2019] [wsgi:error] [pid 1592:tid 140260738557696] [client 81.218.184.134:19087] application = get_wsgi_application(), referer: https://ec2-***.compute-1.amazonaws.com/accunts/login [Thu Apr 18 11:18:59.899066 2019] [wsgi:error] [pid 1592:tid 140260738557696] [client 81.218.184.134:19087] File "/usr/lib/python2.7/dist-packages/django/core/...wsgi.py", line 14, in get_wsgi_application, referer: https://ec2-***.compute-1.amazonaws.com/accunts/login [Thu Apr 18 11:18:59.899078 2019] [wsgi:error] [pid 1592:tid 140260738557696] [client 81.218.184.134:19087] django.setup(), referer: https://ec2-***.compute-1.amazonaws.com/accunts/login [Thu Apr 18 11:18:59.899083 2019] [wsgi:error] [pid 1592:tid 140260738557696] [client 81.218.184.134:19087] File "/usr/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup, referer: https://ec2-***.compute-1.amazonaws.com/accunts/login [Thu Apr 18 11:18:59.899092 2019] [wsgi:error] [pid 1592:tid 140260738557696] [client 81.218.184.134:19087] apps.populate(settings.INSTALLED_APPS), referer: https://ec2-***.compute-1.amazonaws.com/accunts/login [Thu Apr 18 11:18:59.899097 2019] [wsgi:error] [pid 1592:tid 140260738557696] [client 81.218.184.134:19087] File "/usr/lib/python2.7/dist-packages/django/apps/registry.py", line 78, in populate, referer: https://ec2-***.compute-1.amazonaws.com/accunts/login [Thu Apr 18 11:18:59.899105 2019] [wsgi:error] [pid 1592:tid 140260738557696] [client 81.218.184.134:19087] raise RuntimeError("populate() isn't reentrant"), referer: https://ec2-***.compute-1.amazonaws.com/accunts/login [Thu Apr 18 11:18:59.899117 2019] [wsgi:error] [pid 1592:tid 140260738557696] [client 81.218.184.134:19087] …