Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I connect the Submit button to my .py file?
The goal of my program is to place the first and last name into my database upon it being entered and Submit button clicked by the user so that when I manually check in Terminal what’s in my database, I can see what the user has entered and submitted. I need to some how connect my Submit button to my views.py file so that it can go through , sort like an onClick() but this time, to go a .py file. (correct me if I’m wrong with this train of thought). How would I go about making this happen? Here's my views.py file: from django.http import HttpResponse from django.shortcuts import render from .models import Person def index(request): if request.method == 'POST': first_name = request.POST.get('firstName') last_name = request.POST.get('lastName') if first_name and last_name: user = Person.objects.create(firstName=first_name, lastName=last_name) user.save() return render(request, 'music/index.html') def detail(request, user_id): # Testing out page 2 return HttpResponse("<h2>Page # (testing this out) " + str(user_id) + "</h2>") Here's my index.html file: <!DOCTYPE html> <html lang="en"> <head> <title>The Page</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="index.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <form action="#"> <div class="form-group"> <label for="firstName">First Name:</label> <input type="email" class="form-control" id="firstName" … -
How to go about creating a json translation feature, in Django?
I am working on a project (the tech is Django Framework), and I have been assigned a task to create a functionality to store translations and create new translations of a given json file. The json file includes key, value pairs where the key is a unique key that the front-end of the app uses to tell where the text goes, which is the value. For example, { 'restaurant.wait':'Please wait while we process your order'}. So, I have a default json file with keys and values in English, and say we need a translation, I need to be able to get the values (easy part), show them to the translator, then he will input translations in a form with the translation for the given text. Now here comes the hard part, I need to then take this translation and map it back to the same keys in the json file. Another feature that this needs to have is to be able to export/import csv files of translations and then dynamically add them. I can't seem to figure out how to start solving this problem. I tried thinking of a model that I could have to hold the keys and to … -
generating commands on terminal FROM Django after user submits data on webpage
I have made a simple Django webapp which takes two strings outputs from user in the form of CharField but those two strings need to be instantly run on terminal with my "count.py" script to generate another webpage which shows the result from my count.py script. in terminal, command should be generated like this in backend after user submits data1 and data2 on webpage charfield: count.py data1 data2 where data1, data2 comes from views.py after user hits the submit button on webpage. Here is the code in my views.py def fields (request): form = first_form(request.POST or None) data1 = request.POST.get('data1') data2 = request.POST.get('data2') if form.is_valid(): #### how should i execute the arguments 'data1' and 'data2' run in terminal with my 'count.py' script ##### return render(request, "first_page.html", {'form': form}) and here is the code for my count.py: def count (a, b): word = False a = " " + a + " " b = " " + a + " " result = 0 for i in range (len (a)-1): if a[i] == " " and a[i+1] != " ": word = True result += 1 else: word = False for i in range (len (b)-1): if b[i] == " … -
(Django/Javascript/SQLite3): How does this "class*=" selector work? What does it do
I'm taking up a web dev project in Django that uses a database of greek and latin texts. This was worked on by multiple people, however I am taking up the project. I have introductory experience in Django and Javascript though, and while I've been able to learn a lot of new things I still have questions like this. So take a look at these lines of code in our main.js file. // Hide all text/book elements NOT part of the selected language: books.not("[class*='" + lang + "']").css("display", "none"); // Show all which are part of the selected language: books.filter("[class*='" + lang + "']").css("display", "block"); //What if I had a function that took books as an arg, and then app In truth, I just do not know what syntactically is happening with the term, "[class*=]". However, I have learned what the .filter() and .not() methods do, as well as the .css() method. However, these two lines of code seem to accomplish something important. They are able to determine which book objects are in the language that the lang variable (which is a string) specifies. display:none and display:block are applied when necessary. I just can't find any documentation on what this … -
Django could not parse the remainder
I looked through my code a few times and at all previous answers to this error and could still not find a solution. Below is the code in question: base.html: {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-COMPATIBLE" content="IE=edge"> <meta name="viewport" content="wideth=device-width, initial-scale=1"> <title>{% block title %}Rapid Prototypes {% endblock %}</title> <link rel="stylesheet" href="{% static 'css/site.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> </head> <body id="{% block body-id %}body{% endblock %}"> {% block top-nav-wrapper %} <div class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">Rapid Prototypes</a> </div> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li {% if slug=='index' %}class="active"{% endif %}> <a href="/">Home</a> </li> <li {% if slug=='contact' %}class="active"{% endif %}> <a href="{% url 'page' 'contact' %}">Contact</a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li {% if slug=='login' %}class="active"{% endif %}> <a href="{% url 'page' 'login' %}">Login</a> </li> </ul> </div> </div> </div> {% endblock %} {% block content %}{% endblock %} <script src="{% static 'js/jquery.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> </body> </html> The error is said to be on the 29th line which is the line with the first … -
Django formatting input contents
I am using simplemde markdown editor,which adds the markdown elements to the user contents, my problem is when user inputs the below line , with stakedit's block (** text **) and code (4 spaces ) I want to display it as below format This program is not working #include<iostream> int main() { cout<<"Hello world" } but when I save the contents and escape it, I get the following output This program is not working #include int main() { cout<<"Hello world" } in unformatted manner, how do I display it as formatted Here's the code I am using to display : {% block content %} {% if question_detail %} <h4><small> {{ question_detail.title }} </small></h4> <pre> {{ question_detail.get_description|escape |linebreaksbr }} </pre> {% else %} <small > an error occured </small> {% endif %} {% endblock %} get_description in models.py def get_description(self): return mark_safe (markdown(self.description)) -
Linear sum of foreign key count django
I have a profile class in my model like follow: class UserProfile(models.Model): first_name = .... .... I two other classes that has foreign key to profile model: class A(models.Model): profile = models.ForeignKey(UserProfile) .... class B(models.Model): profile = models.ForeignKey(UserProfile) Now I want to filter active users. I want something like follows. But I don't know how to do it in django! UserProfile.objects.filter((2*count(A) + count(B))__gte=10).all() -
Cron script runs fine but not updating Django database
I'm new in this field, and I am currently trying to get a python script to update a sqlite database (for django) every hour using cron. Here is a cut down version of the script import requests, sys, os, django, csv sys.path.append("\var[...]\django") os.environ["DJANGO_SETTINGS_MODULE"] = "s.settings" django.setup() from health.models import s_model import datetime import logging #################### initialising log file today = datetime.datetime.now() logging.basicConfig(filename="/var/[...]/processing.log", level=logging.INFO) logging.info("\nScript run at " + str(today) + "\n") ################### getting data from csv and saving it to DB with open('file.csv', 'rU') as csvfile: try: csvreader = csv.reader(csvfile, delimiter=',', quotechar='"') i=0 for row in csvreader: if(i>0): people = {} people['name'] = notNull(row[0].strip()) people['age'] = notNull(row[1].strip()) people = s_model(**people) people.save() i=i+1 except Exception: logging.error("Error processing number for id "+ str(row["Id"])) return And I have this file sitting in cron.hourly #!/bin/bash /var/[...]myfile.py What I have checked: When I check on the django pages the data from the databases isn't updated. When I run the myfile.py manually from its folder, it runs fine and the database updates immediately. There is a newline at the end of the cron file. I've checked the permissions (both the cron.hourly file and the myfile.py file have +x permission, and are owned by root) When I … -
Django form translation
How to translate form labels in Django? I'm trying to use ugettext_lazy, but there's no effect. All site content is translating the right way, but forms are not. User should have ability to change language manually, so I wrote LocaleMiddleware: class LocaleMiddleware(object): def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. if (request.user.is_authenticated): try: translation.activate(request.user.data.language) request.LANGUAGE_CODE = request.user.data.language except: translation.activate(settings.LANGUAGE_CODE) response = self.get_response(request) # Code to be executed for each request/response after # the view is called. translation.deactivate() return response But forms are still in default language. Form example: class DiscussionCreateForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={"name": "title", "id": "title", "class": "form-control"}), label=_("title").title()) first_message = forms.CharField(widget=forms.Textarea(attrs={"name": "first_message", "id": "message", "class": "form-control"}), label=_("message").title()) -
Referencing extended manytomany User model in Django...?
I'm having a few issues referencing an extended user model (UserProfile) within a template. What I have setup is the currently logged in user will be the "User object" associated to that comment. I have done this as follows: admin.py: class CommentAdmin(admin.ModelAdmin): list_display = ('created_by', 'post', 'created', 'active') list_filter = ('active', 'created') search_fields = ('created_by', 'body') def save_model(self, request, obj, form, change): instance = form.save(commit=False) if not hasattr(instance,'created_by'): instance.created_by = request.user instance.save() form.save_m2m() return instance def save_formset(self, request, form, formset, change): def set_user(instance): if not instance.created_by: instance.created_by = request.user instance.save() if formset.model == Comment: instances = formset.save(commit=False) map(set_user, instances) formset.save_m2m() return instances else: return formset.save() My Comment model is as follows: class Comment(models.Model): created_by = models.OneToOneField(User, related_name='created_by', null=True, blank=True) post = models.ForeignKey(Post, related_name='comments') body = models.TextField() created = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return "Comment by {} on {}".format(self.created_by, self.post) My UserProfile model extends the User model as follows: class UserProfile(models.Model): user = models.OneToOneField(User, related_name='userprofile') user_avatar = models.ImageField(storage=site_media_upload_location, null=True, blank=True) Everything works. I can save comments and associate all comments to the logged in user instance. The issue I now have is this: I want to display the user_avatar (as defined in the UserProfile … -
Django Developments Template_DIRS setting failed
I was recently trying to learn Django for one of my private project. When came to the Chapter on Template,the Django Book recommended setting template path in settings.py using the the following snippet TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__),'templates').replace('\\','/'),) However ,when I opened the file setting.py I found nothing like "TEMPLATE_DIR" but a list: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] the the value related to the key "DIR",was a empty list. So I try to filled it with the content shown above. And then, code something in the views.py(all the import was done ) def current_datetime(request): now = datetime.datetime.now() t = get_template("current_datetime.html") html = t.render(Context({"current_date" : now})) return HttpResponse(html) And then mkdir templates in the same folder with setting.py , saved current_datetime.html in folder templates Finally,run the project.and got the message in my terminal: WARNINGS: ?: (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 > and the TEMPLATES dictionary takes precedence. You must put the values of the > following settings into your default TEMPLATES dict: TEMPLATE_DIRS. System check identified 1 issue (0 silenced). June 15, 2017 - 15:32:49 Django version 1.11.2, using settings … -
Django Test mock instance of module variable
I'm trying to test my django app which has a proxy api which is instantiated in its own module. api.py class ProxyApi(object): def __init__(self, server_info): pass def validate_login(self, credentials): # call to real api here api = ProxyAPi() middlewares.py from mymodule.api import api class MyMiddleware(MiddlewareMixin): def process_request(self, request): if api.validate_login(): pass views.py from mymodule.api import api class TaskView(LoginRequiredMixin, FormView): def get(self, request): # do something with api tests.py class InputTasksViewTest(TestCase): @mock.patch('mymodule.api.ProxyAPi') def test_add(self, mock_api): mock_api.validate_login.return_value = True response = self.client.get(reverse('task')) The original validate_loginis still called. I would like to know how to handle the instantiation of ProxyApi while still retaining mocking capacity. -
Why is Django admin interface uglier on Chrome?
I'm building a website using django. Here's my question : Why is the admin section style ugly (using chromium and chrome, not firefox) and how to avoid it? The "incognito" mode of both chromium and chrome seems to fix it Here's a screen of the admin section using chromium: screen 1 Here's a screen of the admin section using chromium in incognito mode : screen 2 -
Can't get and filter object in database by slug parametr, how to fix? i'm noob
for this function using ajax request We need to get the object from the database, by slug, "slug" we get from the ajax request, and it's like a string, but the get method and the filter method give an error, ostensibly there is no such record, although it exists, how to solve this problem? error exactly in get not some grammar mistake, in query set!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! query just can't accept the string as parametr def mark_and_unmark_this_episode(request): return_dict = {} data = request.POST serial_slug = data.get('serial_slug') season_slug = data.get('season_slug') series_slug = data.get('series_slug') is_delete = data.get('is_delete') serie = get_object_or_404(Series, serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug) #seriess = Series.objects.filter(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug) print(serie) user = request.user watched_serial = seriess.serial_of_this_series watched_serie = seriess minutes_of_series = seriess this part of views.py generic content on same page like error up, there this is work, i can get and filter by slug, Since these slugs are written in the parameters of the function, and everything works there, although in fact this slug is a string, but here everything works, here is this code! def post_of_serie(request, serial_slug=None, season_slug=None, series_slug=None): serie = get_object_or_404(Series, serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug) #print(serie) title = serie.serial_of_this_series.rus_name_of_seriall full_path = All_Images_Of_The_Series.objects.filter(to_series__serial_of_this_series__slug=serial_slug, to_series__season_of_this_series__slug=season_slug, to_series__slug=series_slug, is_poster=True) context = {"serie":serie, "full_path":full_path, "title":title,} try: userr = … -
Why am I getting an AttributeError?
I'm trying to store the first name and last name of a user in my datatbase upon hitting the submit button so that next time when I manually check in Terminal what's inside my database, I can see exactly what the user inputted. This is the error I'm getting: I'm assuming the error is coming from my views.py file: from django.http import HttpResponse from .models import Person from django.shortcuts import render def index(request): if request.method == 'POST': first_name = request.POST.get('firstName') last_name = request.POST.get('lastName') if first_name and last_name: user = Person.objects.create(firstName=first_name, lastName=last_name) user.save() return render('request', 'music/index.html') def detail(request, user_id): # Testing out page 2 return HttpResponse("<h2>Page # (testing this out) " + str(user_id) + "</h2>") -
Django user permissions on model objects
What I am trying to do is, to add a ManyToManyField when I create an object from a model and I can specify, which User or/and Group can view/edit the object. As an example: #models.py class Article(models.Model): name = models.CharField(max_length=30) editors = models.ManyToManyField(User) #other stuff I know I can use the default permissions and define, who can edit the Article model, but my goal is when creating article1 for example, I would like to be able to select that only User1 and Group1 are able to see/edit it. I've read that django-guardian does something similar, but is it possible to just extend the model with a ManyToMany Relationships? -
Can not push the data into array using python
I need one help. I am trying to push data into array using python but getting the following error. root[].append({'lname':lname,'roomname':roomname,'seat':seat,'project':project,'video':video}) ^ SyntaxError: invalid syntax I am explaining my code below. def viewbook(request): doc = minidom.parse("roomlist.xml") staffs = doc.getElementsByTagName("location") for staff in staffs: lname=staff.getAttribute("name"); roomname=staff.getElementsByTagName("roomname")[0] seat=staff.getElementsByTagName("noseats")[0] project=staff.getElementsByTagName("projectorscreen")[0] video=staff.getElementsByTagName("videoconf")[0] root[].append({'lname':lname,'roomname':roomname,'seat':seat,'project':project,'video':video}) return render(request,'booking/viewbook.html',{'people': root}) Here I need to push the set of data into one array. Please help me. -
Django markdown using markdown-deux not working properly
{% load markdown_deux_tags %} {% block content %} {% if question_detail %} <h4><small> {{ question_detail.title }} </small></h4> {% markdown STYLE %} this is **cool** {{ question_detail.description }} #description = **yes because it is not working ** {% endmarkdown %} output : this is cool * yes because it is not working * why it is not getting markdown completely ? am I missing something ? -
Facebook page post is not identifying the its instant article
I am creating Facebook instant article using API. Article is getting created, it's getting live but its not getting linked to its Facebook post. Canonical urls is also right. I am using Facebook api to create instant article in python. I am getting long lived access token from short lived user access token. When i am creating the instant article from Facebook publishing tool using Facebook UI manually then it's getting linked to it's original post, but when i am creating through API it's not getting linked to it's original post. I am using Facebook sdk for python. The way i am creating long lived access token is import facebook def create_long_lived_access_token(app_id, app_secret, user_access_token): # Create fb graph object graph = Facebook.GraphAPI(user_access_token) # Now extend it with the extend_access_token method extended_token = graph.extend_access_token(app_id=app_id, app_secret=app_secret) # Confirm token now expires in ~ 60 days or 5184000 seconds print(extended_token) extended_token = extended_token['access_token'] return extended_token user_access token has "pages_manage_instant_articles", "pages_show_list" and all other available permissions. And this access token is created using the Facebook app i created. And i am creating Facebook instant article bellow import facebook def create_instant_article(blog): canonical_url = "http://myweb.com/{0}/".format(blog.slug) final_html = get_final_html(blog, canonical_url) try: extended_token = FacebookData.objects.get(id=1).long_lived_token except: try: extended_token … -
Python 3.6/ Django1.10 @login_required decorator redirects to link with missing "/"
I am using a decorator login_required on my project Django 1.10 Python 3.6.It redirects to "http://127.0.0.1:8000/accounts/login?next=/profile/ " this link but throws an URL error. Whereas when I manually amend the above link with this "http://127.0.0.1:8000/accounts/login/?next=/profile/" link with a "/" after login it works fine. So I assume it is an issue with the unicode "/" that doesnt get rendered when redirected.[![ScreenShot of the error report1. How can I make this "/" rendered after "login" ? -
Django Moving lookup table to Redis
I have a django app with redis which is currently used as the broker for Celery, and nothing beyond that. I would like to utilize it further for lookup caching. Let's say I had a widely used table in my database that I keep hitting for lookups. For the same of example, let's say it's a mapping of U.S. zip codes to city/state names, or any lookup that may actually change over time that's important to my application. My questions are: Once the server starts (in my case, Gunicorn), how do I one-time load the data from the database table to Redis. I mean- where and how do I make this one time call? Is there a place in the django framework for such "onload" calls? or do I simply trigger it lazy-style, upon the first request which will be served from the database, but trigger a Redis load of the entire table? What about updates? If the database table is updated somehow, (e.g. row deleted, row updated, row added) how do I catch that in order to update the Redis representation of it? Is there a best-practice or library already geared toward exactly that? -
Items disappear from queryset after update
Using Django 1.9, I have some code that makes two select queries on the same table in the same function. The code looks like this: foo_ids = [1] # A list of (actually uuids) foo_qs = Foo.objects.filter(id__in=foo_ids, bar=False) At this point, if I have print the queryset in the code, it would show at least one item: print foo_qs # [<Foo: Foo(id='1', ...)] So I perform an update() on this queryset, modifying bar, but not id. rows_updated = foo_qs.update(bar=True) # 1 updated At this point, print foo_qs will yield []. Since bar=False is no longer met, this is expected. But if I now then create a new queryset under the code, such that the file looks similar to this: foo_ids = [1] foo_qs = Foo.objects.filter(id__in=foo_ids, bar=False) rows_updated = foo_qs.update(bar=True) new_foo_qs = Foo.objects.filter(id__in=foo_ids) # Should contain 1 record Despite records being in the database, new_foo_qs also contains nothing! This can be resolved by first converting foo_ids to a set, like so. foo_ids = [1] foo_qs = Foo.objects.filter(id__in=foo_ids, bar=False) rows_updated = foo_qs.update(bar=True) foo_ids = set(foo_ids) new_foo_qs = Foo.objects.filter(id__in=foo_ids) # 1 record Why is this happening? Is this some caching mechanism I need to know about? -
Django error: could not parse the remainder: ': "Y-m-d"' from 'post.date|date: "Y-m-d"'
I'm creating a blog post and after migrating my blog files successfully I am returned an error when I go to the blog page of my website ( Could not parse the remainder: ': "Y-m-d"' from 'post.date|date: "Y-m-d"') I cant seem to find whether this is a syntax error or a logic error HTML: {% extends "personal/header.html" %} {% block content %} {% for post in object_list %} <h5> {{ post.date|date: "Y-m-d"}} <a href="/blog/{{ post.id }}"> {{ post.title }} </a> </h5> {% endfor %} {% endblock %} Python (models.py): from django.db import models class Post (models.Model): title = models.CharField(max_length=140) body = models.TextField() date = models.DateTimeField() def __unicode__(self): return self.title -
How to set more than one page in django
After I code more than one page in url.py and run it.I can't the page I want see.The browser show me "ERR_CONNECTION_REFUSED".By the way,when I have only one page,it works.I need someone help me,thanks. My code: from django.conf.urls import url from django.contrib import admin from mysite.views import * urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^hello/',hello), ] -
Nginx/Django File Upload Permissions
Today I noticed that whenever I upload a file through my Django site the file is uploaded with the file permissions 0600 meaning whenever a non root user wants to view the file (nginx) a 403 is shown. This only started happening today from what I can tell. I have checked both the file_upload_permissions and file_upload_directory_permissions in the Django settings file and they are both set to 0644. I haven't done any Linux/Django updates recently so that shouldn't be the cause, any help would be greatly appreciated. Thanks, Sam