Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django, how could I get a value from html and interact with other python script?
If I have an html file in Django with an input box and a submit button. I want to grab what is to be typed into the input box and pass this value to another python file. Then this python script will return a value, and needed to be printed in website which the previous HTML shows. The flow is HTML(get input) - > python script (sort of calculation) - > HTML(print). I need to implement this in Django. Can anyone help me with it? -
Bluemix Cloud Foundry, Referencing static files in Django
I am attempting to learn Django development with Bluemix Cloud Foundry and Python 3.5.3. I have a hello world Website running at this time. But I cannot get static files like CSS to be served. I think my settings for finding static files are not correct. My served page is meant to look like: What I am getting is: I get the correct result locally with Debug = True in settings.py, but not with Debug = False. I cannot get the correct result when pushed to Bluemix, regardless of the Debug setting. My project folders are set up like this: the django staticfiles app is in my Installed_Apps variable. In my settings.py file I have: ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # STATICFILES_DIRS = [ # os.path.join(BASE_DIR, 'bluemixsite/static'), # os.path.join(BASE_DIR, 'bluemixapp/static'), # ] STATICFILES_DIRS appeared to make no difference with finding static files. The template page (being loaded) includes the following: ... {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'bluemixapp/stylesheet.css' %}" /> </head> .... With Debug=False, when inspected in firefox, I can see this message under the style editor both locally and on bluemix: The requested URL /static/bluemixapp/stylesheet.css was not found on this server. So either … -
Overriding Admin Templates in django 1.11
I don't get django 1.11 to accept a new base_site.html: Following docs and some posts i copied the file to: BASE_DIR/templates/base_site_html in settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], 'loaders': ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ), }, }, ] -
Django template {% empty %} inside if condition
I have a validation form like google translate community: Previously I have a conditions like below: {% for definition in definitions if not definition.creator == request.user %} {{ definition.description }} {% empty %} <p>Definition isn't available!</p> {% endfor %} But Jinja2 not allowing the loop comprehension, as his says: Jinja2 neither allows you to put arbitrary Python code into templates nor does it allow all Python expressions. The operators are limited to the most common ones and more advanced expressions such as list comprehensions and generator expressions are not supported. This keeps the template engine easier to maintain and templates more readable. more... Now in my case, I have a problem where I should put that {% empty %} condition, if I need the {% empty %} condition is inside {% if: {% for definition in definitions %} {% if not definition.creator == request.user %} {{ definition.description }} {% endif %} {% empty %} <p>Definition isn't available!</p> {% endfor %} To: {% for definition in definitions %} {% if not definition.creator == request.user %} {{ definition.description }} {% empty %} <p>Definition isn't available!</p> {% endif %} {% endfor %} I know my last code should be an error because the … -
Django - passing data in another function to html
So I pass some data from views.py to list.html (only shows the id in list.html) And I would like to pass the data of the selected id to detail.html for users to check details. What should I write in return of analysis_detail ? Here's part of the code. Many thanks! views.py def analysis_list(request): return render(request, 'analysis/list.html', { "analysis_list": [ { "id": "1", "sample_name": "samplefile1", }, { "id": "2", "sample_name": "samplefile2", }, { "id": "3", "sample_name": "samplefile3", }, { "id": "4", "sample_name": "samplefile4", } ] }) def analysis_detail(request, analysis_id): return render(request, 'analysis/detail.html', {}) urls.py urlpatterns = [ url(r'^(?P<analysis_id>\d+)$', login_required(views.analysis_detail), name="detail"), url(r'^comparison$', login_required(views.analysis_comparison), name="comparison"), ] -
Windows line breaks in plain text rendered using Django template
I am attempting to export data to a plain text file using Django 1.10 (Python 3.5) views/templates. This text file must be OS agnostic in that Windows users ought to have no trouble viewing the file. Unfortunately, when Django renders my template which has \r\n (Windows friendly) line breaks in the file, the line breaks are magically converted into \n (Mac/Linux friendly) line breaks. What gives? Here's how I'm attempting to render the plain text file: from django.template import loader, Context def myview(request): my_data = get_my_data() response = HttpResponse(content_type='text/plain') response['Content-Disposition'] = 'attachment; filename="export.txt"' template = loader.get_template('export.txt') # <- this file has \r\n line breaks context = Context({'data': my_data}) response.write(template.render(context)) return response Upon downloading the exported file using Chrome or Edge in Windows and opening in Notepad, the line breaks aren't respected, and upon viewing the file in Notepad++ (and showing EOL characters), only the \n character is there! Any help would be greatly appreciated :) -
Update audio/wav blob FileField in Django via AJAX
Having a real discouraging time trying to update a django field by saving a blob stored in JS variable via AJAX. Here's my view: def UpdateAudio(request): if request.method == 'POST': form = UpdateAudio(data= request.POST, files= request.FILES) if form.is_valid(): print('valid form') else: print ('invalid form') print (form.errors) return HttpResponseRedirect('/') the url: url(r'^update_audio/(?P<pk>[\w-]+)$', views.UpdateAudio, name='update_audio'), The form: class UpdateAudio(forms.ModelForm): class Meta: model = Sounds fields = [ 'sound', ] The form on the page: <form id='update_audio' method="post" class="" action="{% url 'posts:update_audio' instance.pk %}"> <input type="file" name="sound" id="id_sound" value=''> <input class="btn btn-primary" type="submit" value="Save" /> </form> And the AJAX: function upload() { var data = new FormData(); data.append('file', blob); $.ajax({ url: "{% url 'posts:update_audio' instance.pk %}", type: 'POST', data: data, cache: false, processData: false, contentType: false, success: function(data) { alert('success'); } }); return false; } $(function() { $('#update_audio').submit(upload); }); The blob is stored in the global var blob, which is being appended to the var data, which is a FormData instance. I'm getting a POST 403 Forbidden when trying to post. Any clues as to where I'm going wrong? Have been working on this for several days now and would really appreciate some pointers. -
What exactly works at Django views.py "variable" model = ...?
I'm using a class based views and I have problem with understanding views.py at Django. For example: views.py from django.views.generic import ListView from .models import Author class AuthorListView(ListView): model = Author What is a "model"? models.py: class Author(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) def __str__(self): return "{first_name} {last_name}".format(first_name=self.first_name, last_name=self.last_name) Somebody can give me a full explanation od "model" at views.py? I don't want to use "items" which I don't understand. -
uppdate and add in django not in same model
Hello guys i have two model related and i want one will be just add and other one will be updated views.py def entr(request): if request.method == 'POST' : c = Produit.objects.get(ref=request.POST["enrefprod"]) f = fournisseur.objects.get(codfour=request.POST["enreffour"]) qteentr = request.POST["qte"] print qteentr e = entrerstk( qteentr=qteentr, dateentr = request.POST["dat"], ref = c , codfour = f ) Produit.objects.filter(ref=c).update(qte=F('qte') + qteentr) e.save() return HttpResponseRedirect ('/ges/En_aff/') models.py class Produit(models.Model): ref=models.CharField(max_length=100, default='',primary_key=True) marq=models.CharField(max_length=100, default='') nomp=models.CharField(max_length=100, default='') qte = models.IntegerField(default=0) codecateg=models.ForeignKey(categorie, on_delete=models.CASCADE) class entrerstk(models.Model): identr=models.AutoField(primary_key=True) qteentr = models.IntegerField(default=0) dateentr=models.CharField(max_length=15,default=datetime.date.today()) ref=models.ForeignKey(Produit) codfour=models.ForeignKey(fournisseur) so i want when i add in entrestk an update in models produit in the qte ( old qte + new qte ) -
Welcome message after login in django 1.11?
Using django 1.11, I'm trying to show a bootstrap modal with some tips and a welcome message to the user after login. I'm using the django.contrib.auth views to login as follows on my urls.py: from django.conf.urls import url from django.contrib.auth import views as auth_views from companylogin.forms import LoginForm urlpatterns = [ url(r'^login/$', auth_views.LoginView.as_view(template_name='login/login.html', authentication_form=LoginForm), name='login'), url(r'^logout/$', auth_views.logout, {'next_page': '/login'}), ] Not sure if that is possible, if not, how can I pass a message only on loging? -
Can I use allauth and userena apps together in a django project?
allauth is an authentication app and userena is a user profile+authentication app. I have installed both, but both of them use accounts as the name of the app. This causes the problem in url.py file since I cannot have addresses directed to 2 different things. Is there any way I can solve this? urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('myapp.urls')), url(r'^accounts/', include('allauth.urls')), url(r'^accounts/', include('userena.urls')), ] -
Django save() overriding, best practice: on model, form or view?
I've been succesfully hashing my custom user model's passwords by overriding the save() function like this: def save(self, commit = True): user = super(RegisterForm, self).save(commit = False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user But I've placed this override on my register form definition, and it just occured to me that I could also do this in the User model definition, or in my register() view. Is there a "correct" place to override these functions, like clean() or save()? Is there any practical difference? ps: I'm not interested on using Django's default password-change and register views or forms. -
django cbv filter and search form
I have a FBV that have a filter in the template, which I'm processing with POST and a search processed by GET. What is the proper way to convert this code to a CBV? I'm thinking of using the TemplateView and overriding the get and post methods, but the way I'm thinking would be just to create the class and implementing the methods (there would be lot's of duplicated code). this is my view: def control_list(request): group_status = STATUS_LIST group_query_idx = 1 period_initial = date.today()-timedelta(days=30) period_final = date.today() if request.method == "POST": filter_form = FilterControl(request.POST) if filter_form.is_valid(): group_query_idx = int(filter_form.cleaned_data['group_status']) period_initial = filter_form.cleaned_data['period_initial'] period_final = filter_form.cleaned_data['period_final'] else: filter_form = FilterControl() if group_query_idx: filtered_groups = Group.objects.filter_by_status(group_status[group_query_idx]) queryset_list = Control.objects.filter_by_group_status(group_status[group_query_idx])\ .filter(published__range=[period_initial, period_final]) controls_per_group = {} for group in filtered_groups: control = queryset_list.filter(group_id=group.id) controls_per_group[group.title] = control context = { "object_list": queryset_list, "title": "Control", "page_request_var": page_request_var, "controls_per_group": controls_per_group, "column": range(10), "group_status": group_status, "filter_form": filter_form, } return render(request, "control_list.html", context) -
Python Django: open file, use later
I want to create a service (daemon) with Python and Django (important in Django). Common Idea: A big neural network file. I want load this file in start (long time operation), and use this, when I need (to work quickly). I think: I need to read a big file, process this (I will get string and list). Then I want use this string and list later, when I'll make a GET request. How can I realize this? May I can store this string and list anywhere? Or some else ideas? import pickle from keras.models import model_from_json def load_network(path): arch, weights, _ = pickle.load(open(path, 'rb')) # - long time operation # I want store anywhere string 'arch' and list 'weights' maybe nn = model_from_json(arch) nn.set_weights(weights) return nn -
Best image hosting for django
I am building a project using django, which will have lots of images sent by a users, so i wonder which image hosting i most suitable for django or mybe, i should host them directly on my server? -
How to render the POST results in a Django API view?
I have an APIView with a get and post method with two templates called tickets_per_day_no_results.html and tickets_per_day_results.html. When I get access to the results.html file, I have two drop-down menus and a search button that I use to fetch for data from an internal web API, something like the following:. My problem comes when I hit the search button, I end up with the results displayed as an APIView (I do not want these results, I want them to be transferred to my tickets_per_day_results.html file). This is the code I have now: urls.py from .views import ChartData7 urlpatterns = [ url(r'^$', views.index, name='index'), # home url(r'^statistics/$', views.statistics, name="statistics"), url(r'^tickets_per_day_no_results/$', ChartData7.as_view()), ] Views.py class ChartData7(APIView): def get(self,request): template_name = 'personal_website/tickets_per_day_no_results.html' form = DropDownMenuForm() return render(request, template_name, {'form': form}) def post(self,request): template_name = 'personal_website/tickets_per_day_results.html' if request.method == "POST": year = request.POST.get('select_year',None) week = request.POST.get('select_week', None) ....do stuff... data = {"label_number_days":label_number_days, "days_of_data": count_of_days,} return Reponse(data) return render(request, template_name) tickets_per_day_no_results {% block content %} <h3>Please, select the year and week number to retrieve the data.</h3> <form id="search_dates" method="POST"> {% csrf_token %} <h6>Select year</h6> <div class="row"> <div class="col-sm-8"> <select name="select_year"> <option value = {{form.year}}></option> </select> </div> <div class="col-sm-8"> <h6>Select week</h6> <select name="select_week"> <option value= {{form.week}}></option> … -
Update Django Filefield with AJAX
I'm working on a project that allows users to edit an audio file and save their edited file. The edited file is currently output as a Javascript audio/wav blob stored in a var named blob. I'm trying to pass it into an updateview that looks like this: class UpdateSound(AjaxableResponseMixin, UpdateView): model = Sounds form_class = PostForm template_name= 'update_sound.html' class AjaxableResponseMixin(object): def render_to_json_response(self, context, **response_kwargs): data = json.dumps(context) response_kwargs['content_type'] = 'application/json' return HttpResponse(data, **response_kwargs) def form_invalid(self, form): response = super(AjaxableResponseMixin, self).form_invalid(form) if self.request.is_ajax(): return self.render_to_json_response(form.errors, status=400) else: return response def form_valid(self, form): response = super(AjaxableResponseMixin, self).form_valid(form) if self.request.is_ajax(): data = { 'pk': self.object.pk, } return self.render_to_json_response(data) else: return response Which the AxaxableResponseMixin is some code I got from elsewhere and I'm not sure how it works exactly. It works for another updateview I have, but in this updateview I want to be able to pass the blob into the filefield without the user having to save the file locally, and upload it to the form generated by the updateview. My initial idea was to pass the blob as a vlue to the html input of the form, but doesn't look like it's possible due to security reasons. Here is the input … -
How to use django channels with rabbitmq to get live notifications on a websocket
I am a bit new to django channels and message queues in general. My requirement is as follows: Web page makes a websocket connection to django server django server needs to subscribe to channels (based on username) on a rabbitMQ server When a message arrives on subscribed channels, route it to the appropriate user web socket, and the web page updates UI I got a basic websocket sample app working as per http://channels.readthedocs.io/en/stable/ Now I'm at a loss how to proceed - I'm not sure which part of the python code runs in a persistent process. My guess is to try the following: In consumers.py, connect to the rabbitMQ server When a web socket connects, note which channel it needs and remember this connection, if necessary, subscribe to that channel with rabbitMQ When a message arrives on the channel from rabbitMQ, pass it onto the websocket 1 and 2 seem simple, but I have no clue how to do 3. How do I send a message to a web socket outside of it's receive handler? Do I need to use asgi_rabbitmq? Sorry if I am being vague, please ask any clarifications and I will make myself clear. -
Django and HTML5 Video - source tags are gone on Safari
I'm working with Django and I have a template like this: {% load formatting_tags %} {% load staticfiles %} <div class="utility-modal utility-modal__medium modal-dialog"> <div class="modal-content"> <div class="modal-content--header"> <h4 class="modal-content--header--title">{{ education_modal_title }}</h4> <button class="modal-content--header--action icon-close" data-dismiss="modal" title="Close"></button> </div> <div class="modal-content--body"> <video width="100%" controls="true" autoplay poster="{% static poster_url %}" id="video1"> <source src="{% static video_ogg_url %}" type="video/ogg; codecs=theora, vorbis"> <source src="{% static video_url %}" type="video/mp4; codecs=avc1.42E01E,mp4a.40.2"> <source src="{% static video_webm_url %}" type="video/webm; codecs=vp8, vorbis"> <p>Your browser does not support the video tag.</p> </video> </div> <div class="modal-content--footer"> <button onclick="document.location='{{ button_page_link }}'" class="btn btn__primary btn__block">Go to page</button> </div> </div> </div> The video urls are passed as variables from the view. This works fine on Chrome and Firefox, but not on Safari. On Safari, the three source tags inside the video are simply gone. Does anyone know what might be the issue? -
tracking user action in django
I am following a book and in the book I want to create a user follower system. But I got to a point where I dont understand what was in the book and I am hoping someone here can share more light on it for me. Kindly have in mind that I am using django all-auth as means of authentication. class Contact(models.Model): user_from = models.ForeignKey(User, related_name='rel_from_set') user_to = models.ForeignKey(User, related_name='rel_to_set') created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ('-created',) def __str__(self): return (self.user_from, self.user_to) I dont understand the implementation of the following line This is the Contact model we will use for user relationships. It contains the following fields: user_from: A ForeignKey for the user that creates the relationship user_to: A ForeignKey for the user being followed created: A DateTimeField field with auto_now_add=True to store the time when the relationship was created A database index is automatically created on ForeignKey fields. We use db_index=True to create a database index for the created field. This will improve query performance when ordering Query‐ Sets by this field. Using the ORM, we could create a relationship for a user user1 following another user user2, like this: user1 = User.objects.get(id=1) user2 = User.objects.get(id=2) Contact.objects.create(user_from=user1, … -
Django Allauth replace labels
I have the following form that ACCOUNT_SIGNUP_FORM_CLASS is pointing to class SignupForm(forms.Form): def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) for field_name in self.fields.keys(): print(field_name, self.fields[field_name].label) I'm trying to replace the labels for each of the following fields: username, email, password1 and password2. When the form is initiated, the following is printed. username Username email None But the rendered form in my browsers shows all of the fields with their labels Username* E-mail* Password* Password (again)* Why is it that only username and email are being printed, and why is email field label is None yet it shows just fine when it is rendered. How would I be able to change the labels of all four fields? -
Challenge: Generate the blood type of child from parents (literal)
[more of a challenge to see how others may do it better than anything else] The 'Person' model in Django has an object 'bloodtype'. I'm using a spawning routine to create people in a universe with 65536 "planets" (for want of a better description), one of it's subroutines determines the blood type of the new creation. If there's no existing populous, or no possible fertile options, the id of the parents (obviously 'Person' as well) will be equal. In this case a random blood type is returned. So far it appears to be working well, I've adopted the logic from a Red Cross site: Coming up with this routine: def getbloodtype(a,b): #a = Male parent, b = Female parent. (doesn't really matter) if a == b: return choice(( 'O+', 'O-', 'A+', 'A-', 'B+', 'B-', 'AB+', 'AB-' )) else: bloodA = Person.object.get(id=a).bloodtype bloodB = Person.object.get(id=b).bloodtype if bloodA == bloodB: if 'O' in bloodA: blood = 'O' elif 'AB' in bloodA: blood = choice(( 'A', 'B', 'AB' )) else: blood = choice(( 'O', bloodA )) elif ( 'AB' in bloodA ) or ( 'AB' in bloodB ): if ( 'O' in bloodA ) or ( 'O' in bloodB ): blood = choice(('A', … -
Django APIView get data from another class
I'm beginer in Django, I developed a class view wich get data from a form. using this data I run my algorithms and I want to show the result using a chart. So to send data from the view to the template I used APIview. but my problem is I can't get data from the first class which get data and run algorithm and send the result to the second class API view Thanks -
Django Exception ignored in: <bound method _TemporaryFileCloser.__del__ of <tempfile._TemporaryFileCloser object at 0x7f395ef0deb8>>
Hello I am using Django 1.11, DRF and Python 3.4 and i am getting annoying warning messages like this when posting via ajax to rest framework Exception ignored in: <bound method _TemporaryFileCloser.__del__ of <tempfile._TemporaryFileCloser object at 0x7f396409e208>> Traceback (most recent call last): File "/var/webapps/reactmusic/env/lib/python3.4/tempfile.py", line 505, in __del__ self.close() File "/var/webapps/reactmusic/env/lib/python3.4/tempfile.py", line 501, in close unlink(self.name) FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmp6hj_pqvj.upload' How can i prevent them ? PS. I understand that it is caused by this , but i don't want to increase max size. -
"@" users on my django project
Just a quick question. How can I implement the "@" feature used on most social networks on my django project. for example, @ludipie(ludipie being a username) should link to ludipie's profile page when clicked.