Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Local Settings in Django 2
I'm using Django 2 with Python 3.7 I want to import some settings from a file local_settings.py so I can include that file in a .gitignore so I don't share my secret keys on github. I have the folder tree set up like this: settings.py has this at the end: try: from local_settings import * except ImportError: pass ORDERS = '@catsinuniform.myshopify.com/admin/orders.json' PRODUCTS = '@catsinuniform.myshopify.com/admin/products.json' SHOPIFY_SECRET_KEY = '' SHOPIFY_PWORD = '' ORDERS_URL = f"https://{SHOPIFY_SECRET_KEY}:{SHOPIFY_PWORD}{ORDERS}" PRODUCTS_URL = f"https://{SHOPIFY_SECRET_KEY}:{SHOPIFY_PWORD}{PRODUCTS}" I would also like to put my SECRET_KEY in local_settings.py This isn't working and I can't find why not? Is it my Python version or Django? -
djangoajax not reult in tmplate
I should implement ajax in a django application> 2. I installed djangoajax 3.0.3 and configured INSTALLED_APPS. In my html file I created a link that calls ajax views <p><a href="{% url 'secondotest' %}">test link</a></p> Richiama la url: from django.urls import path from .views import secondotest from django.conf.urls import url urlpatterns = [ url(r'^ajax/secondotest$', ajaxtestiamo, name='secondotest'), ] and this is the views: from django.shortcuts import render from django_ajax.decorators import ajax from django_ajax.mixin import AJAXMixin @ajax def secondotest(request): c = 2 + 3 return {'result': c} 125/5000 but I can not get any results. Someone could help me, I'm stuck with ajax on django for 8 days. Thank you -
Django-filter: Choicefilter with checkbox widget doesn't work
So I'm using Django-filter and trying to render choicefilter as checkboxes in Html (so user can press a checkbox to select his choice rather then selecting from a list. I managed to render it correctly in the html which also seem to send the url correctly, however the the filtering action won't take effect by Django-Filter. Filter.py: import django_filters from festival_list.models import Festival from django.db import models from django import forms class FestivalFilter(django_filters.FilterSet): audience_style = django_filters.ChoiceFilter(choices=Festival.audience_style_choices,widget=forms.CheckboxSelectMultiple,) name = django_filters.CharFilter(lookup_expr='iexact') class Meta: model = Festival fields = ('name','audience_style') Template: <form action="" method="get"> <div class="row filters-row text-center"> {% for audienceStyle in filter.form.audience_style %} <div class="col col-pad"> {{ audienceStyle.tag }} <label for="{{ audienceStyle.id_for_label }}"><span class=""></span>{{ audienceStyle.choice_label }}</label> </div> {% endfor %} </div> <input type="submit" value="Submit" /> </form> When tried to add the auto form by Django-filter using it return an auto error that might give a clue: Select a valid choice. ['Rockers'] is not one of the available choices. (Rockers is one of the model field choices) Thanks =] -
overwrite form for django CreateView
Perhaps just another stupid beginner question: I am having trouble overwriting a django model form which is currently using the following code in views.py. The code below works well ! class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content'] ### want this instead of line 1 and 2 above --> form_class = PostCreateForm() view_args = collections.namedtuple('view_args', ['page_title']) view_args = view_args(page_title="Create Post") def get_context_data(self, *args, **kwargs): self.tgt_url_args = MyHelper.parse_tgt_url(self) context = super(PostCreateView, self).get_context_data(*args, **kwargs) context.update(MyHelper.get_context_metadata(self, self.tgt_url_args, PostCreateView.view_args)) return context def form_valid(self, form): form.instance.author = self.request.user tgt_url_args = MyHelper.parse_tgt_url(self) blog_article = Article.objects.get(pk=tgt_url_args.get('Article', '0')) form.instance.article_field = blog_article return super().form_valid(form) However, I would like to overwrite the form in order to add placeholder to the fields. So I replace line 1 and 2 by: form_class = PostCreateForm() I also added the follwing in forms.py: from django import forms from . models import Post class PostCreateForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content'] print('imported PostCreateForm') When I import and run this however, I get the following error: 'PostCreateForm' object is not callable What am I doing wrong here? -
Django: How to randomize choices field of every existing model
I have 100 instances of a Model, but now I've added a new choices Field with a default value. It is working and every instance share the same field, but I want it to be randomize between the X values of the choices. This is a modified version of my model class MyModel(models.Model): A = 'a' B = 'b' C = 'c' CATEGORIES_CHOICES = ( (A, 'Ant'), (B, 'Buffalo'), (C, 'Cat'), ) category = models.CharField(max_length=1, choices=CATEGORIES_CHOICES, default=A) With that I can go to the shell and type the following: mymodel = MyModel.objects.get(id=1) mymodel.category = random.choices(MyModel.CATEGORIES_CHOICES)[0][0] mymodel.save() And it works, but can I automatize it to do it in all 100 instances? -
Does whitenoise really require collectstatic?
I'm exploring using whitenoise to serve static files in a Django application that's packaged in a Docker container. In the documentation it says: As part of deploying your application you’ll need to run ./manage.py collectstatic to put all your static files into STATIC_ROOT. (If you’re running on Heroku then this is done automatically for you.) Is that really needed? I'm not running ./manage.py collectstatic and static files are still served. If it's not needed, is it an optimization? I'm trying to avoid having needless steps in my deployment process. -
Dajngo: 20 html files: 20 TempalteViews and 20 url patterns needed?
I have 20 Django simple "foo.html" template files. Do I need 20 TemplateViews and 20 entries in url_patterns or is there a simpler solution? -
Callback url for webhooks with DRF
I am to receive notifications from a remote API in my application through a callback url I provided. If my callback url is https://example.com/api/callback and the remote API sends notifications using a GET to my app this way https://example.com/api/callback?invoice_id=BNSLE3 The problem is all their requests receive a 404, I was expecting that I can receive the data in their response with request.query_params but I obviously can't because the remote API can't reach this endpoint. This is the endpoint I used for the callback @csrf_exempt @list_route(methods=['GET'], permission_classes=[AllowAny]) def callback(self, request): print(request.query_params) print(request.data) return Response(status=status.HTTP_200_OK) How do I make my endpoint reachable to the external API because all I get is a 404 error. Extra info: I am using django viewsets when I make a request to https://example.com/api/callback without any params, I am able to hit that endpoint. -
Order_by BooleanField in views.py did not work. Python, Django
I try to return all fields which they have BooleanField 'True' in models.py. But I can not get it: My QuerySet (in views.py): prem_user = User.objects.all().order_by(premium=True)[4:8] This situation returns an error: order_by() got an unexpected keyword argument 'premium' models.py premium = models.BooleanField(default=False) How can you return all 'BooleanField = True'? Any help will be appreciated. -
how to save a select item in django
how to save a select item with a background color in a django of a display list of listed project items i was trying to use javascript queryselectors but it kept on selecting the frist project item with a green background indicating the project was taken, i wanted it done but clicking on a particular project id changing it background to green as indication that project has already been. am open to suggestions dont know what am doing wrong ` {% if latest_question_list %} {% for question in latest_question_list %} <div class="container"> <div class="row example" id="posted-projects"> <div class="col-sm-2 text-center"> <img src="{% static 'img\profile.png' %}" width="60"/> </div> <div class="col-sm-2 text-center"> <br> <a href="" class="btn btn-default btn-sm btn-block"><span class="glyphicon glyphicon-pencil"></span> Edit</a> <br> </div> <div class="col-sm-2"> <br> <button type="button" class="btn btn-default btn-sm btn-block"><span class="glyphicon glyphicon-trash"></span> Remove</button> </div> <div class="col-sm-2"> <br> <button onclick="myFunction()" type="button" class="btn btn-default btn-sm btn-block"><span class="glyphicon glyphicon-briefcase"></span> Take Project</button> </div> <div class="col-sm-4"> <br> <a class="btn btn-default btn-sm btn-block" href="{% url 'explore:detail' question.id %}">{{ question.question_text }}</a> <br> </div> </div> </div> {% endfor %} {% else %} <p>No project are available.</p> {% endif %} ` -
Unable to make gunicorn run on EC2
I am following this tutorial to setup a Django-gunicorn-nginx server in AWS EC2. After installing all dependancies and making a change in wsgi.py as follows import os, sys # add the hellodjango project path into the sys.path sys.path.append('/home/ubuntu/project/ToDo-application/') # add the virtualenv site-packages path to the sys.path sys.path.append('/home/ubuntu/.local/lib/python3.6/site-packages') # poiting to the project settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "todo_app.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() I run gunicorn todo_app.wsgi and get the following error: ubuntu@ip-172-31-61-163:~/project/ToDo-application$ gunicorn todo_app.wsgi [2018-11-07 11:25:35 +0000] [8211] [INFO] Starting gunicorn 19.7.1 [2018-11-07 11:25:35 +0000] [8211] [INFO] Listening at: http://127.0.0.1:8000 (8211) [2018-11-07 11:25:35 +0000] [8211] [INFO] Using worker: sync [2018-11-07 11:25:35 +0000] [8215] [INFO] Booting worker with pid: 8215 [2018-11-07 11:25:35 +0000] [8215] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 578, in spawn_worker worker.init_process() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 135, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 377, in import_app __import__(module) File "/home/ubuntu/urbanpiper/ToDo-application/todo_app/wsgi.py", line 20, in <module> from django.core.wsgi import get_wsgi_application File "/home/ubuntu/.local/lib/python3.6/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File … -
Django ORM - Add data from intermediate table
i have the following many to many data structure in my django rest app: class User(Model): name = models.CharField(max_length=64) memberships = models.ManyToManyField('Membership', through='UserMembership', related_name='users') def __str__(self): return "{}".format(self.name) class Membership(Model): name = models.CharField(max_length=64) def __str__(self): return "{}".format(self.name) class UserMembership(Model): user = models.ForeignKey('User', on_delete=models.CASCADE) membership = models.ForeignKey('Membership', on_delete=models.CASCADE) reason = models.CharField(max_length=64) When i want to list all users i get: { id: 1, name: "name-a", memberships: [ { id: 1, name: "member-a" }, ... ] } but i actually want to include the "reason" field { id: 1, name: "name-a", memberships: [ { id: 1, name: "member-a", reason: "somereason" }, ... ] } But how do i modify the queryset? User.objects.all().values('members__usermember') doesnt work unfortunetly... could anybody support? -
Filter on date range with dynamic rest
I am using django, drf and dynamic rest. I would like to filter on a date range, but there is no documentation for it. How can we specify a date range in the url for dynamic rest? -
Django haystack multithreads update index fail
I tried to use elastic search by Django-haystack. And I want to update indexes faster by adding the argument --workers=10 of Django-haystack. Then I got the error below. Traceback (most recent call last): File "c:\users\watas\appdata\local\programs\python\python36-32\Lib\multiprocessing\process.py", line 258, in _bootstrap self.run() File "c:\users\watas\appdata\local\programs\python\python36-32\Lib\multiprocessing\process.py", line 93, in run self._target(*self._args, **self._kwargs) File "c:\users\watas\appdata\local\programs\python\python36-32\Lib\multiprocessing\pool.py", line 108, in worker task = get() File "c:\users\watas\appdata\local\programs\python\python36-32\Lib\multiprocessing\queues.py", line 337, in get return _ForkingPickler.loads(res) File "C:\Users\watas\Documents\code\InteRed-2018\creators\models.py", line 6, in <module> class Channel(models.Model): File "C:\Users\watas\Documents\code\dj_env\lib\site-packages\django\db\models\base.py", line 100, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\watas\Documents\code\dj_env\lib\site-packages\django\apps\registry.py", line 244, in get_containing_app_config self.check_apps_ready() File "C:\Users\watas\Documents\code\dj_env\lib\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. Here is my configure. Django = 2.0.3 django-haystack = 2.8.1 python = 3.6.4 using in Virtualenv 16.1.0 And it run well without --worker. -
Create a random string each time a model object is saved to database
In my models.py, I have: def MakeOTP(): import random,string return ''.join(random.choices(string.digits, k=4)) class Prescriptionshare(models.Model): prid = models.AutoField(primary_key=True, unique=True) customer = models.ForeignKey( customer, on_delete=models.CASCADE, null=True) time = models.DateTimeField(default=timezone.now) checkin =models.ForeignKey(Checkins, on_delete=models.CASCADE, null=True) otp = models.CharField(max_length=5, default=MakeOTP()) In my django shell, I've tried the following: pq = Prescriptionshare(customer = cus, checkin = chk) pq.save() The problem is that each time this is executed, I get the same string in otp field. There is no random change of string. Why is this happening? -
Testing a Django model with custom save method calling external API
i'm pretty new to unittests and want to make some "simple" beginner tests in my Django application, I have a model with a "custom" save method that calls a external api if new. Can't figure out how to that that model without calling the external API, how do a implement a mock solution for this? class Task(models.Model): status = models.CharField(max_length=25, choices=STATUS_CHOICES, default='new') .... def _create(self): .... return requests.post(API_URL + url, json=payload).json() def save(self, *args, **kwargs): is_new = self.created is None super(Task, self).save(*args, **kwargs) if is_new: self._create() class TaskTestCase(TestCase): def setUp(self): self.task = Task.objects.create(status='new') def test_get_new_task(self): task = Task.objects.all()[0] self.assertEqual(task.status, 'new') -
Temporary users in Django
I would like to implement temporary users in my project. The reason is that people should be able to auth in my application via Facebook Oauth or Facebook Account Kit. I've got 2 decisions, but each one is not ideal. 1) Create User and TemporaryUser models. The first one will have all info about regular user + unique db fields. This TemporaryUser will have only phone_number or facebook_id. Temporary user will be created on auth/ endpoint and response will have auth_token to be able perform registration later with all needed fields. The issue is: how will I determine that user is temporary and his auth_token is legit only for registration/ endpoint? 2) Create basic User model with 2 types: regular or temporary. This model will have only general fields. Also there will be different models with OneToOne relation with User. Only Users with type regular will be able to have that instances with OneToOne relation. The issue is: User model should have USERNAME_FIELD , REQUIRED_FIELDS to be able to login by admin panel + users with different types should have different managers. -
Rotating images in Django forms and save issues Important
please help i have created this code to rotate an image once a button has been clicked, but im having 0 luck, this is super important so any help would be majorly appreciated views.py from PIL import Image from io import BytesIO from django.core.files.base import ContentFiledef rotateright(request,userid): pictures = NewPatientPhotos.objects.filter(id=userid) original_photo = BytesIO(NewPatientPhotos.face_serious.read()) rotated_photo = BytesIO() picture= Image.open(face_serious) picture.rotate(-90, expand=True).save(original_photo, 'JPEG') pictures.face_serious.save(picture.pictures.path, ContentFile(rotated_photo.getvalue())) pictures.save() returnrender(request,'newpatientphotos/viewphotos.html/'{'pictures':pictures}) viewphotos.html {% for picture in pictures.all %} <table border = "0px" width = '300px'> <hr> <tr> <strong>New Patient Records</strong> <br/> <p1>{{post.firstnames}} {{post.surname}}</p1> <small> - {{picture.timestamp}}</small> <hr> {% if picture.face_serious %} <div class = "col-8" onclick="window.location = '{% url 'photozoom1' picture.id %}';" style = "cursor: pointer;"> <img src = "{{picture.face_serious.url}}" class = "img-fluid"/> <br> <small>Face Serious - {{post.firstnames}} {{post.surname}}</small> <a href='{{ picture.face_serious.url }}'> <button class="btn btn-primary"></span>Rotate Right</button></a> </div> {% else %} {% endif %} -
Django url that changes with argument passed
I am making a shopping website and I want to make one url that will help in separating men and women's apparel. What I want to do when you enter .../men/ it should display all products whose gender matches men and same for .../women/ my url looks like urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^upload/$', views.upload, name='uploadproduct'), url(r'^(?P<gender>\w+)/$', views.sex), # url(r'^(?P<gender>\w+)', views.sex,), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) but whatever alphanumeric argument I pass in gender in the url, it does not recognize it. It display Men's Products. example even if I go .../nfjwiene/ it will display all men's products. and also if I go .../women/ the same happens. my view looks: def sex(request, gender=''): if gender == 'men' or 'Men': u='M' elif gender == 'women' or 'Women': u='F' else: u='err' result = Product.objects.filter(sex=u) return render(request, 'sex.html', {'item': result}, gender) -
How can i sum the values of an attribute only for the players of a role in Otree
I am programming a version of the public goods game but using roles. Because of that, i cant obtain the sum of the total contributions of the players who are from a determined role. I tried with the following code: self.total_contribution1 = sum( [p.contribution for p in self.get_players() if p.role== 'A']) But it didn't worked and i only obtained an error of Invalid Operation If i dont write the "if part" of that code, it runs, but the values of the attributes like that one become 0 -
Django CSRF_TOKEN issue with Edge only
I'm trying my django application through different browsers (Chrome, Firefox, IE11 and Edge) and I got an issue with the csrf_token and Edge only. This issue is in reference with my django form. My view file : class ManageDocView(AdminRequiredMixin, View): """ Render the Admin Manage documents to update year in the filename""" template_name = 'omcl/manage_doc_form.html' form_class = ManageDocForm success_url = 'omcl/manage_doc_form.html' @staticmethod def get_title(): return 'Change Document Title' def get(self, request): form = self.form_class() context = { "form": form, "title": self.get_title() } return render(request, self.template_name, context) def post(self, request): form = self.form_class() query_document_updated = None query_omcl = None query_document = None if "submitButton" in request.POST: omcl_list = request.POST.get('omcl_list', False) query_omcl = Omcl.objects.get(id=omcl_list) query_document = Document.objects.filter(omcl=omcl_list) form.fields['omcl_list'].initial = query_omcl elif "UpdateDocument" in request.POST: checkbox_id = request.POST['DocumentChoice'] checkbox_id_minus_1 = int(checkbox_id) - 1 query_document_updated = Document.objects.get(id=checkbox_id) omclcode = query_document_updated.omcl.code src_filename = query_document_updated.src_filename filename, file_extension = os.path.splitext(src_filename) category = query_document_updated.category if category == "ANNUAL": category = "ANNUAL_REPORT" year = self.request.POST['pts_years'] # Create the new document title updated by the new year new_document_title = f"{year}_{category}_{omclcode}_{checkbox_id_minus_1} - {src_filename}" # Create the new document file updated by the new year new_document_file = f"omcl_docs/{omclcode}/{year}_{category}_{omclcode}_{checkbox_id_minus_1}{file_extension}" # Get file.name in order to rename document file in /media/ document_path = query_document_updated.file.name … -
Making a Post method that accepts multiple items in a payload
I have a post method that uses the following payload shown below: { "avg_bid_per_unit":20, "sku": "SKU-009", "status": "OPEN", "supplier": null, "bid": [1,2,3,4] } Normally if bid item was not a list in the payload I would simply implement this: bid = Bid.objects.get(id=request.data['bid']) then I add the ID I got to the payload,in our case multiple IDs are being added to the list. I know there is some iteration involved since since we would like to add items in the bid list which is the best approach to add a list of items when posting. Here is my current Viewset implementation: class BidItemViewSet(viewsets.ViewSet,BaseRetrieveUpdateDestroyView): def create(self, request): """Create a bid item instance.""" bid= request.data.pop('bid') status = request.data['status'] avg_bid_per_unit=request.data['avg_bid_per_unit'] supplier =Supplier.objects.get(id=request.data['supplier']) sku = request.data['sku'] for item in bid: Bid.objects.get(id=request.data['bid']) # Calculate average_bid_per_unit, no_of_bids, in get method bid_obj = BidItem.objects.create( name = status, bid=bid, supplier=supplier, sku=sku, avg_bid_per_unit=avg_bid_per_unit, item= item, org_id =get_auth(request) ) serializer = BidDetailSerializer(bid_obj) return Response(data=serializer.data, status=status.HTTP_201_CREATED) Models class Bid(models.Model): STATUS_CHOICES = ( ('OPEN', 'OPEN'), ('CLOSED', 'CLOSED') ) bid_status = models.CharField(choices=STATUS_CHOICES, max_length=10) avg_bid_per_unit = models.IntegerField() item = models.ForeignKey(Item) org_id = models.IntegerField() # Add issue bid view def __str__(self): return str(self.item.name)+" "+str(self.bid_status) class BidItem(models.Model): # Bid Items View bid = models.ManyToManyField(Bid,related_name="bid_items") # multiple bitd … -
context processor content not accessed with django 2.1.3
I've tried to make some global context the following way, in the pages app created a file context_processor from pages.models import Page def pages(request): response = {} response['pages'] = Page.objects.filter(visible=True, parent=None) return response and in settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, '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', #project context processors 'pages.context_processors.pages' ], }, }, ] on the homepage view def home(request, template_name="home.html"): context = RequestContext(request) response_context = {} ... return render_to_response(template_name, response_context) problem is I can't access the pages data from the context, everything else works fine. If I do it directly from the views it works. -
Django shows 404 after renaming file
I am trying to rename a bunch of files on django (extension change), so I tried to do it with example files first, renaming files is ok but when I try to access that files I get a 404 error. I tried two ways (with same result): - SQL Renaming - Python script renaming old_file: 'testdocx' new_file: 'test.docx' Thanks in advance -
setting a view name when used nested_route in Django
I'm new to django. I want to test my ViewSet(Django = 1.11) but I got this error message. django.urls.exceptions.NoReverseMatch: Reverse for 'license' not found. 'license' is not a valid view function or pattern name. I want to figure out what should I put in the reverse() as parameter. urls.py urlpatterns += util.get_nested_route_urls( router=router, lookup='member', domain='license', view_set=MemberLicenseViewSet, base_name='member_license') test.py class MemberLicenseViewSetTestCase(APITestCase): url = reverse("license") factory = APIRequestFactory() views = MemberLicenseViewSet.as_view