Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Flatpages and django-markdown2 template tag
I've installed django-markdown2 and it works in my templates, but when I add the tag {{ flatpage.content|linebreaks }} to my default flatpage template. I get an invalid tag error when trying to render the page. But the standard linebreaks does work. So is there a way to get the markdown tag working on flatpages? Thank you. -
How to pass data between Django module/app functions without using database in asynchronous web service
I've got a web service under development that uses Django and Django Channels to send data across websockets to a remote application. The arrangement is asynchronous and I pass information between the 2 by sending JSON formatted commands across websockets and then receive replies back on the same websocket. The problem I'm having is figuring out how to get the replies back to a Javascript call from a Django template that invokes a Python function to initiate the JSON websocket question. Since the command question & data reply happen in different Django areas and the originating Javascript/Python functions call does not have a blocking statement, the Q&A are basically disconnected and I can't figure out how to get the results back to the browser. Right now, my idea is to use Django global variables or store the results in the Django models. I can get either to work, but I beleive the Django global variables would not scale beyond multiple workers from runserver or if the system was eventually spread across multiple servers. But since the reply data is for different purposes (for example, list of users waiting in a remote lobby, current debugging levels in remote system, etc), the … -
Edit values of model's field in view or modelform
my models.py file looks like this: from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse STATUS_CODES = ( ('open', _('Open')), ('closed', _('Closed')), ) class Issue(models.Model): """Issues""" title = models.CharField(_('title'), max_length=100) description = models.TextField(_('description'), blank=True) assigned_to = models.ForeignKey(User, verbose_name=_('assigned to')) created_by = models.ForeignKey(User, verbose_name=_('creator'), related_name='creator') status = models.CharField(_('status'), default='open', choices=STATUS_CODES, max_length=10) objects = models.Manager() class Meta: verbose_name = _('issue') verbose_name_plural = _('issues') ordering = ('status', 'title', 'assigned_to', 'created_by') def __str__(self): return self.title def get_absolute_url(self): return reverse('edit_an_issue', args=[self.title]) and i have created a model form in the forms.py file like this: class EditAnIssue(forms.ModelForm): class Meta: model = Issue exclude = ('created_by',) The problem: A user can create an issue using a form which i already created. Issue form have fields same as Issue model. The problems i am facing: 1) I want to edit the Issue model from a view. Something like, there will be a form with title value pre-fetched in a dropdown and when user selects a title it loads all the fields values(The user who created the issue can edit/delete it). 2) once all the values are fetched the logged in user can edit the issue or delete that issue. … -
Django: uploaded image is not showing in template
I'm trying to write a simple blog using a Django framework. I want to have a cover image for a every post. I uploaded an image via Admin site and everything seems to be fine but image is not rendering in a browser. Image file is Here is my files: models.py (...) class Post(models.Model): author = models.ForeignKey('Author', on_delete=models.CASCADE) title = models.CharField(max_length=250) slug = models.SlugField(unique=True, blank=True, max_length=250) created = models.DateTimeField(auto_now=False, auto_now_add=True) modified = models.DateTimeField(auto_now=True, auto_now_add=False) image = models.ImageField(upload_to="images/%Y/%m/", blank=True, null=True) content = models.TextField() (...) django_blog_project\urls.py from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('blog.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) blog\urls.py (...) urlpatterns = [ url(r'^posts/create/$', PostCreate.as_view(), name="post_create"), url(r'^posts/([\w-]+)/$', AuthorPostList.as_view(), name="posts_by_author"), url(r'^(?P<slug>[-\w]+)/$', PostDetailView.as_view(), name="post_detail"), url(r'^', PostListView.as_view(), name="post_list"), ] settings.py (...) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') (...) post_detail.html {% extends "blog/base.html" %} {% block content %} <h1>{{ post.title }}</h1> <img src="{{ post.image.url }}" > <p>{{ post.content }}</p> <p>Autor: {{ post.author }}</p> <p>Opublikowano: {{ post.modified }}</p> {% endblock %} Dir tree My directory tree -
Django: writing a view to delete multiple object with checkboxes
So I have a table that lists all the record from my model. But now I'm trying to make a Checkbox and delete it (kinda like the Django admin way), I can't find the documentation for this , as I'm sure there are several ways to to this. But I'm trying to figure out like whats the proper way for doing this , should I do this via view ? How to create single delete button for multiple delete instances in html and view.I am not using form list.html {% for obj in object_list %} <tbody> <tr> <td><input type="checkbox" name="data" value="{{obj.id}}" ></td> <td><a href='#' data-toggle="collapse" value="{{obj.id}}">{{ obj.id }}</td> <td><a href='#demo' data-toggle="collapse">{{ obj.Full_Name }}</a></td> <td><a href="#demo" data-toggle="collapse">{{ obj.Agency_Name}}</a></td> <td><a href="#demo" data-toggle="collapse">{{ obj.Date_of_Birth}}</a></td> <td><a href="#demo" data-toggle="collapse">{{ obj.Agency_Code}}</a></td> <td><a href="#demo" data-toggle="collapse"><span class="label label-primary">{{ obj.Agent_Status}}</span></a></td> <td class="text-right"> <a href="{{ obj.get_absolute_url }}" class="btn btn-warning btn-circle" type="button"><i class="fa fa-list-alt" aria-hidden="true"></i></a> <a href="{% url 'customer:Agent_Edit' obj.id %}" class="btn btn-info btn-circle" type="button"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></a> #<a href="{% url 'customer:Agent_Delete' obj.id %}" class="btn btn-danger btn-circle" type="button"><i class="fa fa-trash" aria-hidden="true"></i></a> #Remove this button and create single button for multiple delete </td> </tr> </tbody> {% endfor %} view.py def Agent_List(request, id=None): #list items queryset = Agent.objects.order_by('id') #queryset = Agent.objects.all() query = … -
django admin reises FieldDoesNotExist on renamed field
sorry for newbie question, but I can't understand why this happen and how to fix it. I created Comment model class Migration(migrations.Migration): dependencies = [ ('myblog', '0001_initial'), ] operations = [ migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('text', models.TextField()), ('pub_date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date published')), ('lft', models.PositiveIntegerField(db_index=True, editable=False)), ('rght', models.PositiveIntegerField(db_index=True, editable=False)), ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), ('level', models.PositiveIntegerField(db_index=True, editable=False)), ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='myblog.Comment')), ], options={ 'abstract': False, }, ), ] After that I realized I forgot FK to Article. class Comment(MPTTModel): text = models.TextField() parent_article = models.ForeignKey(Article, on_delete=models.CASCADE) parent_comment = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) pub_date = models.DateTimeField('date published', default=timezone.now) class MPTTMeta: order_insertion_by = ['pub_date'] class Migration(migrations.Migration): dependencies = [ ('myblog', '0002_comment'), ] operations = [ migrations.RenameField( model_name='comment', old_name='parent', new_name='parent_comment', ), migrations.AddField( model_name='comment', name='parent_article', field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='myblog.Article'), preserve_default=False, ), ] And now I can't add comment at admin site, because it reises FieldDoesNotExist at /admin/myblog/comment/add/ Comment has no field named 'parent' How can I fix it? Do I have to delete Comment model and start from the beggining? Thank you. -
Fast get all subusers of specific node in django users table
I have django model: class Profile(models.Model): user = models.OneToOneField(User) parent = models.ForeignKey(User, related_name='parent_user_for_profile') How to create function which returns all the child users. For example See picture of hierarchy For n12 - [n122, n1211б n121, dsf] For n1 - [n12, n11, n122, n1211, n121, dsf] For n2 - [n21, n212] -
Strange case insensitive select behavior Django + mysql
I Have simple model in Django: class Tag(Model): name = CharField(unique=True, max_length=50) When I do: t = 'Ansible' print("Want tag: " + t) tg, created = Tag.objects.get_or_create(name=t) print("Got tag: " + tg.name) print("Query: {}".format(Tag.objects.filter(name=t).query)) print("Query result: {}".format(Tag.objects.filter(name=t).first().name)) I get result: Want tag: Ansible Got tag: ansible Query: SELECT `main_tag`.`id`, `main_tag`.`slug`, `main_tag`.`name`, `main_tag`.`added_time`, `main_tag`.`public_tips_count`, `main_tag`.`private_tips_count` FROM `main_tag` WHERE `main_tag`.`name` = Ansible Query result: ansible I use Django==1.10.3 and # mysql --version mysql Ver 14.14 Distrib 5.5.34, for debian-linux-gnu (armv7l) using readline 6.2 What I expect? I expect from get_or_create that it will create new tag named Ansible, but it returns some existent tag named ansible -
Docker refusing connection
I'm trying to run my first ever docker. On console everything seems to be fine, but the chrome says connection is refused. It tried to turn off windows firewall - no effect. Running on win10home. $ docker run -p 8000:8000 -v `pwd`:/data --rm -it mydjango mynewproject/manage.py runserver Performing system checks... System check identified no issues (0 silenced). December 28, 2016 - 11:48:20 Django version 1.10.4, using settings 'mynewproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. -
How to deploy django web application on Microsoft Azure cloud services
I have a existing django web application currently deployed on aws. I want to deploy it on Microsoft Azure by using cloud services. How to create config files for deploying web app on Azure? How to access environment variables on Azure? I am not using Visual Studio. I am developing web app in linux env and using git for code management. Please help -
Django/Haystack error: elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception',...)
I am using elasticsearch as backend for haystack in my Django project. I created everything required for a search as mentioned here. But when i search i throws a traceback error with TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]'). I have googled for this issue. But don't get any solution. I would appreciate helping me solve this. My traceback: Traceback (most recent call last): File "c:\python34\lib\site- packages\haystack\backends\elasticsearch_backend.py", line 524, in search _source=True) File "c:\python34\lib\site-packages\elasticsearch\client\utils.py", line 71, in _wrapped return func(*args, params=params, **kwargs) File "c:\python34\lib\site-packages\elasticsearch\client\__init__.py", line 569, in search doc_type, '_search'), params=params, body=body) File "c:\python34\lib\site-packages\elasticsearch\transport.py", line 327, in perform_request status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout) File "c:\python34\lib\site-packages\elasticsearch\connection\http_urllib3.py", line 124, in perform_request self._raise_error(response.status, raw_data) File "c:\python34\lib\site-packages\elasticsearch\connection\base.py", line 122, in _raise_error raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info) elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]') [28/Dec/2016 17:06:58]"GET /search/?q=code HTTP/1.1" 200 395 -
Database and Bounderies in "EBI" (Entity, Boundary, and Interactor) Design
Based on the design and patterns outlined in "EBI" (Entity, Boundary, and Interactor) - Ref Uncle Bob : Clean Code, it raises 3 questions. The concept of entities and interactors makes sense, however... Bounderies - If the boundary is separated to the delivery mechanism. What is it doing ? Would this be converting it from JSON to the correct data structures etc. If so how does this with Django. Would Django sit outside and interact with the boundery? Databases? I see the concept of entity gateways and why you would need them. But to have no dependencies pointing back to the database. What would an example look like. I typically use Mongo. In the world of Django would this be the ORM? But then again this would then tie me to a framework which of course would go against what we trying to achieve, in terms of decoupling. Django - Finally how does EBI work with Django (this slightly overlaps with the previous 2 questions)? Of course Django provides DB, UI and API features. But how would you use a framework outside of the use case / core application whilst ensuring decoupling. Thanks, -
Django: collectstatic works but doesnt find the correct static folder
I'm trying to run my django site in deployment mode with DEBUG=False. In fact when i do a python manage.py collectstatic it will collect all static files into my folder /mysite/static. But when i load my homepage my static files wont load Not Found occurs. Here is my STATIC ROOT definition and urls folder: In settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") (i tried also just only 'static') MEDIA_ROOT = BASE_DIR + '/mysite/media' MEDIA_URL = '/media/' my urls.py: urlpatterns = [ url(r'', include('mysite.urls')), ] urlpatterns += staticfiles_urlpatterns() I notice that is not assuming my collectstatic folder instead is considering the static file in app folder. doing python manage.py findstatic mysite/js/javascript.js Found 'app/js/javascript.js' here: /home/user/mysite/app/static/app/js/javascript.js Well, once that DEBUG=False it should give something like: /home/user/mysite/static/app/js/javascript.js -
Once i activate models in django, why can't i query them directly in postgresql pgAdmin UI?
I am very new to Django, and to web programming in general, so apologize for the silly question. So I am using django as a framework with python and I have made a connection with my database, Postgresql, DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'testdb', 'USER': 'postgres', 'PASSWORD': '****', 'HOST': 'localhost', 'PORT': '5432', } } after that i ran the python manage.py migrate command, and it outputed that everything was OK. I have also created models: class Albums(models.Model): artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=100) album_logo = models.CharField(max_length=1000) class Song(models.Model): albums = models.ForeignKey(Albums, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) song_title = models.CharField(max_length=250) After that i run the commands python manage.py makemigrations, it outputs that it works, then i run the command python manage.py migrate, and it outputs that everything is ok. I want to know why, when i go to the database in pgAdmin and i query the data with a SELECT * FROM Albums it does not even recognize the relation. This is probably not the right way to test to see if the tables were created, but can anyone help me out and tell me why they are not created in the pgAdmin UI also? And … -
jQuery display selected option text from dropdown
When I select a option in my drop down list I want to display that selected option in the drop down list, after I have been redirected to another page. The problem I have is that I use the code bellow to be able to redirect to another page when selecting a option from the drop down list. jQuery("#date-version").change(function (event) { alert("You have Selected ?version= :: "+jQuery(this).val()); alert( jQuery(this).find(":selected").text()); window.location.assign("?version=" + jQuery(this).val()); }); This is my html code with a little django code: <select id="date-version" name="selector"> {% for ver in version_list %} <option value="{% if ver.version %}{{ ver.version }}{% endif %} "{% if version == ver.version %} selected="selected"{% endif %}> {{ ver.user.person.name }} {{ ver.timestamp }} </option> {% endfor %} </select> Can somebody tell why I can not display the selected option text after window.location.assign, and how that can be fixed, thanks :). -
Django: Is it possible to check whether ALL admin forms(including StackedInlineAdmin) are valid?
admin.py class ItemInline(admin.StackedInline): model = Item form = ItemAdminForm class PaymentInline(admin.StackedInline): model = Payment form = PaymentAdminForm class WorkScheduleInline(admin.StackedInline): model = WorkSchedule form = WorkScheduleAdminForm class OrderAdmin(BaseAdmin): inlines = [WorkScheduleInline, PaymentInline, ItemInline, ] form = OrderAdminForm In my Order admin edit page, there are order, workschedule, payment, item forms. Each form has it own clean and validate checking methods. I wonder If I can check wheter ALL forms are valid when saved in admin page. What I want to do is (pseudo code) : if all forms are valid: do_something() Is it possible? Thanks -
My Form is not showing errors and input values after validation
My model.py class VehicleInquiry(TimeStampedModel): inquiry_status = models.PositiveSmallIntegerField(_("inquiry status"), choices=INQUIRY_STATUS_CHOICES, default=1) full_name = models.CharField(_("full name"), max_length=100) address = models.CharField(_("address"), max_length=200) ---- other fields ---- My Crispy form.py: class VehicleInquiryForm(forms.ModelForm): country2 = forms.TypedChoiceField( label=_("Country"), choices=[('','Arrival Country')]+[(country.id, country.name) for country in Country.objects.all().filter(visible=True).order_by('name')], required=True, ) phone_code = ChoiceFieldWithTitles( label=_("Country dialing code"), choices=[('','Dailing Code', 'Dailing Code')]+[(country.id, '{} (+{})'.format(country.name, country.phone_code), '+{}'.format(country.phone_code)) for country in Country.objects.all().filter(visible=True).order_by('name')], required=True, ) arrival_port = forms.TypedChoiceField( label=False, widget=forms.RadioSelect ) class Meta: model = VehicleInquiry fields = ('full_name', 'email', 'phone_code', 'phone', 'arrival_port', 'insurance', 'inspection', 'is_subscribed') def __init__(self, request=None, stock_product=None, *args, **kwargs): super(VehicleInquiryForm, self).__init__(*args, **kwargs) self.fields['is_subscribed'].label = _("Keep me updated") self.helper = FormHelper() self.helper.template_pack = "bootstrap3" self.helper.form_method = "post" self.helper.form_id = "vehicle-shipping-form" self.initial['insurance'] = True self.helper.add_input( Submit('inquiry', _('Inquiry'), css_class='btn btn-default',) ) self.helper.form_method = 'post' self.helper.layout = Layout( Fieldset( _("1. Choose Your Final Destination"), Div( Field('country2', css_class="order-select-country"), ), Div( Field('arrival_port'), Field('inspection'), --- other fields --- ),) My CBV view.py: class VehicleStockDetailView(TemplateView): model = StockProduct template_name = "site/product/vehicle-detail.html" template_name_done = "site/contact/contact-us-done.html" template_name_done_email = "site/contact/emails/contact-us-done.html" def post(self, request, slug, *args, **kwargs): form = VehicleInquiryForm(request.POST) ip="" if form.is_valid(): form.save() return render(request, self.template_name_done, { 'full_name': request.POST['full_name'], 'email': request.POST['email'], }) vehicle = get_object_or_404(VehicleStock, slug=slug) return render(request, self.template_name, { 'product': vehicle, 'form': form }) def get(self, request, slug, *args, **kwargs): vehicle … -
High CPU load sorting by a property with sorted()
The operation sorted() consumes a lot of CPU and the app is using it to order by a property for each user every 5 seconds (It's a table that is modifiyng continously) What do you think that it would be the best way to optimize this operation? Change the property by a field and update it every 5 seconds would be an option? -
Email confirmations are not stored Django allauth
I am using Django allauth with django-rest-auth. I implemented authentication with email confirmation. But now I realize that it does not work exactly as it should since I don't have stored send email confirmation in my DB (can't see them in admin). Email confirmation is being send as it should and it works perfect, just I can't see them in db. What am I missing? -
Django ModelAdmin get_object optimization
I've overriden get_queryset in Django ModelAdmin to optimize the change list view. Problem is that I need to override get_object with a different optimization but the two are bound together: class BaseModelAdmin(...): ... def get_object(self, request, object_id, from_field=None): """ Returns an instance matching the field and value provided, the primary key is used if no field is provided. Returns ``None`` if no match is found or the object_id fails validation. """ queryset = self.get_queryset(request) model = queryset.model field = model._meta.pk if from_field is None else model._meta.get_field(from_field) try: object_id = field.to_python(object_id) return queryset.get(**{field.name: object_id}) except (model.DoesNotExist, ValidationError, ValueError): return None What would be the best approach? Rewriting the entire get_object method Overriding the get_object and patching the get_queryset method Another way I'm not aware of -
Selenium webdrivers not responding properly to method calls in Django
Hey wonderful people of stackoverflow, when I attempt to run this code: from selenium import webdriver browser = webdriver.Chrome() browser.get("http://localhost:8000") assert 'Django' in browser.title Chrome opens however does not show http://localhost:8000 in the address, instead shows: data:, and this below in one of those warning yellow warning bars: "Unsupportedd command-line flag: --ignore-certificate-errors." Any thoughts? I tried adding "--test-type" to the launch settings of chromedriver but it didn't seem to work. I'm worried moving forward I won't be able to properly use many elements of the browser for testing, also I tried to install firefox to no avail. Any help is greatly appreciated. -
Django Admin Site displays the list of 'XXXObject' rather than directly displaying the details of the Objects
These are the Apps added from the Model Class I want it to directly display the details of the Object The attributes of the Leave_Details class are start_date,end_date,details.. -
map each post to the user who posted it by foreign key in django?
I want to connect each post with the logged in user who posted it. models.py from django.conf import settings from django.db import models # Create your models here. class Campagin(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) title = models.CharField(max_length=120) media = models.FileField() description = models.TextField(max_length=220) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self): return self.title` As you can see the posts were mady by two different users, but the relation shows that it is made by the first user this image shows the registered users.. -
NoReverseMatch due to wrong regular expression in url
In my URL I expect to get 2 dates as input: url(r'^export/range/csv/(?P\d+)/(?P\d+)/$', views.export_payment_range_csv, name="export_payment_range_csv"), But I am getting error : NoReverseMatch at /payment/list/range/ Reverse for 'export_payment_range_csv' with arguments '()' and keyword arguments '{u'start_date': datetime.date(2016, 2, 1), u'end_date': datetime.date(2016, 12, 31)}' not found. 2 pattern(s) tried: ['condition/export/range/csv/(?P\d+)/(?P\d+)/$', 'payment/export/range/csv/(?P\d+)/(?P\d+)/$'] I assume this has to do with regular expression in my URL file. what I am doing wrong? -
Weasyprint image size issue
I'm using Weasyprint to generate PDF files from template in my django view. The code is give below: html_template_pf = get_template('pension_form/allpages.html') rendered_html = html_template_pf.render(RequestContext(request, {'invoice_obj': invoice_obj, })).encode(encoding="UTF-8") pdf_file = HTML(string=rendered_html, base_url=request.build_absolute_uri()).write_pdf(stylesheets=[CSS(settings.STATICFILES_DIRS[0] + '/css/pension-form.css')]) invoice_obj.pension_form = SimpleUploadedFile('pension_form_' + invoice_obj.job.job_id + '.pdf', pdf_file, content_type='application/pdf') invoice_obj.save() Here the PDF is getting generated and the template for PDF contains more than one image reference. The images with smaller size (around 100KB) are rendered properly in the PDF. But the images with larger size (more than 350 KB) are not rendered in the output PDF file. How to overcome this issue and render images properly in the output PDF file?