Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-bleach import and deploy to heroku error
I am using Django 1.11. I'm using in my Django application the django-bleach that was installed with: pip install django-bleach So, when I would use it, I've gotten an import error that I fixed, the error occurs in Django version 1.6 or 1.8+, I guess. You can see here what I did. It worked and I continue the development. The problem is: now I am trying to deploy my application in Heroku, but the same error occurs and the import has to be fixed. So, I think that my repository should have the requirements.txt with the correct version of django-bleach (the one that have my commit), this way it would works properly, right? So, I forked the repository, commited the modification and created a requirements.txt with this text: -e git+https://breno_asrm@bitbucket.org/breno_asrm/django-bleach.git#egg=django-bleach Then I created a new virtual env and installed with pip install -r requirements.txt I thought it would install the same thing as before, just adding my modification, but it was not what happened. For instance, now my lib directory (env/lib/python3.5/site-packages/ ) doesn't have django_bleach folder. So, how could I fix it in a way that I don't have to modify the heroku virtualenv that is created automatically (if it's … -
Django Rest_Framework tutorial gives unexpected error
I have tried over and over again, but it still gives the same thing. Couldn't find out the cause -
Django form with different models
I have a question, how to make a form in Django using 3 different models. This is my models: class User(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=50) city = models.CharField(max_length=50) class Team(models.Model): team_name = models.CharField(max_length=250) city = models.CharField(max_length=50) class GameCategories(models.Model): CATEGORIES = ( ('Senior', 'Senior'), ('Middle', 'Middle'), ('Junior', 'Junior'), ) category = models.CharField(max_length=16, choices=CATEGORIES) I want to create a form using <select><option></option></select> with above models that would look like this: <select class="form-control"> <option value=""></option> <option value="user.id">user.first_name + user.last_name</option> <option value="user.id">user.first_name + user.last_name</option> <option value="user.id">user.first_name + user.last_name</option> </select> <select class="form-control"> <option value=""></option> <option value="gamecat.id">gamecat.category</option> <option value="gamecat.id">gamecat.category</option> <option value="gamecat.id">gamecat.category</option> </select> <select class="form-control"> <option value=""></option> <option value="team.id">team.team_name</option> <option value="team.id">team.team_name</option> <option value="team.id">team.team_name</option> </select> and after filling form when user click submit button I want to send to another view all values (user id, game category id, team id). Actually I don't have idea how to do this. I guess that I should create a ModelForm. Could you please help me? -
django 2.0 using MySQL database
I was curious about using MySQL instead of SQLite for my Django project. Firstly, I would like to ask: where can I find an explicite guide of how to install MySQL with Django on Windows and if I use MySQL, will I type the exact type of code I would usually type in SQLite ? For example: class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() When you type this in Django, it gets converted to: CREATE TABLE "books_publisher" ( "id" serial NOT NULL PRIMARY KEY, "name" varchar(30) NOT NULL, "address" varchar(50) NOT NULL, "city" varchar(60) NOT NULL, "state_province" varchar(30) NOT NULL, "country" varchar(50) NOT NULL, "website" varchar(200) NOT NULL ); So the same will be when using MySQL ? -
Django forms - set specific data to the form object before modelForm saving
I have two ModelForm objects in the same view - Person and Adress. After user has bounded , I'm saving Person object. After saving, I want to use that saved object to set the ForeignKey of AdressForm, validate that form, and save. How can I set this? I mean field in ModelForm()? I've searched everywhere, and ewerywhere is said I have to save(commit=False), but I can't save unvalidated form! When I valid(), there is blank ForeignKey field! Here's my code: (I try to avoid create method, rather save) views.py class KontrahentCreate(LoginRequiredMixin, generic.View): template = 'escrm/kontrahent_form.html' context = dict() message = "Utworzono pomyślnie nowego kontrahenta" def get(self, request): self.context['form_kontrahent'] = KontrahentForm(initial={'czy_aktywny': True}) self.context['form_kontrahent'].fields['czy_aktywny'].widget = HiddenInput() self.context['form_adres'] = AdresKontrahentForm(initial={'czy_domyslny': True}) self.context['form_adres'].fields['czy_domyslny'].widget = HiddenInput() self.context['title'] = 'Dodaj nowego kontrahenta' return render(request, self.template, self.context) def post(self, request): kontrahent_form = KontrahentForm(request.POST) adres_form = AdresKontrahentForm(request.POST) if kontrahent_form.is_valid(): kontrahent = kontrahent_form.save() else: self.context['form_kontrahent'] = kontrahent_form return render(request, self.template, self.context) adres_form['kontrahent'].data = kontrahent.pk #AttributeError can't set attribute if adres_form.is_valid(): adres_form.save() else: self.context['form_adres'] = adres_form return render(request, self.template, self.context) messages.success(self.request, self.message) return HttpResponseRedirect(reverse_lazy('escrm:kontarhent-detail', kwargs={'pk': kontrahent.pk})) forms.py class KontrahentForm(ModelForm): class Meta(ModelForm): model = Kontrahent fields = '__all__' class AdresKontrahentForm(ModelForm): class Meta(ModelForm): model = AdresKontrahent fields = '__all__' widgets = { … -
Django: How to submit a form to either create new object or get an existing one?
Using django1.11.4. I am trying to make a page for adding an item to the database, however, to do this, I need to create/get several different objects, (product, manufacturer, supplier), whose forms make up part of the whole form for adding an item. In most case, there will be existing product, manufacturer and suppliers. So I want to retrieve the existing object and use that as the foreign key to relevant form. e.g. manufacturer is a foreign key of product. However, for all forms when I try submitting details for the existing object. e.g supplier. The is_valid fails. The error is: <ul class="errorlist"><li>supplier_name<ul class="errorlist"><li>Supplier with this Supplier name already exists.</li></ul></li></ul> Is there a way of submitting a form with 'existing data' so that I can get to pass on as a foreign key. Thank you for your time. class SupplierTestCase(FormTestCase, BasicTests): @classmethod def setUpTestData(cls): super(SupplierTestCase, cls).setUpTestData() cls.form = SupplierForm def setUp(self): super(SupplierTestCase, self).setUp() self.data = {'supplier_name_text': self.supplier_name} self.blank_data = { 'supplier_name_text': ['This field is required.'] } def test_valid_data(self): form = self.form(self.data) self.assertTrue(form.is_valid()) commit = form.save() self.assertEqual(commit.supplier_name_text, self.supplier_name) def test_get_data(self): form = self.form(self.data) self.assertTrue(form.is_valid()) if form.is_valid(): commit = form.save() self.assertEqual(commit.supplier_name_text, self.supplier_name) form = self.form(self.data) #The problem is below vvvv self.assertTrue(form.is_valid()) if … -
Paypal integration error
I am using django rest framework to integrate paypal. But I am always getting "Return to merchant error". Please help me in solving this issue. Following is the screenshot of the error. Now I am Indian buyer and I want to accept international payment in USD. I have used django-paypal with following codes. def paypal_process(request): try: host = request.get_host() paypal_dict = { 'business': PAYPAL_RECEIVER_EMAIL , 'amount': '1', 'item_name': 'Item_Name_xyz', 'invoice': 'Test Payment Invoice', 'currency_code': 'USD', 'notify_url': 'http://localhost:8000/api/payment/payment_notify/', 'return_url': 'http://localhost:8000/api/payment/payment_done/', 'cancel_return': 'http://localhost:8000/api/payment/payment_canceled/', } form = PayPalPaymentsForm(initial=paypal_dict) return render(request, 'paypal_process.html', {'form': form }) except Exception as e: return JsonResponse("Exception " + str(e), status = status.HTTP_406_NOT_ACCEPTABLE, safe=False) In settings.py I have following settings PAYPAL_RECEIVER_EMAIL = 'xyz@abc.com' PAYPAL_TEST = False The code works fine when PAYPAL_TEST = True. But it gives the above error when in production. -
Django, django-autocomplete-light does not work
I am trying django-autocomplete-light to make work on ZipCode model in admin, which should display list of boroughs it's related. Here are the models.py: class ZipCode(models.Model): code = models.CharField(max_length=24) borough = models.ForeignKey('Borough', on_delete=models.CASCADE) def __str__(self): return self.code class Borough(models.Model): name = models.CharField(max_length=120) def __str__(self): return self.name Creating a form from model ZipCode in forms.py: from dal import autocomplete from django import forms from .models import ZipCode class ZipForm(forms.ModelForm): class Meta: model = ZipCode fields = '__all__' widgets = { 'borough': autocomplete.ModelSelect2(url='borough_select') } In views.py query boroughs: from .models import Borough from dal import autocomplete class BoroughAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Borough.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs Registering in urls.py: from django.conf.urls import url from .views import BoroughAutocomplete urlpatterns = [ url( 'autocomplete/$', BoroughAutocomplete.as_view(), name='borough_select', ), ] and in admin.py: from .models import ZipCode from .forms import ZipForm class ZipAdmin(admin.ModelAdmin): form = ZipForm admin.site.register(ZipCode, ZipAdmin) The result is: I can query boroughs like http://localhost:8000/autocomplete/?q=Manhattan But in admin there are no choices to select (Boroughs already exist in db) Please, help to find out where the problem occurs -
django rest framework documentation
pls I need a link to django rest framework docs. the official site http://www.django-rest-framework.org is not going through. -
Django extended template is not loading base JS at time
I've in Django 1.11 a base.html which contains all the scripts references. Then, I've another page.html that extendes base.html with {% extends base.html %} and {% block content %} / {% endblock content %} tags. Well. In base.html I've a reference to Chartjs.js plugin. In page.html, if I try to call to Chart() function or just $ jquery, I get "function is not defined". If I open console debugger and try to call $ or just Chart(), it works. So I think that there's a problem with loading time. The page.html is rendered before the js are downloaded or requested! How can I solve it? I've done it before, I don't know what could be the problem. Thanks! -
How does the Django app registry work? [on hold]
I am working on my first larger Python project and I would like to store some instances globally. The problem is Python's import system, which is different to some languages I am used to work with (for example a static variable in Java only exists once during runtime). I found out that Django's app registry somehow always manages to give me the same instance of my AppConfig, even when importing it from different locations. This looks a bit strange to me, because it creates an empty registry in the end of the "registry.py": apps = Apps(installed_apps=None) So I couldn't find the answer in the code and the Debugger also isn't useful because it causes internal errors in Django. Could someone please explain how Django manages this? -
ImportError: No module named 'testApp123' django
I am trying a sample django app. I added some changes in view.py and am trying to run migrate but it is giving following error - athakur@athakur-Inspiron-7560:~/Documents/per_code/djangodemo$ python3 manage.py check Traceback (most recent call last): File "/home/athakur/.local/lib/python3.5/site-packages/django/apps/config.py", line 143, in create app_module = import_module(app_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'testApp123' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/athakur/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/athakur/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/home/athakur/.local/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/athakur/.local/lib/python3.5/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/athakur/.local/lib/python3.5/site-packages/django/apps/config.py", line 147, in create app_name, mod_path, cls_name, django.core.exceptions.ImproperlyConfigured: Cannot import 'testApp123'. Check that 'djangodemo.apps.testapp.apps.TestAppConfig.name' is correct. package is correct since if I change name in TestAppConfig class to testApp it says ImportError: No module named 'testApp'. Also following works - athakur@athakur-Inspiron-7560:~/Documents/per_code/djangodemo$ python3 Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from djangodemo.apps.testapp.apps import … -
Get select="multiple" behaviour with groups of radio buttons in POST request
When we have some code like this in HTML: <form action="" method="post"> <select name="answers" multiple="multiple"> <option value="1" >Question 1, Answer 1</option> <option value="2">Question 1, Answer 2</option> <option value="3">Question 1, Answer 3</option> <option value="4">Question 2, Answer 1</option> <option value="5">Question 2, Answer 2</option> </select> <input type="submit"> </form> I can select one item manually from the question 1 group, and one item from the question 2 group. When this is sent in a POST request, I get a POST array containing answers = [1, 3] or similar. I want to get the same behavior from groups of radio buttons, as this is a problem better suited to radio buttons. For example, if I do the following: <form action="" method="post"> <fieldset> <legend>Question 1</legend> <input name="answers" id="id_1" value="1" type="radio"> <label for="id_1">Answer 1</label> <br> <input name="answers" id="id_2" value="2" type="radio"> <label for="id_2">Answer 2</label> <br> <input name="answers" id="id_3" value="3" type="radio"> <label for="id_3">Answer 3</label> <br> </fieldset> <fieldset> <legend>Question 2</legend> <input name="answers" id="id_4" value="4" type="radio"> <label for="id_4">Answer 1</label> <br> <input name="answers" id="id_5" value="5" type="radio"> <label for="id_5">Answer 2</label> <br> </fieldset> </form> It doesn't actually let the user select more than one radio button at once. On the other hand, if I name the radio buttons answers[0] and answers[1], in POST, it … -
ImproperlyConfigured at /app/category/Python/
I wanna make a page which shows POST's models' contents is shown each category.For example, when I put Python link in <a href="{% url 'category' category.name %}"> in detail.html,only POST's models' contents with Python's category is shown in category.html.When I put Python link in category.html,I got an error,ImproperlyConfigured at /app/category/Python/ CategoryView is missing a QuerySet. Define CategoryView.model, CategoryView.queryset, or override CategoryView.get_queryset(). I wrote codes in views.py def top(request): content = POST.objects.order_by('-created_at')[:5] category_content = Category.objects.order_by('-created_at')[:5] page = _get_page(blog_content, request.GET.get('page')) return render(request, 'top.html',{'content':content,'category_content':category_content,"page":page}) class CategoryView(BaseListView): template_name = 'category.html' def get_queryset(self): category_name = self.kwargs['category'] self.category = Category.objects.get(name=category_name) queryset = super().get_queryset().filter(category=self.category) return queryset def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['category'] = self.category return context in urls.py urlpatterns = [ path('top/', views.top, name='top'), path('category/<str:category>/',views.CategoryView.as_view(), name='category'), ] in models.py class Category(models.Model): name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class POST(models.Model): title = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.title in top.html <div class="list-group"> <a href="#"> Category </a> <div> {% for category in category_content %} <a href="{% url 'category' category.name %}"> {{ category.name }} </a> {% endfor %} </div> </div> in category.html {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Category</title> </head> <body> <div> {% for … -
Django 1.11.6 AttributeError: 'DealerForm' object has no attribute 'forms'
I want my form, DealerForm, to save its contents to the database. However, the following comes up: Internal Server Error: /finance/14/record_input/ Traceback (most recent call last): File "C:\Python34\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "F:\NEA Computer Science\mysite\finance\views.py", line 46, in record_input if form.is_valid(): # check whether it's valid File "C:\Python34\lib\site-packages\django\forms\forms.py", line 183, in is_valid return self.is_bound and not self.errors File "C:\Python34\lib\site-packages\django\forms\forms.py", line 175, in errors self.full_clean() File "C:\Python34\lib\site-packages\django\forms\forms.py", line 385, in full_clean self._clean_form() File "C:\Python34\lib\site-packages\django\forms\forms.py", line 412, in _clean_form cleaned_data = self.clean() File "F:\NEA Computer Science\mysite\finance\forms.py", line 16, in clean for form in self.forms: AttributeError: 'DealerForm' object has no attribute 'forms' [07/Jan/2018 14:56:09] "POST /finance/14/record_input/ HTTP/1.1" 500 87806 What does this mean, and how can I solve it? views.py from django.http import HttpResponse from django.shortcuts import render, redirect from .models import Customer, Dealer from .forms import DealerForm from django.db.models import Q, F from datetime import timedelta from django.utils import timezone # Lists all dealers and links them to their welcome page def index(request): dealer_list = Dealer.objects.order_by('name') html = "<ol>" for dealer in dealer_list: html = html + … -
Mocking an HTTP request and forms.Form
So this is a part of the code I'm supposed to make test for: if APPLY_ACTION in request.POST: form = form_type(request.POST) if form.is_valid(): cleaned_data = {} for key, value in form.cleaned_data.iteritems(): if value is None or value == '': continue cleaned_data[key] = value Where form_type inherit from forms.Form and request is an http request. Now, I'm not sure exactly how to mock these two. Is it possible to give a specific line a return value? like for "form_type(request.POST)" return a specified dictionary? -
save() prohibited to prevent data loss due to unsaved related object: How to save related models together?
I have a form and a formset. Formset contains a column foreign key to form. However my forms are not saving and save() prohibited to prevent data loss due to unsaved related object error is being thrown. How could I save both these data together? here's my view: def purchaseOrderView(request): if request.method == 'POST': formset = POFormSet(request.POST) form = POHeaderForm(request.POST) print("POSTED") if form.is_valid() and formset.is_valid(): form.save() formset.save() messages.success(request,"VALID SUBMISSION") return render(request,'purchase_order.html',{'formset':formset, 'form':form}) else: return render(request, 'purchase_order.html', {'formset': formset, 'form': form}) else: formset = POFormSet() form = POHeaderForm() return render(request,'purchase_order.html',{'formset':formset, 'form':form}) here's my model structure: class POHeaderModel(models.Model): date = models.DateTimeField(blank=False, default=timezone.now) reference = models.CharField(validators=[alphanumeric], max_length=25, blank=True, null=True) supplier = models.ForeignKey(SuppliersModel, on_delete=models.PROTECT) note = models.CharField(validators=[alphanumeric], max_length=300, blank=True, null=True) total = models.DecimalField(decimal_places=2, max_digits=10, validators=[MinValueValidator(0)]) class POBodyModel(models.Model): PO = models.ForeignKey(POHeaderModel, on_delete=models.PROTECT) item_number = models.CharField(validators=[alphanumeric], max_length=25, blank=True, null=True) description = models.CharField(validators=[alphanumeric], max_length=100, blank=True, null=True) quantity = models.IntegerField(blank=True, null=True) rate = models.DecimalField(decimal_places=2, max_digits=10) discount = models.DecimalField(decimal_places=2, max_digits=10,blank=True, null=True) total = models.DecimalField(decimal_places=2, max_digits=10, blank=False) There are a lot of examples out there in various blogs and in here in questions using with transaction.atomic():. But none works or may be doesn't suit my scenario. Any advise? -
Get The Data based on start date and date date
Guys I have two tables one is of order table which has Tickets table which has time field for ticket_date. Other Table is of Customer table which also has foreign key relationship with assignee (Manager)table like each customer has start date and end date for assignee to manager If I want to get Data using ORM in Django like How many ticket closed buy assignee(Manager) I just wanted to pick Start date end date of reporting date over the given date range Customer reporting from 1 to 10th of month with manganer M1 in this span he placed 2 order and after 10th of the month reporting manger changes to M2 and placed order 4 So how I can make sure it’s not counted for whole date range -
in Django Admin - save() prohibited to prevent data loss due to unsaved related object
I have 2 models, Company and CompanyLogo: class CompanyLogo(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) logo = models.ImageField(upload_to=file_upload_to) Instead of using an inlineformset I modified the form(used in Admin and outside DjangoAdmin) class CompanyModelForm(forms.ModelForm): logo = forms.ImageField(widget=CompanyLogoWidget, required=False) class Meta: model = Company def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Check if is update/edit if self.instance.pk: logo = CompanyLogo.objects.get(company=self.instance) self.fields['logo'].widget = CompanyLogoWidget(logo=logo) def save(self, commit=True): company = super().save(commit=commit) CompanyLogo.objects.update_or_create(company=company, defaults={"logo": self.cleaned_data['logo']}) return company The error appears only in Django Admin, not outside Django Admin form. I checked the questions on the forum related to mine, but in none of them the error was in Admin, and I save the Company model first calling: super().save(commit=commit) -
Django nested queries
In Django I'm trying to achieve a nested SQL structure like this without using raw queries: SELECT id, session_hash, user_id, price_type_id, room_category_id, check_in_date, price, captured_date FROM (SELECT p.*, Row_number() OVER (partition BY check_in_date, price_type_id, room_category_id ORDER BY captured_date DESC) AS rn FROM dashboard_prices p WHERE room_category_id = 1 AND price_type_id = 1 AND check_in_date >= '2018-01-01 00:00:00' AND check_in_date <= '2018-01-02 00:00:00') p WHERE rn = 1 I couldn't figure out how to achieve that by using "normal" query expressions in Django. Model: class Prices(models.Model): session_hash = models.CharField(max_length=32, blank=False, null=False) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, null=False) price_type = models.ForeignKey(PriceTypes, on_delete=models.CASCADE, blank=False, null=False) room_category = models.ForeignKey(RoomCategories, on_delete=models.CASCADE, blank=False, null=False) check_in_date = models.DateTimeField(blank=False, null=False, db_index=True) price = models.IntegerField(blank=False, null=False) captured_date = models.DateTimeField(default=timezone.now, blank=True) row_number = 'row_number() OVER (PARTITION BY check_in_date, price_type_id, room_category_id ' \ 'ORDER BY captured_date DESC)' I achieved already to get the inner query running by: price = Prices.objects.annotate(rn=RawSQL(Prices.row_number[])) .filter(room_category_id=req['room_category_id'], price_type_id=req['price_type_id'], check_in_date__gte=check_in_date, check_in_date__lte=check_out_date) But filtering after this brings only errors: django.db.utils.DatabaseError: Window function is allowed only in SELECT list and ORDER BY clause when adding: .filter(rn=1) Is there a possibility to achieve that? Thanks! -
Redirect Django to the same spot in the page after post
I have a 2 buttons in my website - 1. Edit entry 2. Delete Entry. The problem is, after I click Confirm for the deleting or editing, the page refreshes and get all the new information but it loads the page from the beginning (Upper side of the page) Since my page is very long with a lot of entries.... I want that after I click "confirm" it will redirect the user to the same spot he clicked in the page so he wouldn't need to roll the mouse to go down the page again and again.. Anyone knows? views.py - class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() forms = {} if query: posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query)) else: posts = serverlist.objects.all() for post in posts: forms[post.id] = HomeForm(instance=post) args = {'form' : form,'forms': forms, 'posts' : posts} return render(request, self.template_name,args) def post(self,request): form = HomeForm(request.POST) posts = serverlist.objects.all() forms = {} if form.is_valid(): # Checks if validation of the forms passed post = form.save(commit=False) post.save() messages.success(request,'{0} has been added successfully!'.format(post.ServerName)) return redirect('serverlist') messages.error(request,'Servername is required, please refresh the page … -
how to call variable in context at template in Django
I added calculation logic in view.py and want to pass the result to html template. I am trying to add calculation result to get_context_data method as below. However, it seems that variable in template is not recognizing the context_data given by view. Can anyone tell me where I am wrong and how I can fix it? view.py class DetailView(DetailView): model = html template_name = 'project_detail.html' def calcOTTV(self,data): glasspath = data["object"].loc.glass[6:].replace("static","data") opaquepath = data["object"].loc.opaque[6:].replace("static","data") value,table=ottv.main(glasspath,opaquepath) return [value,table] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) temp = self.calcOTTV(context) context["ottv"]=temp[0] <=I expected that this key is passed to html template return context html template <div class="row"> <h5>OTTV value</h5>{{object.ottv}} <=nothing is shown in browser </div> -
Error static files trying to push django app to heroku
I am trying to push my django app into heroku but I am getting that kind of error : emote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing requirements with pip remote: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/comm ands/collectstatic.py", line 199, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/comm ands/collectstatic.py", line 124, in collect remote: handler(path, prefixed_path, storage) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/comm ands/collectstatic.py", line 354, in copy_file remote: if not self.delete_file(path, prefixed_path, source_storage): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/comm ands/collectstatic.py", line 260, in delete_file remote: if self.storage.exists(prefixed_path): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 392, i n exists remote: return os.path.exists(self.path(name)) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", li ne 50, in path remote: raise ImproperlyConfigured("You're using the staticfiles app " remote: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set t he STATIC_ROOT setting to a filesystem path. remote: remote: ! Error … -
Uploading django app to digitalocean server, cannot upgrade django, resulting in 502 bad gateway
When I try to upgrade django on my digital ocean server using: pip install --upgrade django I get the following error: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-HzJGUP/django/ I tried to use Python 3.5 instead of 2, however I get the same error. -
passing args and kwargs to parent class with extra content in django CreateView
I've made a django form in which I want to pass some context I need to display (mainly database entries in tags so the user can choose from them). I therefor made a get_context_data function where I add the context to the existing context like this: def get_context_data(self, **kwargs): context = super(UploadView, self).get_context_data(**kwargs) context['categories'] = Category.objects.all() context['form'] = VideoForm return context however the form is not saving the information passed to the database. Why would that not work? Here is part of my code! forms.py: class VideoForm(forms.ModelForm): category = forms.ModelChoiceField(queryset=Category.objects.all(), empty_label=None) class Meta: model = Video fields = [ 'title', 'description', 'description_short', 'category', 'time', 'thumbnail', 'type', ] def clean_thumbnail(self): picture = self.cleaned_data.get("thumbnail") if not picture: raise forms.ValidationError("No Image") else: w, h = get_image_dimensions(picture) if w/h != (16/9): raise forms.ValidationError("Image in wrong aspect ratio (should be 16:9)") return picture upload.html (it's pretty long so it's better to upload it to pastebin) views.py: class UploadView(LoginRequiredMixin, CreateView): form_class = VideoForm template_name= 'upload.html' def form_valid(self, form): instance = form.save(commit=False) instance.uploader=self.request.user return super(UploadView, self).form_valid(form) def get_context_data(self, **kwargs): context = super(UploadView, self).get_context_data(**kwargs) context['categories'] = Category.objects.all() context['form'] = VideoForm return context I'm using a custom form so I can set classes which I use for editing the …