Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin inline to model's related model's related model
I have two models that have foreign keys to the User table. class Device(models.Model): user = models.ForeignKey(User) class Client(models.Model): user = models.ForeignKey(User) So, is it possible to show an Inline form in the Client's admin that shows the Devices that are related to the Client's User? -
How do i print data from a database in column format?
I have created a models.py file and created a format for my table. how can I print this out on a web page below. After this i would like to compare it to other data in the database. the data inputted is done via radio buttons ranging via 1-4 (an example of the database layout is attached) I believe is uses something similar to Objects.get? I could be wrong models.py class Question(models.Model): name = models.CharField(max_length=10, primary_key=True) question1 = models.CharField(max_length=50, choices=Question1_CHOICES) question2 = models.CharField(max_length=50, choices=Question2_CHOICES) question3 = models.CharField(max_length=50, choices=Question3_CHOICES) question4 = models.CharField(max_length=50, choices=Question4_CHOICES) question5 = models.CharField(max_length=50, choices=Question5_CHOICES) question6 = models.CharField(max_length=50, choices=Question6_CHOICES) question7 = models.CharField(max_length=50, choices=Question7_CHOICES) question8 = models.CharField(max_length=50, choices=Question8_CHOICES) question9 = models.CharField(max_length=50, choices=Question9_CHOICES) question10 = models.CharField(max_length=50, choices=Question10_CHOICES)` I have also added the views.py which stores the data just in case. Views.py def question1(request): question_form1 = QuestionForm1 if request.method == 'POST': form = QuestionForm1(request.POST) if form.is_valid(): form.save() # saves to database return render(request, 'music/compare.html') else: return render(request, 'music/failed.html') return render(request, 'music/question1.html', locals()) -
how much time it takes google update indexed page
Many of my website pages indexed with wrong format of url (I used space instead of - in url) so when I found out, I tried to change those mistake but google shows wrong url too. (after a month) right-format: http://doresa.ir/comp/h/%D8%A2%D8%B2%D9%85%D8%A7%DB%8C%D8%B4%DA%AF%D8%A7%D9%87-%D9%84%D8%A7%DB%8C%D8%AA%DA%A9 wrong-format: http://doresa.ir/comp/c/%D8%A2%D8%B2%D9%85%D8%A7%DB%8C%D8%B4%DA%AF%D8%A7%D9%87%20%D9%84%D8%A7%DB%8C%D8%AA%DA%A9/%D8%A8%D8%B1%D9%86%D8%A7%D9%85%D9%87%E2%80%8C%D9%86%D9%88%DB%8C%D8%B3%DB%8C -
Django can't populate a table correctly
Im working on a webapp and i have stumbled in a problem. I need to populate a table where in the table head i have a question and on the first column i have the student number, and on each cell i want to display the qscore if it exists, else display a button. I have the following files. views.py def ExamDetail(request, exam_id): exam = get_object_or_404(Exam, pk=exam_id) questionitems = QuestionItem.objects.filter(exam_id= exam_id).values_list('id', flat=True) questionlist = QuestionItem.objects.filter(exam_id= exam_id) studentexams = StudentExam.objects.filter(student_exam = exam_id).values_list('student_id', flat=True) questions = Question.objects.filter(pk__in=questionitems) students = Student.objects.filter(pk__in=studentexams) studentexamitems = StudentExamItem.objects.filter(student_id__in = studentexams, qitem_id__in = questionitems) context = { 'exam': exam, 'questions': questions, 'questionitem': questionitems, 'questionlist': questionlist, 'students': students, 'studentexamitems': studentexamitems, } return render(request, 'evaluation/exam_detail.html' , context) models.py class Student(models.Model): student_number = models.CharField(max_length=20, unique=True) student_name = models.CharField(max_length=150) student_class = models.CharField(max_length=40) def __iter__(self): return self.pk class QuestionItem(models.Model): exam_id = models.ForeignKey(Exam, on_delete=models.CASCADE) question_id = models.ForeignKey(Question, on_delete=models.CASCADE) question_pontuation = models.FloatField(default=0.0, validators = [MinValueValidator(0.0), MaxValueValidator(20.0)]) def __iter__(self): return self.pk class StudentExamItem(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) qitem_id = models.ForeignKey(QuestionItem, on_delete=models.CASCADE) qscore = models.FloatField(default=0.0, validators = [MinValueValidator(0.0), MaxValueValidator(100.0)]) def __iter__(self): return self.pk and finally the sections of the html where im displaying the table <table style="width:100%"> <tr> <th>Number: </th> {% for quest in questionlist %} <th> … -
Update page with item details on click in Django
I am new to ajax and know I need to use this in order to complete what I am trying to do but can't seem to figure it out. I have a list of companies, and I want to display details about a company on the page when they click on the table row. When the user clicks on a different row, I want the details to change to the details on the new company that was clicked. HTML: {% block content %} <div class='container'> <h3>Hello, </h3> </div> <div class='col-md-6'> <div class='panel panel-primary'> <div class='panel-heading'> <h3 class='panel-title'>Call List</h3> </div> <div class='panel-body' style="max-height: 70em ;overflow-y: scroll;"> <table class="table table-striped table-hover "> <thead> <tr> <th>Company Name</th> <th>Other Information</th> </tr> </thead> <tbody> {% for item in companies %} <tr onclick='UpdatePKFunction({{ item.pk }})'> <td>{{ item.CompanyName }}</td> <td>{{ item.LineOfBusiness }}</td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> <script> function UpdatePKFunction(pk) { pk = pk $.ajax({ url: '/updateDetails', success: function(pk) { $('#DetailView').html(pk); } }); }; </script> <div class='col-md-4'> <div class='panel panel-info'> <div class='panel-heading'> <h3 class='panel-title'>Company Information</h3> </div> <div class='panel-body' id='DetailView'> </div> </div> </div> {% endblock %} What I want to insert: {% for item in companies %} {% if item.pk == pk %} <td> … -
How to create an endpoint for a ManyToMany relationship?
models.py class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(blank=True) class Publication(models.Model): title = models.CharField(max_length=200) pub_date = models.DateField(null=True, blank=True) author = models.ManyToManyField(Author) serializers.py class AuthorSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Author fields = ('first_name', 'last_name', 'email') class PublicationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Publication fields = ('title', 'pub_date', 'author') urls.py router = routers.DefaultRouter() router.register(r'authors', views.AuthorViewSet) router.register(r'publications', views.PublicationViewSet) urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] What I want As you can see, my two models (Author and Publication) are connected with a many to many relationship. What I want is be able to access all the publications of a specific author when I go to api/authors/[id]/publications. How can I do that? -
Why does Django return postgres JSONField value as string?
Environment: Django 1.10.6 psycopg2 2.7.1 PostgreSQL 9.6.2 installed via Homebrew on macOS Sierra Python 3.6.0 installed via Homebrew Example model: from django.db import models from django.contrib.postgres.fields import JSONField class Foo(models.Model): data = JSONField() When I try to create an object, everything works as expected: from myapp.models import Foo x = Foo() x.data = {'key1': 'value1'} x.save() And querying works as expected: Foo.objects.filter(data__key1='value1').count() # 1 However, when I try to retrieve that data from the object, the value of the .data attribute is a string: from myapp.models import Foo x = Foo.objects.get(id=1) x.data # '{"key1": "value1"}' type(x.data) # str I would expect to get back a dict here. The problem gets recursively worse when trying to save back the object x.save() x = Foo.objects.get(id=1) x.data # '"{\\"key1\\": \\"value1\\"}"' x.save() x = Foo.objects.get(id=1) x.data # '"\\"{\\\\\\"key1\\\\\\": \\\\\\"value1\\\\\\"}\\""' -
How can I make a disable field with modelform after django 1.9
I'd like to create disabled field with ModelForm on django 1.11. I read django has "disabled field options" since 1.9. However, I can not understand how do I define disabled field with ModelForm. Could you tell me how to create disabled field with ModelForm please ? Here is my models.py, forms.py and views.py class my_model(models.Model) name = models.CharField(max_length=10,) title = models.CharField(max_length=10,) date = models.DateField(default=date.today,) def __str__(self): return u'%s' % (self.name) class my_modelform(ModelForm): class Meta: model = my_model fields = ['name', 'title', 'date'] widgets = { 'date': DateWidget(usel10n=True, bootstrap_version=3,), } disabled = [ 'name' ] class my_UpdateView(UpdateView): model = my_model form_class = my_modelform template_name = "update_form.html" success_url = "success.html" Although, I changed the "disabled = {'name' : True} instead of [ 'name' ], it doesn't work. -
Django get query_params from one view and redirect to another one
I have this dict saved in self.request.query_params: query_params: <QueryDict: {u'category_id': [u'14'], u'retailer_id': [u'12']}> I have this regular url that ends without a slash: url(r'^stocklist$', product_views.StockItemListView.as_view(), name="stocklist") How do I redirect to that url and send the keys and values in the query_params dict? redirect("misuper:stocklist", kwargs=query_params) # Doesn't work -
Django: Certain aspects of context not passing properly in live environment vs. local
I'm having a strange issue where certain values in a context from my views are not passing to the template in a production environment only. Take the following view: def products(request,cat_id=0): if cat_id: cat = ProductCategory.objects.filter(pk=cat_id) all_products = Product.objects.filter(product_category=cat_id) return render(request, 'drsite/products.html', {'all_products': all_products, 'product_category': cat_id}) else: all_products = Product.objects.all() return render(request, 'drsite/products.html', {'all_products': all_products}) The product_category value is not passing in a live environment, although is passing just fine in my local environment. The goal of that value is to trigger an active state on an element in the page in addition to rendering the products on the page. Worth noting is the products object is passing fine and rendering as expected. -
Weird Python error
This error: cancel_agreement() missing 1 required positional argument: 'agreement_id' appeared while executing this method: def force_cancel(self): api = model_from_ref(self.processor.api) api.cancel_agreement(self.subscription_reference) # transaction.cancel_subscription() # runs in the callback Here is cancel_agreement() method: def cancel_agreement(self, agreement_id, is_upgrade=False): note = _("Upgrading billing plan") if is_upgrade else _("Canceling a service") r = self.session.post(self.server + '/v1/payments/billing-agreements/%s/cancel' % agreement_id, data='{"note": "%s"}' % note, headers={'content-type': 'application/json'}) if r.status_code != requests.codes.ok: raise RuntimeError(_("Cannot cancel a billing agreement at PayPal. Please contact support.")) I don't understand why the error happens: It is calling a two-argument function (api and self.subscription_reference) and its definition is also two required arguments (self and agreement_id). Sadly I can't show the entire code, because my business partner is against releasing it open source. -
Have python find and evaluate all decorated functions in codebase
I'm trying to have functions in my code base that are callable by a unique identifier, for this I created a decorator that registers the function global FUNCTION_REGISTRY FUNCTION_REGISTRY = {} class FunctionAlreadyRegistered(Exception): pass def register_function(function_identifier, function): global FUNCTION_REGISTRY if function_identifier not in FUNCTION_REGISTRY: FUNCTION_REGISTRY[function_identifier] = function else: raise FunctionAlreadyRegistered def call_registered_function(function_identifier, *args, **kwargs): global FUNCTION_REGISTRY if function_identifier in FUNCTION_REGISTRY: FUNCTION_REGISTRY[function_identifier](*args, **kwargs) class EventHandler(object): def __init__(self, identifier): self.identifier = identifier def __call__(self, original_func): decorator_self = self def wrappee(*args, **kwargs): original_func(*args, **kwargs) print "REGISTER FUNCTION", decorator_self.identifier register_function(decorator_self.identifier, wrappee) return wrappee and then I apply this decorator like this @EventHandler(identifier="something.task-created-handler") def task_created_event_handler(pk=None, *args, **kwargs): pass this allows me to easily do the following call_registered_function("something.task-created-handler",argument="value") however this decorator is only evaluated when some other file imports this file intentionally, I'd like to evaluate all this decorator through my codebase to register all identified functions Is there a way to get python to evaluate all this decorators when the runtime starts in a seamless way? -
Django, Python - How do I create a field where the user can only choose a number between 10000 and 100000?
I'm writing a form that a user can fill in in a browser. One of the questions involves selecting a number between 10000 and 100000. How would I go about prompting the user to do this? If they don't, I want a message to pop up in order to get them to actually pick a number between 10000 and 100000. The variable that deals with this particular figure is called borrowing. The data on the form is currently saved in a sqlite3 table. Here is a my models.py: from django.db import models from django.core.validators import MinValueValidator from django.core.validators import MaxValueValidator class User(models.Model): #to store user data firstname = models.CharField(max_length=100) surname = models.CharField(max_length=100) email = models.CharField(max_length=100) telephone_number = models.CharField(max_length=15) company_name = models.CharField(max_length=100) company_street_address = models.CharField(max_length=100) city = models.CharField(max_length=100) postcode = models.CharField(max_length=10) company_number = models.CharField(max_length=9) filter_choices = ( ('retail', 'Retail'), ('professional services', 'Professional Services'), ('food & drink', 'Food & Drink'), ('entertainment', 'Entertainment'), ) business_sector = models.CharField(max_length=100, choices=filter_choices) days = models.CharField(max_length=5) reason_for_loan = models.CharField(max_length=2000) #borrowing = models.IntegerField(choices=[(i, i) for i in range(1, 1)], blank=True) #borrowing = models.IntegerField((validators=[MaxValueValidator(100),MinValueValidator(1)]) borrowing = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(100)]) if 10000 <= borrowing <= 100000: #borrowing = models.CharField(max_length=100) def __str__(self): return self.firstname As you can see I've tried a bunch of stuff … -
how i can send a var in a $(var).*** var="#tag" ,html jquery
i need send information a my Htm. for example <script> $(document).ready(function() { var = "'#"+result.tag+"'" // var = '#tag_dinamy' // then i need append to my html $(var).append("<h1> Good </h1>") }; </script> <p id="tag_dinamy"> </p> I don't need this. $('#tag_dinamy').append("<h1> Good </h1>") //y need pass in a $(var) -
Django nested/sub organizations
I am just starting to develop an app where multiple users can upload and store files, Each user will be assigned an organization and each organization has many "sites"/sub organizations. If they are in the top level organization they should be able to see all files in the top level organization and all sub organizations/"sites". If the user is only assigned to a sub site they should only be able to see data for that site. Does Django's built in user system support this, is there a libray/app that does support this, do I need to build this part of the system from scratch? If I build this from scratch what would be the best way, extend the current user system or just create tables in the app and associate users to those tables? Note: I have a reasonable amount of experience with python but very little with django. -
Trying to compare non-ordered queryset against more than one ordered values django
This unit test fails with the following exception: def test_vote_form_with_multiple_choices_allowed_and_submitted(self): """ If multiple choices are allowed and submitted, the form should be valid. """ vote_form = VoteForm({'choice': [1, 2]}, instance=create_question('Dummy question', -1, [Choice(choice_text='First choice'), Choice( choice_text='Second choice')], allow_multiple_choices=True)) self.assertTrue(vote_form.is_valid()) self.assertQuerysetEqual(vote_form.cleaned_data['choice'], ['<Choice: First choice>', '<Choice: Second choice>']) ValueError: Trying to compare non-ordered queryset against more than one ordered values What am I doing wrong? -
Django registration timeout
When submitting the registration form for a new user, the page keeps loading for a long time (30 sec) and finally stops with a timeout (HTTP Code 504). On the development server, it works without any problems. Neither of the log files (error and access) contains an entry about the form submission (POST request). Any ideas how to solve this or get some more information about the problem? Thank you! The application runs on an nginx 1.6.2 with an apache proxy. We use the django registration (version 2.2) with Django 1.10. -
show django form wizard in a jquery dialog box
I am using a combination of django-crispy-forms, jquery and django-form-wizards to display some forms. I can show a simple ModalForm in a jquery dialog and this works quite well. However, I am having trouble showing a wizard form in a jquery dialog. So, if I have one form as follows: class DummyForm(ModelForm): class Meta: model = DummyModel fields = ['name', 'description', 'time_points'] def __init__(self, *args, **kwargs): super(DummyForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-2' self.helper.field_class = 'col-sm-10' self.helper.form_tag = False self.helper.layout = Layout( Field('name'), Field('description'), Field('time_points')) #, #ButtonHolder( # Submit('submit', 'Submit', css_class='button white') #)) I am able to fill it using some data and show it to the user in an editable form as: @login_required(login_url="login/") def populate_review_form(request): pk = request.GET.get('pk') rec = DummyModel.objects.get(pk=pk) df = DummyForm(model_to_dict(rec)) return render(request, 'reviewform.html', {'DummyForm': df}) And my reviewform.html simply shows it as: {% load crispy_forms_tags %} {% crispy DummyForm %} This works fine and I can also embed it in a jquery dialog and it works. Now, I want to actually have a form wizard, so in addition I have a second form as follows: class OtherForm(ModelForm): class Meta: model = DummyModel fields = ['more_text'] def __init__(self, *args, **kwargs): super(OtherForm, … -
django loop through queryset and add a new property
I have two tables that I joined with a foreign key, I want to get all of the fields from one model and just one of the fields from the other model, how to I add on that field? msos = Msos.objects.using('data').filter(id=121497).prefetch_related('mso_universe') for i in msos: for x in i.mso_universe.all(): # I want to add x.population to each i data = serialize('json', data) return HttpResponse(data) -
How to apply a characteristic to a template variable un Django?
i'm working with Django, and i'm doing and user system for a web, but i'm having a problem with the validation of the form. When i call form.is_valid(), before the save, it always give me false, and i don't know why. I have seen a lot of examples online, and everyone do it like this, and i have never worked with a user register system, so i really don't know what could be making that my forms are always invalid. This is the code of forms.py: from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class MyUserCreationForm(UserCreationForm): email = forms.EmailField(required = True) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(MyUserCreationForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() return user This is the code of views.py: class UserForm(View): def get(self, request): form = MyUserCreationForm() context = {"form":form} return render(request, "register.html", context) def post(self, request): form = MyUserCreationForm(request.POST) if form.is_valid(): form.save() maybe = { "hello":"world"} return JsonResponse(maybe) This is supposed to add the users to the database, but it never pass the form.is_valid(). What could be the problem? -
How to create a timestamp on submit in Django class based views for Update?
I'm new to class based views in Django and was using a simple UpdateView CBV. The view has many fields that is being displayed on a template, except one; the Date field. How do I dynamically save this field when the submit button is clicked? I only want to save date if it is Null or Blank. This is my code: class ReviewsEdit(UpdateView): model = ProductReview fields = ['title', 'body', 'score', 'responder_name', 'response'] template_name = 'review_system/review_edit.html' context_object_name = 'review' The ProductReview model has all the above fields with another Date field, I'd like to save it with timestamp data when the submit button was clicked - only if it is blank when submitting. Is this possible with CBV? -
Convert my Django my website on HTTPS in DigitalOcean
I have a website built with Django in DigitalOcean and I would like to show the https lock when you visit the website. Which are the exact steps to do that? Which files do I have to modify and which modifications do I have to do? I tried to search on Google and DigitalOcean forum but I think I'm missing something because the things I've tried didn't work. -
Django checkbox field
I am trying to add a checkbox that if ticked will make a attribute in my model false. My model is: class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User) public = False My forms.py (where the checkbox should go) is: class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['text'] labels = {'text': ''} And my function: def topics(request): """Show all topics.""" topics = Topic.objects.filter(owner=request.user).order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) Could you please tell me what I need to change in order that when a checkbox in forms is checked, the public variable becomes True, and then the function Topics displays public topics as well as just the owners. Thanks Milo -
form wizard does not show the next button
I am trying to use django form wizard where I have a form split over multiple pages. I have bene trying to piece together something from their documentation. So, currently, I have the following forms: class DummyForm(ModelForm): class Meta: model = DummyModel fields = ['name', 'description', 'time_points'] def __init__(self, *args, **kwargs): super(DummyForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-2' self.helper.field_class = 'col-sm-10' self.helper.layout = Layout( Field('name'), Field('description'), Field('time_points')) class OtherForm(ModelForm): class Meta: model = DummyModel fields = ['more_text'] def __init__(self, *args, **kwargs): super(DummyForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-2' self.helper.field_class = 'col-sm-10' self.helper.layout = Layout( Field('More_text')) I have the views and urls configured as follows: views.py from django.http import HttpResponseRedirect class ContactWizard(SessionWizardView): def get_template_names(self): return "test.html" def done(self, form_list, **kwargs): return HttpResponseRedirect('index') urls.py url(r'^contact/$', views.ContactWizard.as_view([DummyForm, OtherForm])) Finally, my test.html template looks like: {% extends "base.html" %} {% load i18n %} {% block content %} <p>Step {{ wizard.steps.current }} of {{ wizard.steps.count }}</p> <form action="." method="post">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} {% if … -
Django template. Reply-To header
I want to change email's header Reply-to from Django template, because of I use third-party library, which sends email in different cases, and I have no access to it's source code. I guess, block should be exist, but I didn't find similar to it.