Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django admin display field from related model
I would like to display the ip_address from Hosts model in HostInfo's admin display. # models.py class Hosts(models.Model): host_name = models.CharField(max_length=200, unique=True) ip_address = models.GenericIPAddressField(protocol='both', unpack_ipv4=True) def __unicode__(self): return unicode(self.host_name) def hostip(self): return unicode(self.ip_address) and I have the below in admin.py # admin.py class HostInfoResource(resources.ModelResource): host = fields.Field(column_name='host', attribute='host', widget=ForeignKeyWidget(Hosts, 'host_name')) project = fields.Field(column_name='project', attribute='project', widget=ForeignKeyWidget(Project, 'project_name')) env = fields.Field(column_name='env', attribute='env', widget=ForeignKeyWidget(Env, 'env_name')) class Meta: model = HostInfo skip_unchanged = True import_id_fields = ('id', 'host','ticket','deployed_by') export_order = ('id', 'host', 'nexpose_level','cpus','memory','os', 'sudoers_copied', 'sudo_granted', 'extra_disks','app_type','app_name', 'vcenter_status','ticket','env','project','deployed_by', 'updated_on','created_on') class HostInfoAdmin(ImportExportModelAdmin): resource_class = HostInfoResource list_display = ['id', 'host', 'nexpose_level','cpus','memory','os', 'sudoers_copied', 'sudo_granted', 'extra_disks','app_type','app_name', 'vcenter_status','ticket','env','project','deployed_by'] readonly_fields = ('updated_on','created_on',) admin.site.register(HostInfo, HostInfoAdmin) I'm not quite understanding what I need to achieve this end. -
Embedding YouTube Videos from User Submitted Comments in Django Webpage
I am making a blog webpage in Django, and I have allowed comments for the blog posts. When a user submits a comment, I am able to use a function in my comment model to identify links they included in their text. I can also embed the video back in the template using an iframe and the list of urls the user had in the comment. The issue that I have is that I am wanting to show the embedded video in the exact same spot the user types in a link. For instance, if the user typed one paragraph of text, and then pasted in a YouTube link, and then they typed one more paragraph, I would want the video to be embedded in between the paragraphs. I have tried several things, but I just haven't been able to figure it out yet. I appreciate any answer I get. Here is the code for the comment model: class Comment(models.Model): post = models.ForeignKey('forum.Thread', related_name='comments') username = models.CharField(max_length=20,default='guest') text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text def get_youtube_urls(self): urls = [] youtube_regex = ( r'(https?://)?(www\.)?' '(youtube|youtu|youtube-nocookie)\.(com|be)/' '(watch\?v=|embed/|v/|.+\?v=)?([^&=%\?]{11})') matches = re.findall(youtube_regex, … -
Django and Praw for Reddit
My goal is to build a web app that gets data from reddit and displays that data in a page. The web app is being developed in a developer's environment with virtual environments. This was the 1st challenge. This way, one gets full control of versions, they won't clash with local versions and I'm also able to do different projects with different versions. Ok, so far so good. Then, the 2nd challenge was to build a web app with the following conditions: . Admin . Front-End . Blog . A page with a form Ok, so far so good, everything is working fine, the blog can be eddited from inside the admin. Then, the 3rd challenge was to create a form and post that data. That works and is JS alerted after success, using the following code: . form (header.html): <form id="redditor_form">{% csrf_token %} Name: <input type="text" name="redditor_name" id="redditor_name"> <br /> <input type="submit" value="Submit" /> </form> . script (header.html): <script type="text/javascript"> $(document).on('submit','#redditor_form', function(e){ e.preventDefault(); console.log("form submitted!") // sanity check $.ajax({ type: 'POST', url: 'redditor/search/', data:{ redditor_name:$('#redditor_name').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success:function(){ alert("it works!"); } }); }) </script> . urls.py: from django.conf.urls import url from . import views # Create your urls here. … -
RelatedObjectDoesNotExist User and no profile
I am extending User model of Django by following model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) favorites = models.ManyToManyField(Post, related_name='favorited_by') When I click on a button that calls the following view, def add_fav(request,pk): post = get_object_or_404(Post, pk=pk) form = PostForm(instance=post) post = form.save(commit=False) userprofile=request.user.profile with userprofile.favorites.all as favorite_posts: for post in post_list: if post not in favorite_posts: userprofile.favorites.add(post) userprofile.save() return redirect('post_list') I get the error RelatedObjectDoesNotExist User has no profile I applied migrations and everything. -
Too many queries - large dataset optimization in django
I'm creating web app which main aim is to look through the big dataset - about hundreds of thousands of rows and do some calcuations/show results. There is sth wrong in my code because my app makes too many queries and computing for about a few minutes what is unaccaptable. Can you tell me what shoud I do or show me the way. I know that there are iterators etc. but I don't know what would be the best. views.py def index(request): tableHTML = ObservationTable(['']) stations = [] jsonDataPlot = json.dumps({"x":1,"y":2}) if request.method == 'POST': form = ObservationForms(request.POST) if form.is_valid(): table_data = createObservationHTMLTable(form) stations = list(table_data.values_list('nr', 'nr').distinct()) table_list=list(table_data) #Here I'm using django-tables2 to put my data into html table (hit db) tableHTML = ObservationTable(table_list) #Here I'm creating JSON to suply Javascript plot library with data jsonDataPlot = json.dumps([ob.as_dict() for ob in table_list]) else: form = ObservationForms() return render(request, 'index.html', {'form': form, 'table': tableHTML, 'json_from_table': jsonDataPlot, 'stations_to_show': stations}) def createObservationHTMLTable(form): filterargs = {} if form.cleaned_data['sat_svn']: sat_svn = form.cleaned_data['sat_svn'] filterargs['sat_svn__svn']=sat_svn if form.cleaned_data['station']: station = form.cleaned_data['station'] filterargs['nr__nr']=station time_from = form.cleaned_data['time_from'] time_to = form.cleaned_data['time_to'] filterargs['date__range']=(time_from,time_to) #station_nr = form.cleaned_data['station'] data = Observation.objects.filter(**filterargs) return data models.py class Observation(models.Model): id=models.CharField(primary_key=True,max_length=20, verbose_name="ID") nr = models.ForeignKey('Station', to_field='nr',on_delete=models.CASCADE, verbose_name="NR") sat_svn … -
Composite Foreign Key in Django
I need a Composite Foreign Key in Django, which isn't supported. I could add it manually to the DB, or through migrations but then it won't be reflected in the model definition (sadpanda). The backend DB is postgres. Here's my models: class Trial(models.Model): kit = models.ForeignKey(to='Kit') class Kit(models.Model): name = models.CharField(max_length=500) class Component(models.Model): kit = models.ForeignKey(null=True, blank=True, to='Kit', related_name='components') class ComponentOverride(models.Model): trial = models.ForeignKey(to='Trial') kit = models.ForeignKey(to='Kit') component_to_replace = models.ForeignKey(to='Component', related_name='replaced') component_replace_with = models.ForeignKey(to='Component', related_name='replaced_with') I want a foreign key constraint on the ComponentOverride table of the columns trial_id and kit_id (trial and kit in the models) to the id and kit id columns on the trial table (id is auto created by django, kit in the model is kit_id in the table). Basically I want an equivalent to: ALTER TABLE app_label_trial ADD CONSTRAINT app_label_trial_unique_trial_id_kit_id UNIQUE (id, kit_id); ALTER TABLE app_label_componentoverride ADD CONSTRAINT app_label_componentoverride_comp_constraint_trial_id_kit_id FOREIGN KEY (kit_id, trial_id) REFERENCES app_label_trial(id, kit_id) DEFERRABLE INITIALLY DEFERRED; -
$http.get() function can't identify local server's json structured template | AngularJs | Django
I'm using angularjs with Django. Here is my angularjs script: <script> var app = angular.module('myApp',[]); app.controller('myCtrl', function($scope, $http){ $scope.name = 'sh'; $http.get('http://127.0.0.1:8000/json/ls/').then(function(response){ $scope.code = response.status; $scope.text = response.statusText; $scope.data = response.data; },function(){ $scope.message = 'not found!'; }); }); And here's my http://127.0.0.1:8000/json/ls/ page's result: {'record':[{'name':'your name','post':'dp'},{'name':'sdfsdfyour name','post':'sdfsfsfdp'},{'name':'your namefdsfsd','post':'dpsfdfsdf'},{'name':'your namesdfsdfs','post':'dpfsfdsfs'}]} But $http.get('http://127.0.0.1:8000/json/ls') function showing me it's $scope.message's data as result. And you know that this result will be only shown while $http.get() will be failed to find the specific page. Have any suggestion/solution, please? -
Fatal error while installing psycopg2 in virtualenv with Python 3.6 on Ubuntu 16.04
I did pip install psycopg2 and get the following error: ... ./psycopg/psycopg.h:30:20: fatal error: Python.h: No such file or directory compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 I looked at all the other answers and have already installed all python3-dev and libpq packages. -
Angular routing add an extra slash to my url
I'm using Angular on Django with Apache. And I have an app like the following: (function(){ 'use strict'; angular // AngularJS modules define applications .module('app', ['ngRoute']) .config(function($routeProvider) { $routeProvider .when("/", { templateUrl : "/static/app/foo/templates/main.html" }) .when("/red", { templateUrl : "/static/app/foo/templates/templates/red.html" }); }); function foo() { } })(); I'm serving my site on: http://localhost/ok/ When I make a GET to http://localhost/ok/ or to http://localhost/ok, all it's fine and the URL is transformed respectively to http://localhost/ok/#!/ or to http://localhost/ok#!/. In main.html I have a link to the red "anchor" <a href="#red">Go to Red</a>. It points to http://localhost/ok/#red but when I click it, red.html is not returned, and I read in the address bar http://localhost/ok/#!/#red or http://localhost/ok#!/#red (depending on the URL pattern of the first call). I do not understand where the problem is. How can I fix? -
How do I use a datepicker on a simple django form?
Before you mark this as a duplicate to the most famous django datepicker question on SO, hear me out. I have gone through all the questions in the first ten pages of the search results, but no one seems to be explaining anything from the beginning. What I am looking for is the most simple way to have a datepicker on my form, I don't know if the most simple way is importing it from Admin or using an existing Jquery thing, but whatever it is, can someone please explain step by step like you would do to a baby? This, I believe will help any new programmer like me out there who's looking to learn. This is what I have so far. My Form: class SampleForm(forms.Form): date_of_birth = forms.DateField(label='Enter Date') My View: def dlp_test(request): form = SampleForm() return render(request, 'dlp_test.html', {'form': form}) My Template: <form action="/your-name/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> This is the most simple setup anyone can start from, how do I take it from here? When someone clicks on the datefield in the HTML, I want a calendar to pop up so that they can select a date. If … -
Occasional Exit code -1073741819 (0xC0000005) with Django web app after a successful Run
I am a newbie in Django annd also first time using Python. I am making use of Pycharm 2016.3.2 + Django IDE with Python 3.6.0 . Anyway I am keen to build a website with Django and starting with this tutorial here -https://www.youtube.com/watch?v=aX4XjwW4AJQ Everything is going well apart from when I successfully run it for the first time and view the web app on browser. I then close the browser and close the Run/Debug session from the Debug window. After this, any subsequent attempts to run the Web app with report the following exit code for Run: manage.py runserver 8000 Process finished with exit code -1073741819 (0xC0000005) and for Debug runserver 8000 pydev debugger: process 10832 is connecting Connected to pydev debugger (build 163.10154.50) Process finished with exit code -1073741819 (0xC0000005) From the research I have done so far, this seems to be because of the runserver command not exiting after a Run. Indeed, Pydev instruct to use CTRL-BREAK to close this but pressing this doesn't do anything for me, would appreciate any help? -
Can a software which requires vagrant environment be downloaded using pip?
A software requires vagrant installation followed by vagrant up and vagrant ssh. These two commands take a lot of time when run for the first time. Is there any way that the installation of such a software be done using pip? The software is on Django. -
Search Engine Optimization with hash in url
I have a site xyz.com. It has urls like xyz.com#abc. Now the front end is in angular js and it is creating hash in url. My backend calls first go to nginx and from there they are redirected to my django server. Now SEO does not work properly when there are hashes in url. I searched a lot on google but could not find any solution. Any ideas are welcome. -
requests on app engine ('Connection aborted.', error(104, 'connection reset by peer'))
I am getting the below error on google app engine. I am using requests module version 2.13, python 2.7 and django 1.10.4 My code works fine on local development server but raises connection error in requests adapters.py. I not sure of the changes that need to be made while deploying for requests to work on app engine. can anyone help? Thank you! /base/data/home/apps/s~comtimes/app8.399095082090835876/lib/requests/adapters.py raise ConnectionError(err, request=request) conn <requests.packages.urllib3.connectionpool.HTTPSConnectionPool object at 0xfa973450> err ProtocolError('Connection aborted.', error(104, 'connection reset by peer')) proxies OrderedDict() request <PreparedRequest [GET]> self <requests.adapters.HTTPAdapter object at 0xfa973210> stream False timeout <requests.packages.urllib3.util.timeout.Timeout object at 0xfa9736d0> -
Django 1.10 modelform save issue
I am battling with something that should be simple. In fact, I have done this before, and I cannot seem to get my head around what's going on. All I want to do is save a modelform from my front end... I'm on Django 1.10 models.py class Information(forms.ModelForm): class Meta: model = Fathers fields = ('id','first','middle','last','city_of_birth','region_of_birth','country_of_birth',) def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_class='form-horizontal' self.helper.form_id = 'id-information' self.helper.form_method = 'post' self.helper.layout = Layout( Div( FormActions(Submit('dbPostother', 'Save data', css_class='btn btn-success btn-lg', action=".")), css_class = 'col-md-3' ) ) super(Information, self).__init__(*args,**kwargs) urls.py url(r'^dbPostother$',app.views.dbPostother,name='dbPostother'), views.py def dbPostother(request): if request.method == 'POST': form = Information(request.POST) if form.is_valid(): form.save() context = {'year':datetime.now().year} return render(request, 'app/index.html', context) models.py class Fathers(models.Model): id = models.BigIntegerField(primary_key = True,default=1) last = models.TextField(blank=True, null=True) first = models.TextField(blank=True, null=True) middle = models.TextField(blank=True, null=True) city_of_birth = models.ForeignKey(CitiesCity,blank=True, null=True) country_of_birth = models.ForeignKey(CitiesCountry,blank=True, null=True) region_of_birth = models.TextField(blank=True,null=True) def __unicode__(self): return self.first +" "+ self.last class Meta: managed = True db_table = 'fathers' verbose_name = 'Father' verbose_name_plural = 'Fathers' This should be simple - but the database is not updating... Thanks -
How to display a dict context in Django Template
How do you display a dict context passed to a template in Django? U tried these but I got errors and a blank respectively. {{ mydict['key1']['key2'] }} {{ mydict.key1.key2 }} -
optimal django project structure
The bigger my django project gets the more confused I get, how to properly structure it. Let's say I have a website called mysite. I create my first app music, which has a purpose of adding song information, albums and so on. I want all my HTML-files to look the same, so I create a subfolder templates (mysite/music/templates/music/header.html) and add the file header.html (suggested by django docs). This file extends all my other HTML-files and make them look the same. I put a style.css file, also in this directory. Or should I put both in "mysite/music/static/music/"? I decide to do it one of those ways and continue. Now I want the user to be able to register himself on my site. I read in the django doc, that each functionality of the website should be a new app. So I create the app register. I want to make a register form, which looks like the rest of my website. Good that I have a header file, which extends my register form. But wait, it's in the app music and it's really ugly (in my thinking) to go and extend with a file, stored in another app. So what do I … -
Testing Django Admin Action (redirecting/auth issue)
I'm trying to write tests for an Admin action in the change_list view. I referred to this question but couldn't get the test to work. Here's my code and issue: class StatusChangeTestCase(TestCase): """ Test case for batch changing 'status' to 'Show' or 'Hide' """ def setUp(self): self.categories = factories.CategoryFactory.create_batch(5) def test_status_hide(self): """ Test changing all Category instances to 'Hide' """ # Set Queryset to be hidden to_be_hidden = models.Category.objects.values_list('pk', flat=True) # Set POST data to be passed to changelist url data = { 'action': 'change_to_hide', '_selected_action': to_be_hidden } # Set change_url change_url = self.reverse('admin:product_category_changelist') # POST data to change_url response = self.post(change_url, data, follow=True) self.assertEqual( models.Category.objects.filter(status='show').count(), 0 ) def tearDown(self): models.Category.objects.all().delete() I tried using print to see what the response was and this is what I got: <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/admin/login/?next=/admin/product/category/"> It seems like it needs my login credentials - I tried to create a user in setUp() and log in as per Django docs on testing but it didn't seem to work. Any help would be appreciated! -
TensorFlow: error in use of tf.app.flags
I faced the same duplicate problem as error in use of tf.app.flags, but cannot understand how to solve ArgumentError: argument --model_dir: conflicting option string: --model_dir On server i see this problem, but in local PC all is working. I use Django 1.8.12, trying to invoke neural model from view. this is how it working on local PC: tf.flags.DEFINE_string("model_dir", None, "Directory to load model checkpoints from") this is how i tried to set model dir path on server: tf.flags.DEFINE_string("model_dir", "./runs/1486057482/", "Directory to load model checkpoints from") but this line throw error -
Django Endless Pagination - Multiple paginations in the same page
My Django version is 1.10.5 With Django Endless Pagination 3.0.1 i want to show two or more paginated lists(see code) on my site. For that i try to do this tutorial but the solution raises everytime an error if i use a second variable or multiple variables. The second variable(the querystring) in the tutorial is "other_entries_page". The answer from the testserver: Invalid arguments for u'paginate' tag I have no idea whats going wrong. Here is the code from the tutorial: {% load el_pagination_tags %} {% paginate entries %} {% for entry in entries %} {# your code to show the entry #} {% endfor %} {% show_pages %} {# "other_entries_page" is the new querystring key #} {% paginate other_entries using "other_entries_page" %} {% for entry in other_entries %} {# your code to show the entry #} {% endfor %} {% show_pages %} The variables that i mean are GET-variables(like: http://example.com/?page=2). I hope you can help me. -
Displaying multiple models on one template
I have a template which displays a master detail form represented by a formset object. That part is working fine. I have a second detail model which is read-only that I would like to display on the same template as the master-detail form. My view: def order_new(request): if request.method == "POST": form = OrderForm(request.POST) if form.is_valid(): order = form.save(commit=False) lineitem_formset = LineFormSet(request.POST, instance=order) if lineitem_formset.is_valid(): order.save() lineitem_formset.save() return redirect('order_detail', pk=order.pk) else: form = OrderForm() lineitem_formset = LineFormSet(instance=Orders()) return render(request, "orders/order_edit.html", {"form": form, "lineitem_formset": lineitem_formset,}) I have read a number of posts on this topic but cannot seem to make sense of rendering the third model on my template. Here are my models. class LineitemInfo(models.Model): order = models.ForeignKey('Orders') line_item_num = models.CharField(max_length=20) item_description = models.CharField(max_length=1020, blank=True, null=True) quantity = models.FloatField(blank=True, null=True) unit = models.CharField(max_length=20, blank=True, null=True) unit_price = models.FloatField(blank=True, null=True) line_account_code = models.CharField(max_length=260, blank=True, null=True) options = models.CharField(max_length=30, blank=True, null=True) option_num = models.CharField(max_length=8, blank=True, null=True) class Meta: unique_together = (('order', 'line_item_num'),) class Orders(models.Model): pr_num = models.CharField(max_length=80, blank=True, null=True) po_num = models.CharField(max_length=56, blank=True, null=True) task_order_num = models.CharField(max_length=40, blank=True, null=True) credit_card_id = models.CharField(max_length=40, blank=True, null=True) date_ordered = models.DateField(blank=True, null=True) vendor_name = models.CharField(max_length=200, blank=True, null=True) order_description = models.CharField(max_length=400, blank=True, null=True) predicted_order_total = models.DecimalField(max_digits=20, decimal_places=2, blank=True, … -
Certbot cannot reach nginx webroot running django
I'm working through https://serversforhackers.com/video/letsencrypt-for-free-easy-ssl-certificates and https://certbot.eff.org/docs/intro.html , trying to add an ssl certificate to my site. I tried: root@server:/opt/certbot# ./certbot-auto certonly --webroot -w /var/www/html --agree-tos --email me@yahoo.com -d mysite.com -d www.mysite.com --non-interactive Saving debug log to /var/log/letsencrypt/letsencrypt.log Obtaining a new certificate Performing the following challenges: http-01 challenge for mysite.com http-01 challenge for www.mysite.com Using the webroot path /var/www/html for all unmatched domains. ... IMPORTANT NOTES: - The following errors were reported by the server: Domain: example.com Type: unauthorized Detail: Invalid response from example.com.well-known/acme-challenge/gygb7wEj3o-_5MIoUgraBRddmqrtZdfIM-UWMySoNl8: Domain: www.example.com Type: unauthorized Detail: Invalid response from www.example.com.well-known/acme-challenge/z8oZ1FAiHBJNwWvLTI-g9hMZ5zoLdJSZBgaQ9CSTJU0: To fix these errors, please make sure that your domain name was entered correctly and the DNS A record(s) for that domain contain(s) the right IP address. root@server:/opt/certbot# cd . I checked the domain name and A record and they seem to be OK. In my browser I opened the link and I see the screenshot, which makes sense since I'm running a django app. How can I set things so that the certbot can access the webroot? -
How to join multiple models and get the result in pythonic way?
I have 4 models. User id name Subscription user_id title Address user_id street Wallet user_id balance Here I want to get the subscription rows along with the respected user address and wallet balance. Is that possible to retrieve in a single query (ORM)? I heard about select_related() and prefetch_related(). But not sure how to put all together in a single queryset. How can I achieve this in pythonic way? -
How to query database using django python?
I want to query data from database using django python. I read tutorial it alway read by edit models.py ,migrate , and add to admin.py then it can modify data in admin page. I want to read data from DB and show in index page. I was use php to query database but django different from php because django auto generate code. I think it easy to read data from DB and show in index page but I don't know how to do it with django . -
API DJANGO REST REALTIME WEBSOCKETS
I NEED TO MAKE A REST APP IN REAL TIME AND I ASK IF IT IS POSSIBLE TO DO IT WITH DJANGO-REST FRAMEWORK AND WEBSOCKETS OR I RECOMMEND IT?