Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CreateView don't call form_valid neither form_invalid or post()
I have a CBV : class Publish(CreateView): success_url = '/' template_name = "article/publish.html" form_class = ArticlePublish model = Article def get(self, request, *args, **kwargs): print('ee') return super(Publish, self).get(request) def post(self, request, *args, **kwargs): print('jj') return super(Publish, self).post(request) def form_valid(self, form): print('dd') form.instance.author = User.objects.get(id=self.request.user.id) return super(Publish, self).form_valid(form) def form_invalid(self, form): print('cc') return super(Publish, self).form_invalid(form) When i submit this form: class ArticlePublish(forms.ModelForm): class Meta: model = Article fields = ['title', 'synopsis', 'content'] with the following HTML: <form action="" method='POST'> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save" /> </form> I get: [13/Oct/2016 16:33:53] "GET /publish/ HTTP/1.1" 200 591 ee [13/Oct/2016 16:33:56] "POST /publish/ HTTP/1.1" 200 591 ee So it seems that even using post, with the correct modelForm still don't call the form_valid or form_invalid method. Even the post method dont get called. Someone have an idea of what is going on please? -
Greater than or equal to forloop counter django template
How can I use greater than or equal to operator for forloop counter in django template? I want to do something like: {% if forloop.counter<=12 or forloop.counter>=25 %} But it is giving me an error: Could not parse the remainder: '<=12' from 'forloop.counter<=12' -
Python: What OS am I running on
i am in new django framework.i want send mail using django framework.here this is my setting.py file and i want know from you.what should i put Email_Host,EMAIL_HOST_USER EMAIL_HOST_PASSWORD. can you explain what is this. ALLOWED_HOSTS = [] EMAIL_HOST = '' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 EMAIL_USE_TLS = True -
how to integrate Angular2 uglified with webpack with Django
I've been working on this issue for quite a long time now, and I'm completely lost. I have Django backend and I would like to have it serve Angular2 app in the frontend. From what I've been told I need to build Angular2 app for production, and import those minified and uglified .js files as static files in Django template for the main page. So I build my Angular2 app with webpack, and then I incorporated them in my index.html like that: {% load staticfiles %} <!DOCTYPE html> <html> <head> <base href=/ > <title>Angular With Webpack </title> <meta charset=UTF-8> <meta name=viewport content="width=device-width,initial-scale=1"> </head> <body> <my-app>Loading...</my-app> <script type="text/javascript" src="{%static "app.6dfc63771c3fd30c056a.js"%}></script> <script type="text/javascript" src="{%static "vendor.6dfc63771c3fd30c056a.js"%}></script> <script type="text/javascript" src="{%static "polyfills.6dfc63771c3fd30c056a.js"%}></script> </body> </html> this index.html file is being served as Django template and it only displays "Loading...". I'm completely lost now, and I don't know how can I fix this. Please, help. -
Ajax filter django
model class WinF(models.Model): title = models.CharField(max_length=200) text = models.TextField() user = models.ForeignKey(User) date = models.DateTimeField() view def home(request): arctic = WinF.objects.all() cont = {'arctic': arctic } return render(request, 'Mysitez/home.html', cont) block {% for arctics in arctic %} <option value="{{ arctics.user }}">{{ arctics.user }}</option> {% endfor %} {% for arctics in arctic %} <h4>{{ arctics.title }}</h4> <pre>{{ arctics.get_shor_text }}</pre> {% endfor %} need ajax filter by user with output on page titles and texts selected user or similar example -
How to get reversed data in admin using GenericTabularInline?
Models: class Criterias(models.Model): name = ... class Places(models.Model): name = ... class PlacesToCriterias(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() criteria_group = models.ForeignKey(Criterias) Admin - PLACES part: class PlaceCriteriasInlineAdmin(GenericTabularInline): model = PlacesToCriterias class PlacesAdmin(admin.ModelAdmin): inlines = [PlaceCriteriasInlineAdmin] admin.site.register(Places, PlacesAdmin) In this case, when I open Places admin change page, I can add Criterias items to my 'place'. Admin - CRITERIAS part: class CriteriaPlacesInlineAdmin(GenericTabularInline): model = PlacesToCriterias class CriteriasAdmin(admin.ModelAdmin): inlines = [CriteriaPlacesInlineAdmin] admin.site.register(Criterias, CriteriasAdmin) In this case, when I open Criterias admin change page, I CAN NOT add Places item to my 'criteria', because instead of possible places I see criterias. How to get Places items at Criterias admin page? -
VisualStudio django.conf.urls
This is my first question ever. I am working in VisualStudio to create a django/python application for smartshopping AI. This is also my first python/django technology application. I have trouble with the urls.py and have read that django versions do not include urlpatterns. I've changed my url patterns to reflect the advice online and have changed my django.conf.urls import url section of my code. It is still not working. Please help. I've followed the advices online to get here I want an easy fix not to change all the views to add include - these were autogenerated by visual studio. I want to keep autogeneraton working and just add a line of code to reference the url.py -
How to call a Python script inside a HTML file?
I am using HTML5,Django ,Python 3.4 1) I want 2 call a python script inside an html5 document Code(pyscript.py)= print("Hello everyone") Note the file pyscript.py and mywebpage.html r in the same directory named templates 2)I want 2 call a python script inside another python script ,how do i do it? 1.py Code== a=5 2.py CODE== //here i include python script that is 1.py then print(a) -
How to add more space in `__str__` method of Django model?
I want to add more spaces to __str__ method, but method cut off spaces to 1. For example: class Spam(models.Model): foo = models.IntegerField() bar = models.IntegerField() def __str__(self): return 'more spaces {} {}!'.format(self.foo, self.bar) This output in Django admin: more spaces 1 2 I want : more spaces 1 2 How do this? -
Logic to jump weekends Django/python
I got this function. What I need is to make some changes in my model depending on the day. As my if statements shown below, if the "ddate" is today or tomorrow make some changes in my "pull_ins" column and set it up as "Ready to ship" but if is the day after tomorrow and the next day, set "Not yet". This is working but my problem is that I need to jump weekends and keep the 4 days logic, any ideas? As an example if today is Thrusday to get the ddate from today, tomorrow(friday) -----jump weekend --- monday, tuesday. This is what I got: def Ship_status(): week = {0, 1, 2, 3, 4} deltaday = timedelta(days=1) today = datetime.now().date() day = today day1 = day + deltaday day2 = day1 + deltaday day3 = day2 + deltaday for i in Report.objects.all(): if i.ddate.weekday() in week: if i.ddate == day: i.pull_ins = "Ready to ship" i.save() if i.date == day1: i.pull_ins = "Ready to ship" i.save() if i.date == day2: i.pull_ins = "Not yet" i.save() if i.date == day3: i.pull_ins = "not yet" i.save() Thanks for your time. -
django-oscar categories and products translations
I want to use django-oscar for building an web shop and this shop will provide two main languages. Oscar's translations do very well with regular fields like View chart or Add to chart, but does not support custom elements e.g. Categories or Product's Titles. I want have translated: Category Product.Title Product.Description I've figured out two approaches: Approach one - modify django-oscar templates I can create custom set of tranlsations according to oscar's translation doc. And then fill proper django.po file with translated categories and product's titles. Unfortunately I will have to overwrite some templates, because they don't use trans templatetag by default. E.g. I would change. <a href="{{ category.get_absolute_url }}">{{ category.name }}</a> to <a href="{{ category.get_absolute_url }}">{% trans category.name %}</a> In this oscar's template. Main problem with this approach is need for overwriting templates, updating django.po as well as compiling it with every new entry to translate. Approach two - use django-modeltranslation Using this plugin. Question Does I miss some build in django-oscar's feature, or I have to use one of above approaches? Does my -
Distance between two 3D point in geodjango (postgis)
my problem is the following: I created two points for the example: SRID=3857;POINT Z (62780.8532226825 5415035.177460473 100) SRID=3857;POINT Z (62785.8532226825 5415035.177460473 70) As you can see, there is 5m difference in X coordinates, and 30m in Z coordinates. When I run a.distance(b) in django shell, it returns 5, which is wrong. However, when i run in a psql shell: SELECT ST_3DDistance(a.coordinates, b.coordinates) FROM restapi_entityxyz a, restapi_entityxyz b WHERE a.external_id='6841zef1561' AND b.external_id='1G23Fzd'; It returns: st_3ddistance ------------------ 30.4138126514911 Which is the right answer. Is it a lack of functionality in geoDjango or a bug ? Should I use a custom library to perform such a calculation ? My environment is the following: Python 3.5, Django, postgresql 9.4 + postgis with gdal and a lot of python libraries. -
Creating dynamic URLS by concatenating strings rises UnicodeEncodeError
I am trying to build my urls dynamically upon my project execution, it retrieves all my projects and concatenates the strings to create the urls like following: for project in projects: domain = Settings.objects.get(id_project=project).site_domain urlpatterns += patterns('', (r'^'+project.type+r'/'+project.name+r'/', include('apps.'+project.type+'.urls'))) The problem is that django is generating me this error: UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 144: ordinal not in range(128) and when I take a look at the stack, there is nowhere pointing to my code.. I believe it has a relation to the r'^' which could be a different type of encoding, but I couldn't find resources to draw any conclusion. Any help is extremely appreciated -
How does Django's `url` template tag reverse a Regex?
How does Django's url template tag work? What magic does it use under the covers to "reverse" a regex? You give it a regex like this: urlpatterns = [ # ex: /polls/5/ url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), ] ... and then in your template you can generate a URL that matches that pattern like this: <a href="{% url 'detail' question.id %}">{{ question.question_text }}</a> How does that work? Normally a regex is used to parse text, not generate it. Are there built-in tools in the re module that provide this functionality? My question is not about how to use Django, or how to parse text with a Regex. Instead I'm interested in learning how I can use regular expressions in this "string template" way elsewhere. -
Django url config with multiple urls matching
in one of our Django applications we have defined multiple urls for views. The first URL matches a general feature with pk and a second match group. The second URL matches a subfeature with pk. Between this two urls more urls are defined, so it is not easy to see them all at once. Or, for example, the subfeature would have its own url.py. url(r'^(?P<pk>\d+)/(?P<special_data>\d+)/$', views.b), url(r'^subfeature/(?P<pk>\d+)/$', views.a), After some time letters are also allowed in pk, so we now have to change \d+ to [^/]+. url(r'^(?P<pk>[^/]+)/(?P<special_data>\d+)/$', views.b), url(r'^subfeature/(?P<pk>\d+)/$', views.a), Now the subfeature breaks because the url is not correctly matched, 'subfeature' is matched as pk in the first url. How to avoid breaking other urls when changing a url regex? -
How to add python code in template in Django
I am new to django, please tell me that can I write this code in html page or not, If I can write thewn Please show me a simple example. Thanks in advance. while True: for i in ["/","-","|","\\","|"]: print "%s\r" % i, -
Cannot open filename that has umlaute in python 2.7 & django 1.9
I am trying doing a thing that goes through every file in a directory, but it crashes every time it meets a file that has an umlaute in the name. Like ä.txt the shortened code: import codecs import os for filename in os.listdir(WATCH_DIRECTORY): with codecs.open(filename, 'rb', 'utf-8') as rawdata: data = rawdata.readline() # ... And then I get this: IOError: [Errno 2] No such file or directory: '\xc3\xa4.txt' I've tried to encode/decode the filename variable with .encode('utf-8'), .decode('utf-8') and both combined. This usually leads to "ascii cannot decode blah blah" I also tried unicode(filename) with and without encode/decode. Soooo, kinda stuck here :) -
Django - Dynamic form fields based on foreign key
I'm working on creating a database which has programs and these programs have risks. Some background information: Programs (grandparents) have multiple Characteristics (parents) which have multiple Categories (children). I've already constructed a database containing these, however, I want to add risks to a particular program. That is, for example i have Risk 1 which i want to add to Program 1. I have to answer the following questions: Which characteristics do Risk 1 have? To answer this, I want to construct a dynamic form field. (Note, the amount of characteristics can by any arbitrary number, as well as the amount of categories each characteristic has). How do I construct such form? I've tried formsets, however I do not know how to implement those in a practical way (I'm still a bit new with Python). This is a printscreen of how I want it to be implemented: https://gyazo.com/40c448c0096a9ec5da751ba9883dc912 However, I have no idea what to do. (Note that the possible answers in the drop down menu are the categories that correspond to that particular Characteristic). This is what I'm getting: https://gyazo.com/25fd18e2f31e6931bfd3639ce4be632c This is the corresponding code I have thus far: # views.py def risk_create(request): program = get_object_or_404(Program, id=20) RiskFormSet = formset_factory(RiskForm, … -
Serve Different Sphinx Docs Build in Django Project
I have a Django Project and I want to include the HTML Sphinx Docs build pages with associated css/JavaScript/etc. to be served on the website. I have built the Sphinx docs in the templates/foo directory of my Django project, and used the following view.py for the app created as docs/: from django.conf.urls import url from django.views.generic import TemplateView from . import views app_name = 'docs' urlpatterns = [ url(r'^$', TemplateView.as_view(template_name = 'foo/index.html')), ] When I run server, I am able to see the Sphinx Docs at domain/docs. It is not formatted with the CSS nor are any of the links to the sections/pages working. I tried adding STATICFILES_DIRS: STATICFILES_DIRS = [ "templates/foo", ] And ran python manage.py collectstatic, but that did not work. Is there a way to just serve this foo directory within this Django Project? -
how to set theme for tinymce.models.HTMLField?
How does one set the theme and other attrs for django-tinymce's HTMLField for models? I would like to do the same as for ModelForms, setting attrs: content = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30})) Thanks! -
How to integrate Django-CMS into an existing project
I need to integrate Django-CMS 3.x into an existing project (mypjc hereafter). I already checked this question (and other similar) but they point to a tutorial page that is no longer available. I'm a bit confused by the tons of infos you can find online and I have not really understood if Django-CMS can be integrated as an app into an existing and independently running Django project. mypjc (using Django 1.8) would benefit from a user friendly CMS. Basically I'd the user to be able to write texts and to load in their posts images stored in the (common) database, images that are created by the user in mypjc. Is it possible? if yes, could anyone help me defying the steps needed to make the integration clean and successful? Thank you in advance for any help you could provide. -
How can I automatically change the value of a Boolean field?
This particular Boolean field determines whether a post is a draft. The default is set to True. When the user edits a draft, I want the value to be automatically changed to False, so that it is listed with all the other posts (instead of in the drafts list). Could the submit button both submit the post and change the Boolean value? Ideally, I suppose, the field would be changed as soon as the draft form is entered. Here is the relevant code: Template for editing Draft {{ title }}</B></h3></div> <div class="row"> <div class="col-sm-12-md-7 col-sm-offset-0 col-sm-8"> <div class="panel panel default"> <div class="panel-body"> <p class="well col-sm-offset-3 col-sm-12">{{ summary }}</p> <form class="form-horizontal" method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {% include 'posts/form-template.html' %} <div class="form-group col-sm-offset-3 col-sm-6"> <div class="col-sm-offset-9 col-sm-10"> <button type="submit" class="btn btn-primary">Send</button> </div> </div> </form> </div> </div> </div> </div> This my form for editing the draft class UpdateForm(forms.ModelForm): class Meta: model = Post fields = [ "title", "content", "categories", "tags", ] This is the Post model class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) title = models.CharField(max_length=100) content = HTMLField() draft = models.BooleanField(default=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) upvote = VotableManager() timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) categories = models.ManyToManyField( 'category.Category', help_text='Categorize this item.' ) tags … -
Is it possible to get Facebook user's ID when user clicks on postback payload?
I want to make a wishlist for every user on Facebook so that after searching product, user can add product to his/her wishlist. ( my bot will search and give a generic template back with product info and 2 postback buttons ) see screenshot. I use Django to save all data and I have made all the models but I need the user's id to create his/her wishlist before all this happens. I wonder if I can get Facebook user's id when he/she clicks on the postback button(1). Or do I have to make a request to Facebook?(2) I have also read about Account linking which allows user to loggin and identify him/herself to start the conversation, but with in way I need to build a website for user to create account and manage his/her wishlist on that website(3). If I'm wrong, please corret me. Which option should I choose? Or if you have a better idea, please let me know! I'm a junior programmer so I dont know what possible and what better to do but I can learn! Just show me the way. Thank you! -
Python List Segregation
I have a list of roughly 30,000 items that I am currently printing into a table with their associated relationships. I want to break apart this list into alphabetically segregated pages. Current list code is quite simple: {% for TblCompanies in object_list %} <tr> <td width="35">{{ TblCompanies.company_id }}</td> <td width="10"> </td> <td>{{ TblCompanies.company_name }}</td> <td>{{ TblCompanies.billing_address }}</td> </tr> {% endfor %} Could someone advise me on how to go about doing this and break down the code for me? Name____#___#___#__ _____________________ acari | 1 | 2 | 3 | |__A__|__B__|__C__|__ ... angle | 1 | 2 | 3 | | |______________ arhat | 1 | 2 | 3 | |Name_|_#_|_#_|_#_ akkra | 1 | 2 | 3 | | amiel | 1 | 2 | 3 | TO |acari| 1 | 2 | 3 | barce | 1 | 2 | 3 | |angle| 1 | 2 | 3 | bogie | 1 | 2 | 3 | |arhat| 1 | 2 | 3 | betty | 1 | 2 | 3 | |akkra| 1 | 2 | 3 | brill | 1 | 2 | 3 | |amiel| 1 | 2 | 3 | blyth | 1 | 2 … -
Track visitor information like Google Analytics
I am building a little dashboard-app in a Django where I want to combine tracking information for a few websites. Imagine it as the Google Analytics dashboard, but then my own. Google Analytics uses a javascript script on each page of the different websites. I want to build something like that too, but less comprehensive. To summarize: I want to know how I can create a little script for each website that sends the visitor data to my server and how to get this data into a Django model.