Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
programming error column plans_to_lodge.id does not exist LINE 1: SELECT "plans_to_lodge"."id"
models.py class PlansToLodge(models.Model): sm_sequence = models.IntegerField() sm_year = models.IntegerField() location = models.TextField(blank=True, null=True) car_number = models.CharField(max_length=100, blank=True, null=True) client_or_owner = models.TextField(blank=True, null=True) date_received = models.DateField(blank=True, null=True) date_lodged = models.DateField(blank=True, null=True) remarks = models.TextField(blank=True, null=True) sent_or_received = models.TextField(blank=True, null=True) receipt_number = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'plans_to_lodge' unique_together = (('sm_sequence', 'sm_year'),) view.py def searchPlanInfo(request): logger = logging.getLogger(__name__) if request.user.is_authenticated(): if request.method =='POST': if request.POST['smYear'] is not '': searchPlan = request.POST['smYear'] logger.error('lets see here') foundPlan = PlansToLodge.objects.filter(sm_year=searchPlan) logger.error(foundPlan[0]) context = {'parcel_list': foundPlan} return render(request,'parcelmanager/index2.html',context) return HttpResponse("once again") traceback Traceback: File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\core\handlers\base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Sites\Landregistry\surveyplanmanager\views.py" in searchPlanInfo 39. logger.error(foundPlan[0]) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\models\query.py" in __getitem__ 201. return list(qs)[0] File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\models\query.py" in __iter__ 162. self._fetch_all() File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\models\query.py" in _fetch_all 965. self._result_cache = list(self.iterator()) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\models\query.py" in iterator 238. results = compiler.execute_sql() File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql 829. cursor.execute(sql, params) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\backends\utils.py" in execute 79. return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\backends\utils.py" in execute 64. return self.cursor.execute(sql, params) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\utils.py" in __exit__ 97. six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\utils\six.py" in reraise 658. raise value.with_traceback(tb) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\backends\utils.py" in execute 64. return self.cursor.execute(sql, params) Exception Type: ProgrammingError at /surveyplanmanager/searchPlanInfo/ Exception Value: column plans_to_lodge.id does not exist LINE 1: SELECT "plans_to_lodge"."id", "plans_to_lodge"."sm_sequence"... … -
Looking for a way to keep my code DRY when creating models on Django
I would like to know how to keep my code as DRY as possible. I want to model the follow situation. In a social network the user can choose between 3 kinds of profile (A , B and C), All the profiles have core fields, but B has more fields than A, and C more the B. And one Profile that would be my main class has a OneToOne relation with django user system and must have a OneToOne relation with some of the profile types Profile_Type_A: interests favourite_colour favourite_food Profile_Type_B: interests favourite_colour favourite_food favourite_sport Profile_Type_C: interests favourite_color favourite_food favourite_sport favourite_language So, what do you suggest me? Should I create just one profile type then use a system of conditions according the user profile selection? Or should I create 3 classes, one for each profile repeating the core fields? Thanks -
Mezzanine overextends() template tag examples?
I've been searching but there no examples of Mezzanine overextends()template tag, which allows you to extend a template with the same name. Does anybody know? -
Multilanguage site with Python Django
We are making a site for multiple users, using Python Django. We need to set language of system messages (such as indications of user's errors, labels of control elements, etc.) different for different registered users. What is the best way to do this? -
Retrieving form data after setting initial value
I wanted to populate my form fields with initial data, so I've set my view just like recommended by @ars in this question: def update_member(request): if request.method == 'POST': urn = 'urn:publicid:myurn' member = Member(urn=urn) retrieved_members = member.search_member(filter_params=['urn', 'first_name', 'last_name']) # If search returns member if retrieved_members != []: member = retrieved_members[0] member_attributes = {'first_name': member.first_name, 'last_name': member.last_name} form = UpdateMemberForm(initial=member_attributes) And it works properly. But when I manually fill in the fields in the template, my view still sets those initial values. I cannot reset the values as the ones passed via POST method. I know this happens because of the way I set the initial values, but I don't know how I could fix it. Does anyone has an idea of how I could solve this? -
Models referring to each other - how can I most efficiently fix this issue?
I have a Django application that contains two models - Company and User. These are each in separate files. Each User has a Company by a model.ForeignKey field: company.py: class Company(models.Model): name = models.CharField(max_length=32) is_admin = models.BooleanField(default=False) user.py: # Ignore the clumsy in this import for a moment from package.models.company import Company class User(models.Model): name = models.CharField(max_length=32) company = models.ForeignKey(Company) Now, one thing I want to do is to add a method list_admins to Company (not User), whereby it would give me a list of all users who happen to have is_admin set to True: def list_admins(self): return User.object.filter(is_admin=True); But of course that would require me to import User in Company, which I can't, as I can't import User in Company and Company in User at the same time owing to its circularity. So how does one resolve this in a Pythonic/Djangoic way? -
Class based views how to handle OneToOneField in a model
I have 2 models: class CompanyInfo(models.Model): name = models.CharField(_('name'), max_length=100) address = models.OneToOneField(Location) class Location(models.Model): address_1 = models.CharField(_("address"), max_length=128) address_2 = models.CharField(_("address cont'd"), max_length=128, blank=True) city = models.CharField(_("city"), max_length=64, default="") state = USStateField(_("state"), default="") zip_code = models.CharField(_("zip code"), max_length=5, default="") When I use CBVs and prints out the form on the template. It shows name with an input field and address as a multiple choice selection. Is there anyway in which I could convert the multiple choice to act as multiple input fields and the state to be multiple choice. I figured I could have 2 form for these, but how would I incorporate a form inside of a form? Edit: Also, the way in which the models and fields are must not be changed. For this example sure location fields could be in the company info, but I simply want how to do something similar when it doesn't make sense to include all these fields into the same model. -
storing values from html to mysql via django
i want to send data to my mysql db via django. When i run server i dont get any error. When i submit form from hello.html, the values arent stored in my db. in DB i got table hello_cont hello.html {% block content %} <form action="/polls/" method="POST"> {% csrf_token %} <input class="form-control" id="name" name="name" placeholder="Name" type="text" required> </div> <div class="col-sm-6 form-group"> <input class="form-control" id="email" name="email" placeholder="Email" type="email" required> </div> </div> <textarea class="form-control" id="comments" name="comments" placeholder="Comment" rows="5"></textarea><br> <div class="row"> <div class="col-sm-12 form-group"> <button class="btn btn-default pull-right" type="submit">Send</button> {% endblock %} models.py from __future__ import unicode_literals from django.db import models class cont(models.Model): name = models.CharField(max_length=10) email = models.CharField(max_length=10) comments= models.CharField(max_length=250) def __str__(self): return self.name forms.py from django import forms from .models import cont class PostForm(forms.ModelForm): class Meta: model = cont fields = ('name', 'email', 'comments') view.py from django.utils import timezone from django.shortcuts import render from django.http import HttpResponseRedirect from .models import cont from .forms import PostForm def hello(request): return render(request, 'polls/hello.html') def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.name = request.user post.email = request.email post.comments = request.comments post.save() else: form = PostForm() return render(request, 'blog/post_edit.html', {'form': form }) -
'str' object is not callable Django Rest Framework
I'm trying to create an API view but I'm getting an error. Can anyone help? urls.py: app_name = 'ads' urlpatterns = [ # ex: /ads/ url(r'^$', views.ListBrand.as_view(), name='brand_list'), ] views.py: from rest_framework.views import APIView from rest_framework.response import Response from . import models from . import serializers class ListBrand(APIView): def get(self, request, format=None): brands = models.Brand.objects.all() serializer = serializers.BrandSerializer(brands, many=True) data = serializer.data return Response(data) -
Django IntegrityError: Column 'position' cannot be null
I'm using Django-CMS and I created some custom plugins that I use in several pages but in one of the pages I can't publish nor I can't copy plugins that are nested and gives me the same error in both situations: Internal Server Error: /en/admin/cms/page/copy-plugins/ Traceback (most recent call last): File "lib\site-packages\django\core\handlers\base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "lib\site-packages\django\core\handlers\base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "lib\site-packages\django\utils\decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "lib\site-packages\django\views\decorators\cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "lib\site-packages\django\contrib\admin\sites.py", line 244, in inner return view(request, *args, **kwargs) File "lib\site-packages\django\utils\decorators.py", line 67, in _wrapper return bound_func(*args, **kwargs) File "lib\site-packages\django\views\decorators\http.py", line 42, in inner return func(request, *args, **kwargs) File "lib\site-packages\django\utils\decorators.py", line 63, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "lib\site-packages\django\views\decorators\clickjacking.py", line 39, in wrapped_view resp = view_func(*args, **kwargs) File "lib\site-packages\django\utils\decorators.py", line 184, in inner return func(*args, **kwargs) File "lib\site-packages\cms\admin\placeholderadmin.py", line 363, in copy_plugins plugins, target_placeholder, target_language, target_plugin_id) File "lib\site-packages\cms\utils\copy_plugins.py", line 24, in copy_plugins_to old_parent_cache, no_signals)) File "lib\site-packages\cms\models\pluginmodel.py", line 319, in copy_plugin new_plugin.save() File "lib\site-packages\cms\models\pluginmodel.py", line 240, in save self.parent.add_child(instance=self) File "lib\site-packages\treebeard\mp_tree.py", line 970, in add_child return MP_AddChildHandler(self, **kwargs).process() File "lib\site-packages\treebeard\mp_tree.py", line 361, in process newobj.save() File … -
obtain path inside custom plugin
I create my first custom plugin using the official documentation of django cms inside my plugin I have a static and template folder... my static folder has js and CSS folder inside inside my template folder, I have other folder and inside this my drawchart.html file I use this info to handling my js and CSS file inside the plugin I have this in my drawnChart.html file to obtain the path of my static folder inside my plugin {% load sekizai_tags %} {% addtoblock "js" %}<script type="text/javascript" src="{{ STATIC_URL }}drawChart/js/chart.js"></script>{% endaddtoblock %} but I obtain this response GET http://127.0.0.1:8000/static/drawChart/js/chart.js any idea to How obtain this path? thanks in advance! -
Custom template not displaying when bse template is extended?
Mezzanine CMS docs says, "The view function mezzanine.pages.views.page() handles returning a Page instance to a template. By default the template pages/page.html is used, but if a custom template exists it will be used instead. The check for a custom template will first check for a template with the same name as the Page instance’s slug, and if not then a template with a name derived from the subclass model’s name is checked for." So the above is true for my custom template with the name of the my Page intance's slug. But once I extend a base.html template inside my custom template my custom template does not display instead the pages/page.html is displayed. What is wrong? -
Trigger a function with a button Django
I'm building a webapp and I need to configure a button that when is clicked download a xls file (I already have that function and can be triggered by the url) what are the ways I can trigger a function? This is what I got: my button in my admin.html: <p><button type="button" class="btn btn-danger" name="runreport" value="report">3a5 Report</button></p> My function in excel_views.py is: def xls_report(request): #logic here (if you want I can share it (is just long) response = HttpResponse(output.read(),content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") response['Content-Disposition'] = "attachment; filename=Reporte3a5.xlsx" return response What is the easiest wat to do this? When ever the button is clicked to download the file Thanks for your time -
Django remove duplicate entry in html templatetag
I am pulling items from a database and listing them on my site. I will have items that share a common field. When listing this field, where multiple objects share it, how do I only show one item. Here is a snippet of my html to show what I mean: django html: {% for obj in object_list %} <li>{{ obj.manufactured_city }}</li {% endfor %} the html output: <li>Philadelphia<li> <li>Philadelphia<li> <li>Philadelphia<li> <li>Boston<li> <li>Ann Arbor<li> My desired output: <li>Philadelphia<li> <li>Boston<li> <li>Ann Arbor<li> Later in the html page I will use the data again for a full list of all the info. So I'd like to filter inside the html, and not the view. My only guess in the view is to have two variables, one for this search info above, and another for the rest of the info, not shown here. Any thoughts? -
Django Python, Form show the csrf token
I'm trying to make a variable form in django but it seems not working properly, I hope you can help me because i show me the token instead of form values. Help me please! url. url(r'^test', views.test), views. def test(request): if request.method == "POST": for key, value in request.POST.items(): response = '%s %s' % (key, value) return HttpResponse(response) return render(request, 'datos2.html') datos2. <form action="/test" method="post"> {% csrf_token %} <input type="text" name="eee"> <input type="submit"> </form> <p>ADD VALUE</p> <button onclick="myFunction()">ADD</button> <script> function myFunction() { var x = document.createElement("INPUT"); x.setAttribute("type", "text"); x.setAttribute("value", "0"); x.setAttribute("name", "eee"); document.body.appendChild(x); } </script> Help me please! -
Django 1.7: on_delete=models.SET_NULL not work
My models.py: class MyFile(models.Model): file = models.FileField(upload_to="myfiles", max_length=500, storage=OverwriteStorage()) slug = models.SlugField(max_length=500, blank=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True,) date_created = models.DateTimeField(auto_now_add = True, blank=True, null=True) date_expired = models.DateTimeField(default=default_time, blank=True, null=True) expires = models.BooleanField(default=True) def __str__(self): return self.file.name @models.permalink def get_absolute_url(self): return ('myfile:myfile-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(PSFile, self).save(*args, **kwargs) def delete(self, *args, **kwargs): self.file.delete(False) super(PSFile, self).delete(*args, **kwargs) class Meta: managed = True But, if User deleted, all related myfiles still deleted. Any idea? Thanks -
Django: Using get_form_kwarg to pass url pramater into form __init__ for ModelChoiceField selection filiter
I am building a FAQ app. Model flow Topic -> Section -> Article. Article has a FK to Section which has a FK to Topic. In my create article from I want to take in the Topic_Pk so when the user selects a Section the choice selection is limited to just the Sections attached under the Topic. I am using get_from_kwarg to pass the Topic_Pk from the url to __init__ in the form. I keep getting a TypeError __init__() got an unexpected keyword argument 'topic_pk'. I do not want to pop the data or set topic_pk=None in the init parameters as this would invalidate the whole point. What is it I am missing to allow me to use this variable? Url: url(r'^ironfaq/(?P<topic_pk>\d+)/article/create$', ArticleCreateView.as_view()), View: class ArticleCreateView(CreateView): model = Article form_class = CreateArticleForm template_name = "faq/form_create.html" success_url = "/ironfaq" def get_form_kwargs(self): kwargs = super(ArticleCreateView,self).get_form_kwargs() kwargs.update(self.kwargs) return kwargs Form: class CreateArticleForm(forms.ModelForm): section = forms.ModelChoiceField(queryset=Section.objects.none()) def __init__(self, *args, **kwargs): super(CreateArticleForm, self).__init__(*args, **kwargs) self.fields['section'].queryset = Section.objects.filter(topic_pk=self.kwargs['topic_pk']) class Meta: model = Article widgets = { 'answer': forms.Textarea(attrs={'data-provide': 'markdown', 'data-iconlibrary': 'fa'}), } fields = ('title','section','answer') Model: class Article(Audit): title = models.CharField(max_length=255) sort = models.SmallIntegerField() slug = models.SlugField() section = models.ForeignKey(Section,on_delete=models.CASCADE) answer = models.TextField() vote_up = models.IntegerField() … -
Search in django app with haystack, the results is lower than with ORM? Why?
enter image description hereenter image description here And I am sure rebulid_index. Thanks. -
Python, Flask: Performance implication of loading large JSON config at runtime
I would like to better understand the performance cost of loading large JSON config files at every request in a web app (to keep the topic specific, let's aim for flask, or django). The use case: I am using JSON to share models between different services written in different languages, because they change often and thus it is easy to deal with JSON files. It seems the solution is to explicitly cache in memory with something like memcache, but I would like to know if I'm not missing something; If there's isn't some OS level (Linux) or any application level mechanism that would automatically somehow cache these files being read everytime? -
token authentication with Django Rest framework in backend + ionic
I have a Django REST project with token authentication for users .. And I now I am creating a new mobile application for authentication with ionic . What should I do to generate a token while inscription and recover that token when authenticated and store it in local storage of the application and use it each time for calling APIs from my backend project . What should I do please, I am new in ionic ! -
Unable to cache changes to django models
I cannot seem to cache changes I make to fields of a Django model. I understand that the reason is that I am only ever changing copies of those fields. But I don't know what to do about it. Consider this trivial example (the real code is much more complex, but I believe this isolates the issue): models.py: class Parent(models.Model): name = models.CharField(blank=True, max_length=BIG_STRING, unique=True) class Child(models.Model): name = models.CharField(blank=True, max_length=BIG_STRING, unique=True) parent = models.ForeignKey("Parent", blank=True, null=True, related_name="children") Now someplace in my code I create a hierarchy of models and then cache it (using memcached): view1.py: parent = Parent(name="parent") child = Child(name="child1") parent.save() child.save() parent.children.add(child) request.session["my_unique_key"] = parent So far, so good. Elsewhere in my code I retrieve my cached object and make some changes to it and then re-cache it. But those changes are not saved: view2.py: parent = request.session.get("my_unique_key") local_copy_of_child = parent.children.get(name="child1") local_copy_of_child.name = "child2" request.session["my_unique_key"] = parent Obviously the value of parent.children.all()[0].name is "child1" instead of "child2". But, in the real code, the location of the instance I want to change is arbitrarily complex (it could be the child of a parent of a parent of parent of a parent, etc.). So at some point I will … -
How can I convert django queryset list into dictionary?
I have more then two django querysets and merged them into a list as shown output below. work_queryset = Work.objects.filter(base_id = q).values('worktype', 'datestart', 'dateend', 'dailyworktime', 'remarks') holiday_queryset = Holiday.objects.filter(base_id = q).values('holiday_type', 'datestart', 'dateend', 'remarks') Merged list merged_list = list(chain(work_queryset, holiday_queryset)) output [{'datestart': u'2016-04-11', 'dateend': u'2018-07-21', 'remarks': u'Hello remarks', 'worktype': u'Remote'}, {'remarks': u'New holiday', 'datestart': u'2018-09-22', 'dateend': u'2019-09-22', 'holiday_type': u'Sick leave'}, {'remarks': u'nothing comment', 'datestart': u'2016-04-11', 'dateend': u'2016-07-20', 'holiday_type': u'Summer holiday'}] What i am trying to achieve is to convert merged_list into dictionary as shown below: [{'work' : [{'datestart': u'2016-04-11', 'dateend': u'2018-07-21', 'remarks': u'Hello remarks', 'worktype': u'Remote'}], 'holiday': [{'remarks': u'New holiday', 'datestart': u'2018-09-22', 'dateend': u'2019-09-22', 'holiday_type': u'Sick leave'}, {'remarks': u'nothing comment', 'datestart': u'2016-04-11', 'dateend': u'2016-07-20', 'holiday_type': u'Summer holiday'}]}] How can i achieve this? -
Tasty pie multipart post integer field become array
I uploading lie with additional fields to DJANGO testy pie and get validation error If I post file field and char field - char field become from 'test' to '[test]' If I post also integer field for example 57 it becomes ['57'] I check fron - it's ok In back request.POST have converted data... Field in model described as small integer field -
django templatetags for jquery to get item from html templatetag
I have photo album for this site I'm working on and am using jquery to filter by country/city. If I hardcode in each country into the jquery I get my desired results. I obviously do not want to do this. Below is what I mean by that. <div class="container"> <div class="photo-title"> <h1>Welcome to Our Photo Album</h1> </div> <div class="col-sm-12 photoalbum-buttons"> <div class="dropdown form-actions"> <button class="btn btn-primary gradient dropdown-toggle" type="button" data-toggle="dropdown"> <i class="fa fa-search"></i> By Country </button> <ul class="dropdown-menu"> <li><button id="all_countries" value="all_countries">All Countries</button></li> {% for obj in object_list %} <li><button id="{{ obj.country }}" value="{{ obj.country }}">{{ obj.country }}</button></li> {% endfor %} </ul> </div> <div class="dropdown form-actions"> <button class="btn btn-primary gradient dropdown-toggle" type="button" data-toggle="dropdown"> <i class="fa fa-search"></i> By City </button> <ul class="dropdown-menu"> {% for obj in object_list %} <li><button id="{{ obj.city }}" value="{{ obj.city }}">{{ obj.city }}</button></li> {% endfor %} </ul> </div> </div> <div id="all-photos-div"> <div class="dropdown form-actions hidden-div"> <button id="all_photos" class="btn btn-primary gradient dropdown-toggle" type="button" data-toggle="dropdown"> <i class="fa fa-search"></i> All Photos </button> </div> </div> <p id="photo-separator">______________________________________________</p> <div class="row"> <div class="row photo-post"> {% for obj in object_list %} <div class="col-sm-3 country_{{obj.slug}}"> <div class="thumbnail"> <a class="thumbnail" href="#" data-image-id="" data-toggle="modal" data-title="{{ obj.city }}, {{ obj.country }} {% if obj.picture_taken %}| {{ obj.picture_taken }}{% else … -
DJango Broken Buttons in Admin
In django admin, the change, add , delete buttons are broken. I mean broken as in they show up as broken gifs (or svgs?) How can I get rid of the buttons ? Thanks.