Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to override settings.py with settings_local.py in Django 1.11
I'm quite new in Django 1.11.1 I want to ask how to override settings.py with settings_local.py in my settings.py I have: ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } ... try: from settings_local import * except ImportError: pass in my settings_local.py I have: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DB_NAME', 'USER': 'USER_NAME', 'PASSWORD': 'PASSWORD', 'HOST': 'localhost', 'PORT': '5432', } } but everytime I do python manage.py migrate, the table only created in sqlite3 not in postgresql. I already try to find and use the solution that already provided by other user and already install psycopg2, but still, cannot do it. Is there something wrong with my settings? Regards, -
Installing Pillow for Python 3.6 on Windows
I am new for Python and Django, I am trying about Pillow but When I install Pillow via pip install Pillow from Python Command Shell, I get the message:Exception: Traceback (most recent call last): File "c:\program files\python36\lib\site-packages\pip\compat__init__.py", line 73, in console_to_str return s.decode(sys.stdout.encoding) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa6 in position 79: invalid start byte And I google and try but all failed. Can any one help ? -
Django ORM extra with multiple returns
Is there a way in Django 1.3.7 to return multiple values from one extra select? For example I have two extra selects used to get two separate values, and i would also like to get their difference (I need to be able to filter on it) without needing an extra query: invoices = invoices.extra(select={"value_storned_left": add_invoice_storned_total_query()}) invoices = invoices.extra(select={"total_value_paid": add_invoice_total_paid_query()}) I did not find a solution using annotate for this in Django 1.3 so I was wondering if can combine the two queries and also get the difference there and return 3 values from the same extra query, maybe get something like this: invoices = invoices.extra(select={("value1", "value2", "value3"): combined_query()}) Is there a way to do this and how would it look. The only method I found so far to do this was making and extra third query to get the difference, that uses what i do in the first 2 queries, so this takes longer and it;s heavier on the DB. Thanks -
How to add N dynamic form fields in Django without using javascript / ajax?
I have a model which looks like this: class AddCoffee(models.Model): user = models.CharField(max_length=50) coffee_name = models.CharField(max_length=50) coffee_price = models.CharField(max_length=10) Now, from this model, I get all the coffee_names: coffee_names = AddCoffee.objects.values_list('coffee_name', flat=True) Now, what I want to do (and I couldn't find any way of doing it even if there're some topics closely related here on SO) is to: generate len(coffee_names) ChoiceFields with the labels being each coffee name and the values being a list from 0 to 50. Something like this: class RequestCoffeeForm(forms.Form): coffee_names = AddCoffee.objects.values_list('coffee_name', flat=True) for name in coffee_names: forms.ChoiceField(label="{}".format(name), choices=[x for x in range(51)]) """ Suppose coffee_names = ["ABC", "DEF"] I should have two `ChoiceFields` as follows: ABC = forms.ChoiceField(label="ABC", choices=[x for x in range(51)]) DEF = forms.ChoiceField(label="DEF", choices=[x for x in range(51)]) """ How can I achieve this ? -
Import files into a colection from CLI (django command)
I'm trying to build a django command to upload files and create associated pages for them. My docs are PDF files, and my problem is to automatically "upload" those files into the right target "media" directory, without explicit copying them with my command script from the 'docs repository' to the MEDIA_ROOT defined directory. I've tryed to use: Code f = File(open(file_path, 'r')) # models.OfficeDocument is an inheritor of BaseDocument class new_document, created = models.OfficeDocument.objects.get_or_create(title=title, collection=collection, file=f) Error SuspiciousFileOperation: The joined path (<my_local_path>) is located outside of the base path component (<MEDIA_ROOT path>) but wagtail says me I'm not in the right directory (not in MEDIA_ROOT) How can I do that ? Thanks ! -
Tables2, crispy forms and django chaining filter and paginationnot working
I am trying to filter a joined table2 with django filters and crispy forms. If the user goes to the next page everything is ok, if the user is on the first page and they apply the filter, everything is okay. But if the user goes to the next page and applies a filter (http://localhost/records/?page=2&Duplicates=Duplicates) I get a 404. More over if I apply one crispy form filter and then another filter (http://localhost/records/Duplicates=Duplicates&UnassignedRecords=Unassigned+Records) I get a 404 as well. I render the filter and table like this: <form action="" method="get">{% csrf_token %} {% crispy filter.form filter.form.helper %} </form> {% render_table table %} In my utils I get the query set and context data: class FilteredRecords(SingleTableView): model = None filter_class = None formhelper_class = None context_filter_name = 'filter' def get_queryset(self, **kwargs): qs = super(FilteredStudents, self).get_queryset() self.filter = self.filter_class(self.request.GET,queryset=self.queryset) self.filter.form.helper = self.formhelper_class() return self.filter.qs def get_context_data(self, **kwargs): context = super(FilteredStudents, self).get_context_data() table = setTableDetails(self,context,False) context = {**context, **table} context[self.context_filter_name] = self.filter return context and my filter class looks like this: class RecordFilter(django_filters.FilterSet): Duplicates = django_filters.OrderingFilter(method='duplicateRecords', widget=django_filters.widgets.LinkWidget, fields={'Duplicates':'Duplicates'},) UnassignedRecords = django_filters.OrderingFilter(method='filterUnassinged', widget=django_filters.widgets.LinkWidget, fields={'UnassignedRecords': 'Unassigned Records'},) def filterUnassinged(self,queryset,value,name): qs = Records.objects.filter(id=0) return qs def duplicateRecords(self,queryset,value,name): duplicates = Records.objects.values('Name').annotate(Count('Name')).order_by().filter(Name__count__gt=1) qs = Records.objects.filter(Name__in=[item['Name'] for item in … -
What is the difference between django.views.generic.list.ListView and django.views.generic.ListView in Django?
In the fourth part of the Django tutorial, it used the django.views.generic.ListView, but in Class-based views API reference, the ListView is in django.views.generic.list.ListView. What is the difference between django.views.generic.list.ListView and django.views.generic.ListView? -
Python - Django. DEF function from view aren't showing up after using in the templates
I have a small problem where i unfrotunately cant understand why it happens. I want to use my DEF defined in view in my templates within the for cycle. If i put it just like this (not loading functions from view) it works fine: {% for i in "1234567" %} <option value={{i}}> {{i}}</option> {% endfor %} BUT if i try to load my function defined in view in this 2 different ways: def skuska(request): template = loader.get_template('bc_python\templates\event_list.html') questions = ['name', 'quest', 'favorite color'] context = { 'items':questions } return HttpResponse(template.render(context, request)) OR: def skuska_2(request): questions = ['name', 'quest', 'favorite color'] return render_to_response('event_list.html',{ 'items_n': questions }) AND then i am trying to call it in a for cycle in my template: {% for post in items %} <p>{{ post }}</p> {% endfor %} AND the second : {% for palo in items_n %} <p>{{palo}}</p> {% endfor %} It doesn't not do anything. No error state but on the other side no result on the screen. My Template file can be viewed here event_list.html Could you please explain me how to solve this "issue". I am stucked on this place already for days and cant find any suitable resolution here or on … -
Overriding StackedInLine field
So i basically have models connected like this User Group -> Group -> User So User is in one Group and Group is in one User Group 1:n always. Now in django admin i want to override the StackedInLine Group class GroupInline(admin.StackedInline): model = Group So i wont have to add them one by one but so i can check all of them in following style: So the title Normal User comes from UserGroup name, and listed users are from User model. Now should i override complete admin template for model? Or just stacked inline template? Or just use form somehow? -
Working with Streaming Audio
I am trying to implement a Django application that is able to stream the audio input from browser to the server in real time for further translation. I'm thinking about using Websockets (Django channels or similar) and the HTML5 getUserMedia object. As an alternative, I also understand WebRTC can stream to a media server, but I don't know what approach (if any of these) would be better for requirements. I'd like to be able to save the audio that is being streamed in different files after an X seconds time interval of silence. Any software solution that allows this? -
user_passes_test for CreateView class in django
I want to use user_passes_test for the group Rep to this class.How can I apply this to a create view. views.py class RetestCreate(CreateView): model = Retest fields = ['semester', 'dept', 'batch', 'date', 'subject', 'name', 'admnno', 'reason', 'proof', 'is_sure'] -
Clone and edit an object with inlineformset factory
I have three models, viz. Item, RecipeIngredient and Recipe which look like this: Model - RecipeIngredient class RecipeIngredient(models.Model): item = models.ForeignKey(Item) recipe = models.ForeignKey(Recipe) item_quant = models.DecimalField(max_digits=7, decimal_places=2, default=0) sub_recipe = models.ForeignKey( Recipe, blank=True, null=True, related_name="sub_recipe" ) class Meta: verbose_name = _("Recipe Ingredient") verbose_name_plural = _("Recipe Ingredients") unique_together = (('item', 'recipe'),) Model - Recipe class Recipe(models.Model): name = models.CharField( max_length=128, ) num_servings = models.IntegerField() class Meta: verbose_name = 'Recipe' verbose_name_plural = 'Recipies' Model - Item class SKU(models.Model): name = models.CharField( max_length=128 ) I have RecipeCreateView where I am using inlineformset_factory to create the recipe and the corresponding ingredients. I have a functionality in the RecipeListView to clone the recipe. What I am doing here is that I am redirecting to the create view url with the id of the recipe to be cloned. RecipeCreateView - class RecipeCreateView(InventoryEditMixin, CreateView): model = Recipe form_class = RecipeForm template_name = 'inventory/recipe_add.html' formset_class = RecipeIngredientFormSet def get_initial(self): clone_recipe = self.request.GET.get('clone_recipe') if clone_recipe: recipe = Recipe.objects.filter(id=clone_recipe).first() if recipe: self.initial.update({'num_servings': recipe.num_servings}) return self.initial Under InventoryEditMixin, I am using get_context_data to initialize the inlineformset_factory using the queryset. def get_context_data(self, **kwargs): clone_recipe = self.request.GET.get('clone_recipe') if clone_recipe: recipe = Recipe.objects.get(id=clone_recipe) ingredients = RecipeIngredient.objects.filter( recipe__id=clone_recipe) if recipe: context['formset'] = RecipeIngredientFormSet( queryset=ingredients, … -
Django + nginx + gunicorn views Increment post entry view count not updated
Django + nginx + gunicorn views Increment post entry view count not updated when http request my post not updated. Because web server cached. BUT i not use webserver(nginx) cache . My code worked only development version on django web server my code views.py class ArticleDetail(EntryArchiveTemplateResponseMixin, BaseDateDetailView): ... def get(self, request, *args, **kwargs): self.object = self.get_object() Article.objects.filter(pk=self.object.pk).update(views_count = F('views_count') +1) ... settings.py ... CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } MIDDLEWARE_CLASSES += ( 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ) ... -
Forms with multiple objects at once. Will Django formsets be useful?
I need to create settings page for my items(based on these settings I'll validate data in Item form clean() method depends of item_type). How can I make form like this? Will django formset be useful? COMMUNICATION = "communication" TAXES = 'taxes' ITEM_TYPE_CHOICES = ( (TAXES, "Taxes"), (COMMUNICATION, "Internet/Phone"), class Item(models.Model): name = models.CharField(...) item_type = models.CharField(max_lenght=10, choices=ITEM_TYPE_CHOICES) photo = models.ImageField(...) class ItemTypeSettings(models.Model): item_type = models.CharField(max_lenght=10, choices=ITEM_TYPE_CHOICES) is_required = models.BooleanField(default=False, verbose_name="Photo is requred?") min_value = models.IntegerField("Greater Than (USD)", null=True, blank=True) -
How do the Django csrf token work
Im not clear on the csrf token using Django forms. I have this in my form submit and I see it generated dynamically. If capture my session with fiddler and try to submit my form without that token I get a 403 error. But what I don't understand is I can use fiddler to submit as much data as I want with that same token, so I don't understand the security this token does. If someone hacks your forms they can just use the same token. Am I missing some addition steps to assure that token is always unique. -
Merging Django webaps
I have two working django webapps and I want to merge them, i can do the code but no idea what to do with the databases, how to add the preexisting data to the new fields in the database? Thanks -
Djanho: check if a specific ManyToManyField is empty
This seems super simple but surprisingly could not find any clue on SO or Django docs yet. I want to check if a particular ManyToManyField is empty but cant figure out a way to do it yet. Here's my exact usecase, if it helps: for field in school._meta.get_fields(): # school is the Model object if (field.get_internal_type() == 'ManyToManyField'): #if (find somehow if this m2m field is empty) #do something if empty else: if (field.value_to_string(self) and field.value_to_string(self)!='None'): #do something when other fields are blank or null Found this post which looks similar but is about filtering all ManyToManyFields that are empty in a Model object, so doesn't help the case above. all() or count() or empty() or exists() don't seem to work on ManyToManyFields. if (field): returns True (since its referring to the Manager) Didn't find a relevant option in the Field reference or ManyToManyField reference -
Which is better Nginx or Apache2 for improving the performance?
Some Parameters for comparison are: 1) Handling concurrent requests 2) Serving static content (can Page speed module in Nginx help) 3) Resource utilisation 4) Responsiveness under load Note: My application is in Python/Django. So, I am looking for a Django specific Answer (if it makes some difference). -
save postgres arrayfield using modelform
I have a model with ArrayField and I want save data using ModelForm. But my problem is every time only the first value from array is saving . How do I save whole array from form ? Here is my code: model: class Reminder(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(default=True) provider_type = ( ('Em', 'Email'), ('Sm', 'SMS'), ('De', 'Desktop'), ('Mo', 'Mobile'), ) notification = ArrayField(models.CharField(choices=provider_type, max_length=2, default='Em')) form: class ReminderForm(ModelForm): class Meta: model = Reminder exclude = ('user', ) view: def create(request): if request.method == 'POST': reminder_form = ReminderForm(request.POST) if reminder_form.is_valid(): form = reminder_form.save(commit=False) user = get_object_or_404(User, username=request.user.username) form.user = user form.save() else: ..... return redirect('create') return render(request, 'add.html') -
Include other field as choices to foreign key, Django
I have two models as follows : class FlightSchedule(models.Model): tail_number = models.ForeignKey(TailNumber, null=False, blank=False) flight_number = models.CharField(max_length=30, null=False, blank=False) flight_group_code = models.ForeignKey(FlightGroup, null=False, blank=False) origin_port_code = models.ForeignKey(Port, null=False, related_name="Origin", blank=False) destination_port_code = models.ForeignKey(Port, null=False, related_name="Destination", blank=False) flight_departure_time = models.TimeField() start_date = models.DateField() end_date = models.DateField() def __unicode__(self): return u'%s' % self.flight_number class Meta: verbose_name_plural = "flights Schedule" class PosFlightSchedule(models.Model): tail_number = models.ForeignKey(TailNumber, null=False, blank=False) pos_flight_number = models.ForeignKey(FlightSchedule, max_length=30, null=False, blank=False, related_name='pos_flight_number') pos_flight_departure_time = models.ForeignKey(FlightSchedule, max_length=30, related_name='pos_flight_departure_time') pos_route_id = models.ForeignKey(FlightScheduleDetail, null=False, blank=False, related_name='pos_route_id') pos_flight_date = models.ForeignKey(FlightScheduleDetail, null=False, blank=False, related_name='pos_flight_date') pax_count = models.IntegerField(null=True) def __unicode__(self): return u'%s' % self.pos_flight_number class Meta: verbose_name_plural = "Flights Schedule" For the pos_flight_departure_time , I need the choices from flight_departure_time from the FlightSchedule class. But I get the flight_number values in the drop down. What do I have to change, to get the flight_departure_time values? The classes are from different apps in a single django project. So they have two admin files. -
django's request.META.get('wsgi.url_scheme') returns http instead of https
I find it weird when I saw my request.META.get('wsgi.url_scheme') returning http and my request.scheme returns https This is what my request object dictionary looks like: {'session': <django.contrib.sessions.backends.cache.SessionStore object at 0x7fec7ff57a90>, '_post': <QueryDict: {u'notify_page': [u'https://example.com/my/deposit/success/'], u'bank': [u'CMB'], u'transaction_id': [u'2017051111382524291123'], u'payment_type': [u'1']}>, 'COOKIES': {'csrftoken': 'Y3FRFDfvK6U2dkgVr3KarzJE6GUdAZ1I', 'sessionid': 'uuoxols288i9018fw11coz1yvvwn9ndh', 'auth_req': ''}, '_post_parse_error': False, 'resolver_match': ResolverMatch(func=pay.views.perform, args=(), kwargs={}, url_name=None, app_names=[], namespaces=[]), 'user_agent': <SimpleLazyObject: <function <lambda> at 0x7fec842d2c80>>, '_stream': <_io.BytesIO object at 0x7fec84017cb0>, '_body': 'transaction_id=2017051111382524291123&notify_page=https%3A%2F%2Fexample.com%2Fmy%2Fdeposit%2Fsuccess%2F&bank=CMB&payment_type=1', '_files': <MultiValueDict: {}>, '_read_started': True, 'META': {'HTTP_REFERER': 'https://example.com/my/deposit', 'HTTP_X_FORWARDED_SSL': 'on', 'SERVER_SOFTWARE': 'gunicorn/19.7.1', 'SCRIPT_NAME': u'', 'REQUEST_METHOD': 'POST', 'PATH_INFO': u'/payment/', 'HTTP_ORIGIN': 'https://example.com', 'SERVER_PROTOCOL': 'HTTP/1.0', 'QUERY_STRING': '', 'HTTP_X_REAL_IP': '180.232.79.194', 'CONTENT_LENGTH': '127', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36', 'HTTP_CONNECTION': 'close', 'HTTP_COOKIE': 'csrftoken=Y3FRFDfvK6U2dkgVr3KarzJE6GUdAZ1I; auth_req=; sessionid=uuoxols288i9018fw11coz1yvvwn9ndh', 'SERVER_NAME': '0.0.0.0', 'REMOTE_ADDR': '172.17.0.2', 'wsgi.url_scheme': 'http', 'SERVER_PORT': '8000', 'REMOTE_PORT': '57938', 'HTTP_X_FORWARDED_PROTO': 'https', 'wsgi.input': <gunicorn.http.body.Body object at 0x7fec84220750>, 'HTTP_HOST': 'example-backend.com', 'wsgi.multithread': True, 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'wsgi.version': (1, 0), 'RAW_URI': '/payment/', 'wsgi.run_once': False, 'wsgi.errors': <gunicorn.http.wsgi.WSGIErrorsWrapper object at 0x7fec84036550>, 'wsgi.multiprocess': True, 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'gunicorn.socket': <socket at 0x7fec7ff95590 fileno=14 sock=172.17.0.6:8000 peer=172.17.0.2:57938>, 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'HTTP_X_FORWARDED_FOR': '180.232.79.194', 'wsgi.file_wrapper': <class 'gunicorn.http.wsgi.FileWrapper'>, u'CSRF_COOKIE': u'Y3FRFDfvK6U2dkgVr3KarzJE6GUdAZ1I', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br'}, 'environ': {'HTTP_REFERER': 'https://example.com/my/deposit', 'HTTP_X_FORWARDED_SSL': 'on', 'SERVER_SOFTWARE': 'gunicorn/19.7.1', 'SCRIPT_NAME': u'', 'REQUEST_METHOD': 'POST', 'PATH_INFO': u'/payment/', 'HTTP_ORIGIN': 'https://example.com', 'SERVER_PROTOCOL': 'HTTP/1.0', 'QUERY_STRING': '', 'HTTP_X_REAL_IP': … -
django filter on APIView
I have a APIView class for showing all the rents and posting and delete etc. Now i want search feature so i tried to use DjangoFilterBackend but it is not working. I see in documentation, it has been used with ListAPIView but how can i use it in APIView. class Rent(APIView): """ List all the rents if token is not provided else a token specific rent """ serializer_class = RentSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('city', 'place', 'property_category',) search_fields = ('=city', '=place') def get(self, request, token=None, format=None): reply={} try: rents = Rental.objects.all() if token: rent = Rental.objects.get(token=token) reply['data'] = self.serializer_class(rent).data else: reply['data'] = self.serializer_class(rents, many=True).data except Rental.DoesNotExist: return error.RequestedResourceNotFound().as_response() except: return error.UnknownError().as_response() else: return Response(reply, status.HTTP_200_OK) when i search the rent with the following parameters in the url, i get all the rents, instead i should get only those rents that lies in city Kathmandu and place koteshwor http://localhost:8000/api/v1/rents?city=Kathmandu&place=Koteshwor -
New items in Django admin do not have auto-incremented IDs in PostgreSQL
I have a Django application, and I'm using the Django admin panel to manage my database. I have items with non-sequential IDs (i.e. 1, 2, 4, 5, 7, 9 for example), but when I try to add a new item, it will go to the first unfilled ID (3 in my example), which is fine, but then it will try to insert something into ID 4, which is already occupied. This throws an integrity error. I'm using DataGrip and this is the 'default' value: nextval('<schema>.<table>'::regclass) I tried using SERIAL as the datatype but DataGrip rejected it. My goal: get PGSQL to find the lowest value ID that isn't assigned, and assign that to the object being inserted. If the next value is taken, it should jump to the next available lowest value. If this is not possible, is there a way to get PGSQL to start at a certain number (i.e. 400) and start auto-incrementing from there? And lastly, is there a way for Django to manage the auto-incrementation as opposed to PGSQL? -
If statement only producing one output for all conditions
I have if conditions that are only producing output for one condition on different values. I have tried changing the positions but they always produce one output. Am I doing it wrong? How can I make the values different as per my requirements in the conditions Sample code: def allocate_service(ModelAdmin, request, queryset): platinum_customers = [] silver_customers = [] gold_customers = [] non_customers = [] message = '' for customer in queryset: # This class allows function addition, multiplicationn, division etc. class operable: def __init__(self, f): self.f = f def __call__(self, x): return self.f(x) def op_to_function_op(op): def function_op(self, operand): def f(x): return op(self(x), operand(x)) return operable(f) return function_op for name, op in [(name, getattr(operator, name)) for name in dir(operator) if "__" in name]: try: op(1,2) except TypeError: pass else: setattr(operable, name, op_to_function_op(op)) @operable def getAge(): age = 0 if customer.Age == Customer.objects.get(Age = "60 +"): age = 0 elif customer.Age == Customer.objects.get(Age = "36 - 59"): age = 1 else: age = 2 print(age) return int(age) def getEducation(): education = 0 if customer.Education == Customer.objects.get(Education = "Highschool and below"): education = 0 else: education = 1 return int(education) def getEmployment(): employment = 0 if customer.Employment == Customer.objects.get(Employment = "Student"): employment = … -
Show/hide a link based on checkbox value and saved session
I don't know how to accomplish this. I have this checkbox that when check will show the link and once unchecked will hide the link. $('#chk').click(function(){ if( $(this).is(':checked') ) { $('#link1').show(); } else { $('#link1').hide(); } }); <input type="checkbox" value="1" id="chk" />Check <ul> <li id="link1">Link 1</li> </ul> It should be like this, if I leave the checkbox checked(link should be shown) then I logout, once I login again the link should be shown and vice versa. What should I do to save it to session? Do I need to get the value of the checkbox then saved it in session? Hope someone could help. Thanks. I'm just a newbie in django.