Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unkown FastCGI error when using conda env
Here is my scenario.... I am trying to configure a Django application on IIS 8.5 (Windows Server 2012 R2). Basic steps included... Added a FastFGI Handler Mapping Configured FastFGI Handler Using wsfastcgi.py I have done this several times with success, but I have always "pointed" my configuration to the "primary" python installation on the server. This time, I wanted to set up a virtual environment (I use Anaconda envs - not virtualenv) to isolate my environment. However, when I point my IIS/FastFGI configuration setting to point to my virtual environment's python.exe, I am getting an unknown FastCGI error when I go to access my site. This is the only change I am making to the config. Bottom line - it works when I point to "primary" python.exe and doesn't when I point to my virtual environment's python.exe. I can give more information on my environment/configs if need be. Just let me know the information you need to help diagnose. As always - appreciate everyone's help! -
NameError: global name 'Model' is not defined
I have a simple Django app where I want to define two tables in the database: user and question. I have the following models.py: from django.db import models class User(models.Model): name = models.CharField(max_length=100) @classmethod def create(cls, name): user = cls(name=name) return user class Question(models.Model): content = models.CharField(max_length=300) answer = models.CharField(max_length=200) @classmethod def create(cls, content, answer): question = cls(content=content, answer=answer) return user In /questions, which is defined in views.py, I would like to display all objects of type question: from django.views.generic.base import TemplateView from django.http import HttpResponse from django.shortcuts import render_to_response from django.db import models def questions(request): questions = Model.objects.raw('SELECT * FROM questions') return render_to_response('questions.html', questions) However, I am getting: NameError: global name 'Model' is not defined Why is the Model object visible in models.py but not in views.py? Also, is the way in which I query the database correct? -
Django call function from button, while staying on the same page
I have a dynamically created table with data from a django model. This table is displaying additional information about each data_element. In the last column there should either be a button displayed for each row, which will run the script with additional keywords from that specific data_element, without reloading or freezing the page. If the script is still running (can take hours) there should be progress icon displayed and if the script has already finished, there should be a button displayed, redirecting to an results.html How can I program that with django? Currently I am executing a script manually, but for that I am redirecting to another template with the args to parse and when the script is executed (with call_command('my_script', *args) the page freezes until the script ends. <form action="{% url 'calculate' element_id %}"> <input class="btn btn-primary-custom" id="submit" type="submit" value="run script"> </form> I tried to insert the code from this post: Django button ajax click But when I click on that button, nothing happens. What do I have to do, to create that table? -
Passing Functions
def HourlyPay(): Hours = float(input("2 of 4 - Enter Hours Work (Maximum of 60 hours): ")) Hours = abs(Hours) while Hours > 60: print("Error: Enter an amount between 1 - 60") Hours = float(input("2 of 4 - Enter Hours Work (Maximum of 60 hours): ")) Hours = abs(Hours) else: pass PayRate = float(input("3 of 4 - Enter Employee's Hourly Pay Rate (Maximum of $100): ")) PayRate = abs(PayRate) while PayRate > 100: print("Error: Enter an amount between 1 - 100") PayRate = float(input("3 of 4 - Enter Employee's Hourly Pay Rate (Maximum of $100): ")) PayRate = abs(PayRate) return Hours, PayRate def gross(): salary = PayRate * Hours if Hours > 40: overtime = 40 - Hours salary += 0.5 * overtime return salary def taxrate(): tax = float(input("4 of 4 - Enter Employee's Income Tax Rate (Maximum 50% or 0.5): ")) tax = abs(tax) while tax > 0.5: print("Error: Enter a Tax Rate no more than 50% or 0.5") tax = float(input("4 of 4 - Enter Employee's Income Tax Rate (Maximum 50% or 0.5): ")) tax = abs(tax) else: pass taxtotal = tax * salary return taxtotal def Netpay(): Net = salary - tax return Net again = True … -
Django Static Inlines
I have a model Student with lots of fields and a model Document with a ForeignKey to Student. I'm using an inline to edit Students' associated Documents. models.py: class Document(models.Model): def media_path(instance, filename): return '{0}/{1}'.format(instance.Student.Id, filename) File = models.FileField( _('File'), upload_to=media_path,) Title = models.CharField( _('File Name'), max_length=32, blank=True,) Student = models.ForeignKey( Student, null=True, on_delete=models.SET_NULL) class Meta: verbose_name = _('Document') verbose_name_plural = _('Documents') admin.py: class DocumentInline(admin.TabularInline): model = Document extra = 0 class StudentAdmin(UserAdmin): ... inlines = [ DocumentInline, ] class Meta: model = Student admin.site.register(Student, StudentAdmin) What I want is to add 3 inline Document lines with specific Title each time a Student is created, so for example: I just created a Student and I already have 3 lines in the Document inlines section and each one with a pre-defined Title (and the File obviously is empty): File 1 File 2 File 3 How can I do such thing? Thanks in advance. -
django-rest-framework + NamespaceVersioning: How to mock 2 allowed_versions for testing?
I'm on Django 1.8 and djangorestframework 3.5.2. For testing my versioning setup I want to mock a scenario where I have 2 versions live, while I currently only have one. So my production setting is: REST_FRAMEWORK = {... 'ALLOWED_VERSIONS': ["v1"] ...} My test url pattern setup works, but I fail to temporarily switch to two allowed api versions. I tried to override it just for my testcase, but looking at the versioning source code it reads the value on server-start, so that overriding later has no effect on it. import copy from django.test import override_settings from django.conf import settings REST_FRAMEWORK_TEST = copy.deepcopy(settings.REST_FRAMEWORK) REST_FRAMEWORK_TEST["ALLOWED_VERSIONS"] = ["v1", "v2"] with override_settings(REST_FRAMEWORK=REST_FRAMEWORK_TEST): ...making request to a v2 url... It will still say that v2 is not a valid version. How could I mock it nonetheless except for using a whole different settings file? -
Abstract models with a parameter in Django
Is it possible to create an abstract Django model with a parameter? Like a meta-meta class? class Parent(models.Model): field1 = CharField(max_length=100, default=MY_STRING) field2 = CharField(max_length=100, default=MY_STRING + ' lorem ipsum') field3 = IntegerField(default=5) class Meta: abstract = True class Child(Parent(MY_STRING='abc')): # now it should have: # field1 with default value "abc" # field2 with default value "abc lorem ipsum" # field3 with default value 5 -
django: mock post_save signal handler?
tests.py from unittest.mock import patch from orders.models import Order class OrderModelTest(CartSetupTestCase): def test_string_representation(self): # Mocking Order's post_save signal with patch('orders.signals.post_save_order', autospec=True) as mocked_handler: post_save.connect( mocked_handler, sender=Order, dispatch_uid='test_cache_mocked_handler' ) order = Order.objects.create( user=self.user, merchant_uid="1475633246629", customer_name="최정우", address="주소", address_detail="상세주소", postal_code="12345", phone_number="01095104344", possible_date_start="2011-11-24", possible_date_end="2011-11-24", possible_time_start="11:22 AM", possible_time_end="11:22 AM", total_price=self.cart.total_price, ) signals.py @receiver(post_save, sender=Order, dispatch_uid="spacegraphy") def post_save_order(sender, instance, created, **kwargs): if created: SlackNotification.objects.create( receiver="order_web", content="새로운 견적 주문이 들어왔습니다. 자세한 사항은 <http://naver.com|여기> 클릭 :)" ) I followed http://stackoverflow.com/a/13119150/3595632, but it doesn't work, which means, it called signal handler in real! (I checked it out using print()) Anything wrong? -
Django App + Payment Gateway + Hosting server
Hi Guys can you please guide me , which will be the best hosting server for the django app with any payment gateway integrated on it, in which server the payment will be secured, I heard about AWS but can you please suggest any other hosting sever will be best for this and can you please explain me the pros and cons.Thanks in advance. -
multiple load tags in django templates
directory structure app_one templatetags __init__.py filter_one.py app_two templates app_two template_one.py templatetags __init__.py filter_two.py There are some filters in filter_one.py, Also there are some filters in filter_two.py. And every usages of these filter in the template_one.html were working. Then I added two more filters in filter_one.py filter_one.py @register.filter def f1(val): return val['evaluations'][0]['range'] @register.filter def f2(val) return val['evaluations'][1]['data-type'] template_one.html {% load filter_one.py %} {% load filter_two.py %} {{ value | f1 }} This gives an error "Invalid Filter: f1". But it works when I move the templates to filter_two.py Can't figure out the logic behind it! -
Django Info logging doesn't rotate anymore
I modified the logging system in my Django app, so to log some warning messages in some situations. These new warning log files work correctly, but the default log info files have stopped rotating, and now all messages goes to the same .log file, instead of rotate each day and compress old files, and delete older ones. I'm using Django 1.9 running in uWSGI and Nginx. Nginx log files work just fine. This is how the logging part of my settings file looks like: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'hc': { 'format': '%(asctime)s \n%(message)s' }, 'verbose': { 'format': ' [%(asctime)s] [%(levelname)s] [%(name)s] %(message)s' }, }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, 'error': { 'level': 'ERROR', 'class': 'logging.handlers.TimedRotatingFileHandler', 'backupCount': 50, 'when': "D", 'interval': 1, 'filename': '/var/log/django/error.log', 'formatter': 'verbose' }, 'alarm': { 'level': 'WARNING', 'class': 'logging.handlers.TimedRotatingFileHandler', 'backupCount': 50, 'when': "D", 'interval': 1, 'filename': '/var/log/django/warningalarm.log', 'formatter': 'hc' }, }, 'loggers': { '': { 'handlers': ['error'], 'propagate': True, }, 'django': { 'handlers': ['console'], 'propagate': True, }, 'application': { 'handlers': ['alarm'], 'level': 'WARNING', 'propagate': False, }, } and this is the uwsgi .ini file for my app: [uwsgi] … -
Django - admin custom search, where search field is not in model
I want to add a custom search to the django admin, where the searched field is not in the model. Until now, i have this: search_fields = ['sku'] def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super(InputItemAdmin, self).get_search_results(request, queryset, search_term) return queryset, use_distinct When i'm calling the super class i get this error: FieldError - Cannot resolve keyword 'sku' into field. How can I prevent this error while calling the super class? Is it possible to tell the super class that the search field not exists in the model? -
Django: Make query using url ( Assigning variable using url )
I am trying to make a query system for my website, i think the best way and the most compact would be to assign search variable using url pattern. So for example, i want to search objects of model User: User sends HttpRequest to following url: https://127.0.0.1/search/q="admin" Now HttpRequest is also sent to search view, we somehow get q variable data. def search(request): for query in User.objects.all(): if q in query: # < We somehow need to get data of 'q'. return HttpResponse(q) Since i have admin in User.objects.all(), this should return HttpResponse of 'admin'. How can this url pattern be made? So i can assign q variable from the url and then send it to system to find it? -
django create and use multi databases at runtime
how can build a multi tenant Django application, that might create new databases on run time and use them on run time too,Odoo does the same but in Django the settings file restricts you to define the databases before you run the application. -
Server doesn't start in hello world app
I am trying to create a Django hello world app. I have the following code: import sys from django.conf import settings from django.http import HttpResponse settings.configure( DEBUG=True, SECRET_KEY='badkey', ROOT_URLCONF=sys.modules[__name__], ) def index(request): return HttpResponse('Hello, World') urlpatterns = [ (r'^hello-world/$', index), ] Located at /smartQuiz/smartQuiz/hello.py, where smartQuiz is the root directory of my project. If I run python hello.py runserver from the directory where hello.py is located, the server won't start. What am I doing wrong? -
Django multiple upload images doesn't work
I'm trying to add a multiple upload, but where i upload 2 or more images can be added only one views with add files: def post_new(request): if request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): try: f = request.FILES['image'] post = form.save(commit=False) post.image.save(f.name, f) post.date = timezone.now() post.save() except MultiValueDictKeyError: post = form.save(commit=False) post.date = timezone.now() post.save() return redirect('home:index') else: form = PostForm() return render(request, 'home/edit_post.html', {'form': form, 'error_message': 'something error message'}) else: form = PostForm() return render(request, 'home/edit_post.html', {'form': form}) and form where i get image form: class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'text', 'image'] and I also tried this: image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) But it did not help own model where is the image: class Post(models.Model): title = models.CharField() date = models.DateTimeField(editable=True, null=True) text = models.TextField() image = models.ImageField(null=True, blank=True, upload_to='my-images') is_super = models.IntegerField(default=0) template edit_post: <form action="" method="POST" enctype="multipart/form-data">{% csrf_token %} {% if error_message %} <p><strong style="margin-left: 35%; color: red">{{ error_message }}</strong></p> {% endif %} <div class="input-group" style="margin-bottom: 10px; margin-left: 38.5%"> <label for="id_title" style="margin-left: 35%">title</label> <input style="text-align: center" value="{{ form.title.value }}" class="form-control" placeholder="****" id="id_title" name="title" type="text"> </div> <div class="input-group" style="margin-bottom: 10px; margin-left: 30%"> <label for="id_text" style="margin-left: 42%">text</label> <textarea style="resize: none; width: 500px; … -
AbstractUser extended custom User class, Admin page, trying to change user entry doesn't work, shows generic 'server error' message
This is the Django App I am working on: https://github.com/enlighter/ndl-question-papers-search-hub/tree/explore3/qp_search_project/searcher In this approach I have extended AbstractUser to create my User model and specified it in settings.py like AUTH_USER_MODEL = 'searcher.student'. This is how I have defined my admin.py : https://github.com/enlighter/ndl-question-papers-search-hub/blob/explore3/qp_search_project/searcher/admin.py. In my admin page, the entry for users shows Users and not student, when I click on the change option button in the admin page for the Users entry, and then I click on an entry to change, the url opened is : http://127.0.0.1:8000/admin/searcher/student/1/change/ And this shows a blank page with the message: A server error occurred. Please contact the administrator. Can anyone please help me with why this is happening and how to fix it? -
Cannot download file from Django template
I've got a Django template with the following code: {% for f in files %} <tr> <td> {{ f.file_name }} </td> <td> <a href="{{ f.path }}" download="{{ f.file_name }}"> <input type="button" value="Download"/> </a> </td> </tr> {% endfor %} However when I try to download the file in Chrome I get a "Failed - No File" error, although the file does exist in my system. If I copy the link to another tab I can download it just fine. There's probably some kind of problem with the address that is contained in the download button? Any help would be appreciated. -
Django: How to get parameters from QuerySet
Consider the following Django model: class SomeModel(models.Model): some_var = models.IntergerField() Whats the best way to get an array of a models parameters from a search results? Example (not working of course): a = SomeModel.objects.all().some_var would give something like [3, 4, 1, 9, 1, 2] -
Django pagination - how to redirect back to a ListView and a page number
In a the ListView I render a table using the Paginator with paginate_by = 5. In each row I have a Button that opens the UpdateView. After a successful update I'm back on my ListView but always on the first page. How can I change the success_url so that I'm back on the page number, from where I opened the UpdateView? Is there a proper way in Django to solve this? #views.py class Orders_list(ListView): model = Order context_object_name = "orders" queryset = Order.objects.all() paginate_by = 5 template_name = "orders/orders_list.html" class Orders_update(UpdateView): model = Order form_class = Order_UpdateForm template_name = "orders/orders_update.html" #success_url = '../../../orders/' success_url = reverse_lazy('orders') #urls.py urlpatterns = [ url(r'^orders/$', Orders_list.as_view()), url(r'^orders/detail/(?P<pk>\d+)/$', Orders_detail.as_view()), ] #forms.py class Order_UpdateForm(forms.ModelForm): class Meta: model = Order fields = ['order_text', 'customer', 'cyclist'] def __init__(self, *args, **kwargs): super(Order_UpdateForm, self).__init__(*args, **kwargs) self.fields['cyclist'].queryset = Cyclist.objects.filter(active=True) #models.py class Order(models.Model): customer = models.ForeignKey('Customer') cyclist = models.ForeignKey('Cyclist') order_text = models.CharField(max_length=200) pick_up = models.CharField(max_length=200) destination = models.CharField(max_length=200) created_date = models.DateTimeField(default=timezone.now) changed_date = models.DateTimeField(blank=True, null=True) def created(self): self.changed_date = timezone.now() self.save() def __str__(self): return self.order_text class Customer(models.Model): company_name = models.CharField(max_length=200) created_date = models.DateTimeField(default=timezone.now) changed_date = models.DateTimeField(blank=True, null=True) def created(self): self.changed_date = timezone.now() self.save() def __str__(self): return self.company_name class Cyclist(models.Model): lastname = models.CharField(max_length=20) … -
How to pass variable from save method to view in Django?
I need to display message with information if form was successfuly saved in database. Since there are many different forms in my website I want to write custom save method and pass variable to view every time save method was called. I tried to use global for creating global variable when saving and then catch it in view and pass to template. def save(self, *args, **kwargs): global some_var some_var = True super(ModelName, self).save() But this does not allow me to get some_var in view after I save model. I understand that making variables global is not best practice but could not figure out anything better. -
Docker container in Djago memory leak
I'm having a horrid issue with a django container - it keeps leaking for some reason and I can't figure out why. I have double checked that DEBUG = False so we're not storing any of the queries. I tried using guppy and executing it from inside the container - but nothing piles up in the heap there. The structure in htop can give a hint as to what is happening but I'm truly stuck at how to debug this further: I also have a Celery worker running on the same server but it seems to be working perfectly fine, but it could be the one generating the extra processes when executing tasks? -
Django-CMS custom plugin not showing data in published pages
I created a custom plugin for my project in Django/Django-CMS and the plugin has a list of testimonials that the user pick when adding the plugin to the page. The model is this: class TestimonialsPlugin(CMSPlugin): n_testimonials = models.PositiveIntegerField( verbose_name=_('Number of Testimonials'), default=5) speed_autoplay = models.PositiveIntegerField( verbose_name=_('Speed of slider (milliseconds)'), default=3000) picked_testimonials = models.ManyToManyField(Testimonials, verbose_name=_('picked_testimonials'), blank=True, null=True) In the edit mode I can se the testimonials in my page and I can publish without errors but when I see the published page the testimonials doesn't show. The plugin template is being rendered but the picked_testimonials gives None. Here's the template: <div class="max-width1440 block clearfix relative"> <div class="small-only-text-left small-12 small-offset-0 medium-text-center medium-offset-1 medium-10 large-offset-1 large-10 column pt-px60 pb-px40 pl-px40 pr-px40 slider-testimonials"> {% for testimonial in instance.picked_testimonials.all %} {% if forloop.counter0 < instance.n_testimonials %} <div class="slider column"> <blockquote class="acta_mediumitalic size36 pl-px80 pr-px80 line-height140"> {% render_model testimonial "description" %} </blockquote> <div class="mt-px30"> <p class="acta_book size20 softblack">{{ testimonial.author }},<span>{{ testimonial.city }}</span> </p> </div> </div> {% endif %} {% endfor %} </div> </div> -
Use a Max inside a Q query in Django
I am using Django Q objects to automatize the construction of complex queries from a textual description. In some of my queries, I need to combine classic Q queries, with Max operator as in: Book.objects.filter(Q(....) & Q(...) ....).aggregate(Max('price')) Is there a way to express the Max filter as a Q() filter, so that I can use a simple chain of: filter(Q(...) & Q(...) & Qmax(...)) which would be more convenient in the frame of my query-generator algorithm -
Django Rest Framework - image serializer returns url with escape characters
I try to save an Image using DRF. It saves but in response after saving I receive broken link because of escape characters. Response after saving looks like this { "profilePic" : "http:\/\/127.0.0.1:8000\/media\/Images\/profilePic_MnPwLVh.jpg", "user" : 31 } My serializer and view class ProfilePicCreateSerializer(ModelSerializer): profilePic = serializers.ImageField(max_length=None, use_url=True) class Meta: model = ProfilePic fields = [ 'user', 'profilePic' ] read_only_fields = ('user',) class ProfilePicCreateAPIView(CreateAPIView): queryset = ProfilePic.objects.all() serializer_class = ProfilePicCreateSerializer permission_classes = (IsAuthenticated,) parser_classes = (MultiPartParser, FormParser,) def perform_create(self, serializer): serializer.save(user=self.request.user) What can I do in order to get links in correct way, that will have no need to do additional processing in order to use ?