Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
djangorestframework - security popup if not logged in
For some reason, in setting my DEFAULT_PERMISSION_CLASSES as rest_framework.permission.IsAuthenticated I get the following popup window: This is my REST_FRAMEWORK value in my settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer' ), 'DEFAULT_FILTER_BACKENDS': ( 'rest_framework.filters.DjangoFilterBackend', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication' ), 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'anon': '100/day', 'user': '10000/day' }, 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.URLPathVersioning' } Extra info. If I login using the popup I cannot logout of the website. If I login using the standard login button on the navbar the popup goes away and I can logout but as soon as I refresh the page the popup returns because I'm not authenticated. -
How to have a dot in combination with an no file extension on Windows?
I've a problem with a tutorial I follow from a book. I'm making a website with Django and Python. I'm now at the chapter where I export the website to an server. I have to use Git in order to have some like a back-up for when anything goes wrong. Now I need to make a file, .gitignore, to let Git ignore some files. It must start with a dot and has no file extension. I already knows how to make a file with no extension, to fill in the save field "filename". When I use ".gitignore" the file isn't visible, only the icon and nothing more. I've tried it with another way, make a no file extension to type "gitignore", save it and then edit the name in .gitignore. But then Windows gives an error: "You must specify a filename" Does anyone knows this problem and have a way to fix this? -
django migration impossible because of bug in field default value?
I am facing a strange situation with one of my django models. I am using Django 1.10.3 with python 3.5.2. The model looks like this (simplified for clarity): class Report(models.Model): date = models.FieldDate() def fieldA_default(self): return MyObject.objects.filter(date=self.date).count() fieldA = models.IntegerField(default=fieldA_default) I have the initial migration that creates the model and adds the field, autogenerated by django using ./manage.py makemigrations. I committed this code to my git repo, and deployed it to my production server, but the model isn't actually used (there are no Report objects in my database). I just discovered that this code is incorrect (django set default value of a model field to a self attribute) and decided to override save() instead. But when I change the default from fieldA_default to 0, running ./manage.py makemigrations fails because it tries to run the old default value function fieldA_default. After trying a few options, I eventually decided to delete the model entirely. But that doesn't work either because makemigrations is still trying to run that same function. Here is the traceback from makemigrations when I simply delete the model: Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "venv/lib/python3.5/site-packages/django/core/management/__init__.py", … -
Images didn't display
I'm trying to display images on my local server, but I have a little issue at this point. Picture From settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR From urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home), url(r'^posts/(?P<post_id>[0-9]+)/$', views.post_details, name="post_detail"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Could anyone be able to tell me what is the issue? -
How to get the previous and next object for a model?
I have a model called Post that looks like this: class Post(models.Model): title = models.CharField(max_length=18) body = models.TextField() date = models.DateTimeField() def __str__(self): return self.title How would I get the previous and next Post objects? -
How can I access the rest of the lower name spaces with django-redis?
How can I access the rest of the lower name spaces with django-redis? cache.keys("*") Is only giving me the name space 1:1:TEST which is the key I put in via django-redis. See image below that's the only name space that I'm able to access. How do I access the rest of those assets? Thanks! Casey -
How to include python3 in virtualenv and always start with it?
A client is paying us for me to learn Django - I had a hell of a time setting up a Django CMS project back in December but eventually got it working with Python 3.5. It's been mothballed for about a month since I have not had time to work on this. In trying to pick this up again, I think I messed up my virtualenv. In env/lib is my python3.5 directory from December that has all my site-packages for my DjangoCMS install. However, there is now a python2.7 directory in my env/lib as well from today. Also in my env/include is a link to the Python2.7 install on my Mac. I do not want this. Nor do I want the python2.7 directory in my lib folder. How do I add a link to Python3.5 to my lib folder? All I can find is tutorials on how to CREATE a virtual environment with Python 3: virtualenv -p python3 env But I can't even do that: dyld: Library not loaded: @executable_path/../.Python Referenced from: /Library/Frameworks/Python.framework/Versions/3.5/bin/python3 Reason: image not found I'm so lost and confused and I don't know where my problem is. If it's with my Python3 install or my virtualenv. But … -
Can not import my django settings in python script
i'm trying to use django models in my python script, but everytime i run, it says No module named mysite.settings. import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "WsaleWeb.settings") from models import * def RunScript(): all_cart_items = CartItem.objects.get(is_confirmed=True, is_confirmed_buy_buyer=True) return all_cart_items a = RunScript() print(a) -
Multiple order_by in Django with conditions
I have some Django Model, how can I order_by data from table depend on field value. For e.g. when field with name "status" has value='10', do ASC, when value of status equal '20', do DESC. Need do it in single query. I'm first time here, sorry if I said something wrong. Thanks. -
Django: Designing e-commerce database for fashion application
Designing my first ecommerce application and I would like to know if I am on the right track in regards to designing our Product Model. Some Background: It will be an application with multi brands. Each brand will have products linked to their store. Each Product linked to a brand's store will have various attributes (my focus is on the attribute size but I assume you can do the same for color as well). We are using Django on the (backend) to build the application and launching it via IOS (front-end) Product Model: class Product(models.Model): name = models.CharField(unique=True, max_length=200, blank=True) description = models.TextField() # This would be specific sizes meant for the product that would display # on a dropdown via the front-end for the customer to select: small, medium, Large or 30, 32, 34, 36 size = ArrayField() category = models.ForeignKey('ProductCategory') class ProductCategory(models.Model): name = models.CharField(unique=True, max_length=200, blank=True) -
Accessing list of key value pairs by specific key
I have a matrix in django that looks like: [{'row': 'row_1', 'column': 'column_1', 'value': 'value_1'}: [], {'row': 'row_1', 'column': 'column_2', 'value': 'value_2'}: [], ..., {'row': 'row_n', 'column': 'column_n', 'value': 'value_n^2'}: []] I want to somehow access this monstrosity by row_i, column_j and get value_i*n+j. If I want to get the first value I can do mat.0.0.value. I want to be able to somehow do mat.{'row': 'row_i', 'column': 'column_j'}.0.value Is there any way to do this? -
Django Models Radio Input
I am trying to incorporate radio buttons in my form. In my forms.py I have the following fields for the form : class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['first_name', 'last_name', 'gender'] In my models.py: user = models.ForeignKey(User, db_column='user_id') first_name = models.CharField(max_length=250) last_name = models.CharField(max_length=250 GENDER = (('M', 'Male'), ('F', 'Female'), ('O', 'Other')) gender = models.CharField(max_length=1, choices=GENDER, null=True) I want gender to be rendered as a radio button not a CharField. But I know the models module do not support the RadioSelect and I cannot use widget either. Is there a way to do this? -
Reverse for 'post_detail' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['posts/(?P[0-9]+)/$']
I have this error : Reverse for 'post_detail' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['posts/(?P[0-9]+)/$'] from the line 7 in posts_detail.html template : <a href="{% url 'post_detail' post.id %}">{{ post.title }}</a> From urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home), url(r'^posts/(?P<post_id>[0-9]+)/$', views.post_details, name="post_detail"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) From views.py def post_details(request, post_id): post = get_object_or_404(Post, pk=post_id) return render(request, 'posts/posts_detail.html', {'post':post}) Could anyone be able to tell me how could I fix this problem? -
Django Test server occasional -"Refused to connect error message"
I am hosting my Django Test server on Digital Ocean . I have virtualenv under which when tester requires they just run the python manage.py runserver 0.0.0.0:8000 However occasionally tester gets "Refused to connect error message" But I do not see any error message on the server side What could be the issue? -
Leave only one active connection per user
Using websocket with Django 1.10.5 with Channels 1.0.2. I'm opening a connection with a user token, and I would like the opening to disconnect everyone who is using that user's ID. However the command, even running before accepting the connection, ends up closed the user himself. Here's how I did it: def get_group(user): if isinstance(user, User): uuid = str(user.uuid) return Group('user-%s' % uuid) @channel_session def websocket_connect(message): user = CachedOAuth2Authentication().authenticate(socket_messeger=message) if user: # Do not use more than one device. get_group(user).send({"close": True}) message.channel_session['user'] = user get_group(user).add(message.reply_channel) message.reply_channel.send({"accept": True}) else: message.reply_channel.send({"close": True}) -
Django authentication system not logging in properly
My custom login function seems to login the user. I see the session cookie and all, but when it redirects to the url populated by next, since that page has method decorator(login_required), it goes back to the login page and login treat it as anonymous user. In accounts/views.py: class Login(View): """ Class-based login View """ form = AuthenticationForm template_name = 'login.html' def dispatch(self, *args, **kwargs): return super(Login, self).dispatch(*args, **kwargs) def get(self, request, *args, **kwargs): ''' The get method handles rendering of the login form when the user visits the page. Note that password would show if the form is submitted with a GET request ''' the_user = request.user the_user_authenticated = the_user.is_authenticated() redirect_to = request.GET.get('next', '/') #assert False if the_user.is_authenticated(): return HttpResponseRedirect(redirect_to) authentication_form = self.form() c = {'form': authentication_form, 'user': the_user} return render(request, self.template_name, c) def post(self, request, *args, **kwargs): ''' The post method handles the actual logging in of the user ''' authentication_form = self.form(data=request.POST) redirect_to = request.GET.get('next', '') if authentication_form.is_valid(): cd = authentication_form.cleaned_data the_email = cd['email'] the_password = cd['password'] #assert False # Now, use the custom authentication backend function, authenticate, to authenticate the user using email address #assert False the_credentials = {'email': the_email, 'password': the_password} the_user = authenticate(**the_credentials) #the_user … -
Default OS Environ on Local Machine
I have recently deployed my Django Application to Heorku. However, want to setup some clever way for it to automatically switch to Debug mode when not on Heroku and on my local machine. Thus far, I have added an environment variable as 'Debug_Flag' (FALSE) to Heorku to trigger the following: DEBUG = os.environ['DEBUG_FLAG'] But want to have a it default to True if not found. Any ideas without using an if statement? -
Django REST framework:Use OneToOneField can't GET
when i use Django REST framework ,and use Use OneToOneField and RetrieveUpdateDestroyAPIView can't GET by pk; my code are as follows: models.py class UserAccount(models.Model): username = models.CharField(null=False, max_length=45) password = models.CharField(null=False, max_length=16) class UserContactInfo(models.Model): userAccount = models.OneToOneField(UserAccount, primary_key=True) phone_number = models.CharField(null=True, blank=True) email = models.CharField(null=True, blank=True, max_length=45) serializers.py class UserAccountSerializer(serializers.ModelSerializer): class Meta: model = UserAccount fields = ('id', 'username', 'password') class UserContactInfoSerializer(serializers.ModelSerializer): class Meta: model = UserContactInfo fields = ('userAccount', 'phone_number', 'email') views.py class UserContactInfoDetail(generics.RetrieveUpdateDestroyAPIView): queryset = UserAccount.objects.all() serializer_class = UserContactInfoSerializer urls.py urlpatterns = [ ... url(r'^ContactInfo/(?P<pk>[0-9]+)/$', views.UserContactInfoDetail.as_view()), ] Ok , when i try to GET UserContactInfo data: GET http://127.0.0.1:8000/ContactInfo/1/ and go wrong: AttributeError at /ContactInfo/1/ 'UserAccount' object has no attribute 'userAccount_id' Request Method: GET Request URL: http://127.0.0.1:8000/ContactInfo/1/ ..... Who can help me to fix it . Thanks! -
Django-mobile is not applied in browser developer mode
I have installed django-mobile, followed instructions(had some problem solved Django-mobile import error: module does not define a flavour attribute/clsss) and created mobile folder with existing user.html file inside app_name/templates/app_name where other templates are including desktop version user.html. As far as I understand it must switch to mobile version, if I refresh page from mobile device mode in developer mode(if I am not mistaken, responsive design mode in english) in Safari(in my case )? The question is, shall it normally switch to mobile version in mobile developer mode(or it doesn't work this way) or I haven't implemented something to make it work -
Add a foreign key object within parent form in Django
I am writing a project for studies in which I have a ModelForm based on a model that contains several foreign keys. In this case I need to also add new foreign keys while setting a content for my new object. For example: I am adding a new medicine X that has a producer field (with options: A, B, C) and I want to instantly add a new producer (D) and use it as a producer of medicine that is being created (so the D is a producer of the medicine X). This is exactly what the admin panel provides. I found a topic covering a widget that does it, but I had no luck implementing it. I also found django extra views, but the documentation is very dry and since I am very new to django and MVC architecture I don't know how to use it. Did anybody have an experience using any of the mentioned above? -
Django - Query extended models effeciently
I have a BaseModel(models.Model), and ExtendedModelA(BaseModel) and ExtendedModelB(BaseModel). ExtendedModelA and ExtendedModelB both have foreign key fields to other models. Their unicode methods return a field from this foreign key related model. I have a dropdown menu which I want to populate with BaseModel objects (which naturally includes ExtendedModelA and ExtendedModelB objects). To do this I need a queryset which will get all extended objects (type A and B) and their related objects. I have a merged queryset: queryset = BaseModel.objects.filter(type=1).select_related('extendedmodela') | BaseModel.objects.filter(type=2).select_related('extendedmodelb') The trouble is that the unicode representation of the BaseModel is presented in the dropdown. If I add a unicode method to the BaseModel class which has conditions: if hasattr(self, extendedmodela): return self.extendedmodela.__unicode__() else: return self.extendedmodelb.__unicode__() This results in querying the database for each object. Anyone any ideas about how to get myself out of this mess? Essentially I need to formulate a queryset which will get all BaseModel objects efficiently, and when they're displaying in the dropdown their unicode methods for their respective extended classes (which print fields from a foreign key field object) dont hammer the database. I have a few thousand objects so the database takes a hit. Cheers, Dean -
Django +runmodwsgi Not refreshing data via imported script
For a while now I've been running a Django app using manage.py runmodwsgi --reload-on-changes. Occasionally, the data displayed in the page is old data. I've found that I had to restart the server whenever data became wonky (every few weeks) to rectify. In addition, I've recently added notations to the error log to indicate when the data was sourced and found the below: [Sat Jan 21 22:17:22.230816 2017] [wsgi:error] [pid 26101:tid 139786681575168] [remote 192.168.5.1:49636] Expected Balances Calculations **** as of 2017-01-20. ..i.e. script run today with data as of yesterday (2017-01-20); the expected behavior is the script runs as of today (2017-01-21). When I log into the machine and run the script manually, the expected results are shown with the current date. I did some research and found that Django QuerySets are lazy, but that doesn't apply here, as I'm gathering the data using a separate script outside of Django - below is the views.py. @login_required def index(request): try: Balance_Difference, ProjectedBalance, ActualBalance, PaymentsBalancesList, SumTotalSavings, SumTotalPayments, _ = CompareProjectedandCurrentBalance(0, connection=financesconnection(dbuser=DetermineAppropriateUser())) except OperationalError: connection.close() Balance_Difference, ProjectedBalance, ActualBalance, PaymentsBalancesList, SumTotalSavings, SumTotalPayments, _ = CompareProjectedandCurrentBalance(0, connection=financesconnection(dbuser=DetermineAppropriateUser())) return render(request, 'budget/payments_index.html', {'Balance_Difference': Balance_Difference, 'ProjectedBalance':ProjectedBalance, 'ActualBalance':ActualBalance, 'SumTotalSavings':SumTotalSavings, 'SumTotalPayments':SumTotalPayments, 'PaymentsBalancesList': PaymentsBalancesList, 'title' : "Balances Overview"}) Any ideas? -
Django-Rest-Framework - How to Deserialize Custom Nested Field
I have a model called 'Invite' that searches for an existing user and creates one if they do not already exist: from django.contrib.gis.db import models from users.models import CustomUser class Hangout(models.Model): name = models.CharField(max_length=255) class InviteManager(models.Manager): def create_invite(self, hangout, arrival_time, phone, status=STATUS_INVITED): (user, did_create) = CustomUser.objects.get_or_create(phone=phone) invite = self.create(status=status, hangout=hangout, arrival_time=arrival_time, user=user) return invite class Invite(models.Model): hangout = models.ForeignKey(Hangout, on_delete=models.CASCADE, related_name='invites') user = models.ForeignKey(CustomUser) objects = InviteManager() I am having a lot of trouble deserializing it. I'd like to create a hangout with nested invites with this post request: { 'name': 'Bobs House', 'invites': [ { 'phone': '5127914819', 'name': 'Bob1' }, { 'phone': '0000000000', 'name': 'Bob2' }, { 'phone': '0000000001', 'name': 'Bob3' }, { 'phone': '0000000002', 'name': 'Bob3' }, { 'phone': '0000000003', 'name': 'Bob4' } ] I want the Invite serializer to check that phone exists and is 10 digits long. I am having a lot of trouble setting up a sequence of serializers to work. I have tried combinations of the solutions here and here, but the combination of nested deserializers and custom create fields that are not on the model at all is driving me nuts. Any help is much appreciated! Thanks -
django: disable PREPEND_WWW when using ip address instead of domain name
Django website running behind load balancer which performs health checks by making an HTTP GET request on /health/ using the instance's IP address rather than the domain name. I use PREPEND_WWW to add www to the domain name if missing. But PREPEND_WWW also adds www to the IP address too, which is obviously wrong. e.g. http://www.123.123.123.123/health/ Is there a way to prevent adding the www's for IP addresses, or perhaps only add the www's when a list of regex is matches? Or should I simply avoid using PREPEND_WWW and implement the redirection manually using a custom view/redirection? Please note I am also using SECURE_SSL_REDIRECT = True, in case that also has implications for the www redirection. -
Django-mobile import error: module does not define a flavour attribute/clsss
Trying to apply django-mobile to build mobile versions of templates. https://pypi.python.org/pypi/django-mobile Installation is little mess because TEMPLATE_LOADERS were deprecated (Using Django 1.8), so I added loaders below according to django documentation. So that may be the only difference between my code and instruction. After this I had error saying that APP_DIRS shall be removed so I set it false. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django_mobile.context_processors.flavour ', ], 'loaders': [ 'django_mobile.loader.Loader', ] }, }, ] Finally, with such settings I get this error: ImportError at /user/VitalyKotik/ Module "django_mobile.context_processors.flavour " does not define a "flavour " attribute/class Exception Location: /Users/TheKotik/glboy1/denv/lib/python3.5/site-packages/django/utils/module_loading.py in import_string, line 29