Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Media files "Could not load image" with 200 status response
I'm slightly new to Django and I'm having an issue with the ImageField field type in development environment. I'm able to upload images through the admin panel, and I have them going to my media folder location locally. But they will not render in the DOM from Django. I'm running Django 2.1.7 and have Pillow 5.4.1 installed My media folder is located in my base directory (same level as my manage.py file), and has a sub-directory of series (as created by my model), with all of the correct images I uploaded through the admin panel. Within my template .html file, I am trying to load the image with: {% load static %} <img src="{{ s.cardImage.url }}"> And I get a 200 status response in the terminal, but the image does not render and when I inspect the image, it says "Could not load image". If I simply output {{ s.cardImage.url }} within my template, I get this path: /media/series/IMG_5776.PNG. So I'm inclined to think that my views are correct and I'm querying the correct object from my database. When I uploaded the image within the Admin panel, this is what it looks like: Admin Panel If I click on that … -
How do you call a view from one app in another
I have two apps the posts and home..How do I call one of the functions from my posts app in my home app. That way all information would be displayed on my home.html page. home/views.py from posts import views from posts.models import Post # TODO: Found a hacky way to display all posts on home page def home(request): # TODO: If the user is not authenticated then don't show the home page, # but instead show soe other page reporting the error. (Maybe just the login page). #Not sure if I should call it like this. #views.posts_list(request, "home.html") return render(request, 'home.html') posts/views.py def posts_list(request): # return HttpResponse("<h1> List a posts. </h1>") # TODO: Privacy stuff queryset = Post.objects.all() context = { "object_list": queryset, "user": "username" } return render(request, "home.html", context) home.html <html> <body> <h1>Homepage</h1> {% if user.is_authenticated %} <h1>What's on your mind, {{ user }}</h1> <!-- {% for obj in object_list %} {{ obj.user }} <br /> {{ obj.content }} <br /> {{ obj.timestamp }} <br /> {% endfor %} --> {% endif %} </body> </html> -
Django generic views form
I am working on an online leave system when staff can use the system to apply for leave and get their leave approved online. Once an applicant launch leaves, the leave are stored on the DB. where the authorizer can view the leaves on a table. To authorize a leave the authorizer click on a respective row where he then gets a form to authorize the leave. When I try to process the form to authorize the leave I get an error message: could not convert string to float: class NewLeave(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) APPROVAL_STATUS_CHOICES=( ('Pending','Pending'), ('Approved','Approved'), ('Rejected','Rejected'), ) Director_Authorization_Status = models.CharField(max_length = 100, choices = APPROVAL_STATUS_CHOICES, default = 'Pending', blank = False) def save(self, *args, **kwargs): getid= NewLeave.objects.get(pk=pk) minus_value = self.Total_working_days if (self.Director_Authorization_Status == 'Approved'): LeaveBalance.objects.filter(pk=pk).update(Leave_current_balance=F('Leave_current_balance') - minus_value) return super(NewLeave, self).save(*args, **kwargs) else: return super(NewLeave, self).save(*args, **kwargs) class NewLeaveCreate(CreateView): model = NewLeave fields = ('Director_Authorization_Status','Authorized_by_Director') def form_valid(self, form): super().form_valid(form) auth_status = form.cleaned_data['Director_Authorization_Status'] if (auth_status == 'Approved'): return redirect('myapp:success_page') elif (auth_status == 'Pending'): return redirect('myapp:pending_success') else: return redirect('myapp:rejected_success') Traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/newleave/6 Django Version: 2.1.7 Python Version: 3.6.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', … -
How can I snapshot the state of my Google App Engine application and upload it to a separate Google Cloud Storage?
I am setting up a relationship where two Google App Engine applications (A and B) need to share data. B needs to read data from A, but A is not directly accessible to B. I have an idea where I take a snapshot of A's state and upload it to a separate Google Cloud Storage location. This location can be read by B. Is it possible to take a snapshot of B using Google App Engine and upload this snapshot (perhaps in JSON) to a separate Google Cloud Storage location to be read from by A? If so, how? -
Html alert box pop up on condition
In my django project, I want to build one function in my html page to show the alert frame if some output from the view.py equals to some number. Like, after clicking the button, the view.py function do the calculation and give the output, and if the number equals to one set in the html function, it will show the alert. How could I fulfill it? For example: Here's the button in html: <form action="{% url 'xx:aaa' %}" method='GET'>start</form> In the view.py function aaa will process the data and give one output m. I want to fulfill that if m equals to n in html function, it will show alert box, if m does no equal to n, the alert box won't show. How can I do it? Thx! -
How can I modify the response.content in a Django Middleware __call__ method
I'm trying to remove all blank lines in xml response by processing it in a middleware as suggested in this example: https://code.djangoproject.com/wiki/StripWhitespaceMiddleware Now the problem is that in Django 2.1 that code is no more current since Dajngo 1.10 the way the Middleware works change quite a bit. Now I see that the response.content is of type bytes and so no straightforward editable with regex. What is the correct way to do this in Django 1.10+? -
ModelFormset_factory how to modify previously saved data
I've stuck in this issue for three days and really appreciate any suggestions or help. I've created a formset using modelformset_factory and successfully save data to the database. I also successful load the data using queryset. Right now i want to modify the data but it always hit an formset invalid error "id is required". I don't know where goes wrong and i read the documentation but couldn't find anything help. Here is my form: FocusFormset = modelformset_factory( startupFocus, fields=('name',), widgets={ 'name': forms.TextInput( attrs={ 'placeholder': 'Enter Area of Focus here', 'label': 'Area of Interests', } ) } ) Here is my view: if request.method == 'POST': edit_form_io = update_startup_info_form(request.POST, instance=current_user) formset = FocusFormset(request.POST) if edit_form_io.is_valid() and formset.is_valid(): # print(formset) edit_form_io.save() instances = formset.save(commit=False) for instance in instances: instance.myUser = current_user instance.name = instance["name"] instance.save() return redirect('../display-profile') Here is my model: class startupFocus(models.Model): name = models.CharField(max_length=255, verbose_name='Area of Interests:') myUser = models.ForeignKey( MyUser, on_delete=models.SET_NULL, null=True ) def __str__(self): return self.name Here is my template looks like: template -
Django Static file wont load in Block Content even when {% load static %} is applied
I can't load my static particles.js file inside my block content even when I have load static in my file. {% extends 'base.html' %} {% load static %} {% block content %} <!--Particles--> <script src="{% static 'particles/particles.js' %}" defer="defer"></script> <script src="https://cdn.jsdelivr.net/npm/particles.js@2.0.0/particles.min.js"></script> In chrome I am getting this error GET http://localhost:8000/static/particles/particles.js net::ERR_ABORTED 404 (Not Found) Although it is pointing to the right place. -
Render 2 models on the same template using CBV
I am trying to render two differents models using a loop in my templates/dashboard/home.html using Class Based View. Let's have a look on my code : views.py class DashboardListView(ListView): model = Links template_name = 'dashboard/home.html' class ContentListView(ListView): model = Dashboard template_name = 'dashboard/home.html' First I would like to used the same ListView but was unable to do so. My home.html {% for dashboard in object_list %} {{dashboard.content}} {% endfor %} {% for links in object_list %} {{links.content}} {% endfor %} I would like to render those two models but I can only render one and the other object list will take the content for the preivous one. Thanks for your help -
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_a661306a439a8a536a6131afb3654efa/static'
I'm setting my django,use "git push heroku master",something problem happend STATIC_URL = '/static/' LOGIN_URL='/login/' BOOTSTRAP3={ 'include_jquery':True, } import dj_database_url SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTO','https') ALLOWED_HOSTS=['*'] STATIC_ROOT=os.path.join(BASE_DIR,'static') STATICFILES_DIRS=[os.path.join(BASE_DIR,'static'),] -
Can't render model using CBV using django
I am currently learning CBV and using it over function view, however I have difficulty rendering it. My template is as follow Post_list.html {% for post in post_list %} <p class="article-content">{{ object.content }}</p> {% endfor %} and my view class PostListView(ListView): model = Post I want to render it into a loop like i used to do with function view. Thanks -
(Django, Nginx) Prevent client browsers from caching static files?
My website uses Django, Gunicorn, and Ngnix. I'm trying to get client browsers that access my website to always get the latest static files without having to press Ctrl+F5 to clear the browser cache to get the new static files. I've found in many places answers similar to the following: Modify file /etc/ngnix/sites-enabled. $Sudo Nano mysite. Add the following code the the server block. location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { expires -1; } The only thing that ever happens is either the static files don't load at all or they do load but but the browser is still caching them and they need to be manually cleared by ctrl+F5. How can I get the browsers to fetch new static files each time? -
Whick programming language about web development is more easily work with mobile applications
Which programming languages (django, C# asp.net, php with can contact and very fastly and securely communicate with website and application? -
Retrieving checkbox output from a template and sending it to a secondary view
I have this template that outputs objects (yoga positions) in a standard blog format of sorts. Users may upload new yoga positions to the site via a different form and that all works dandily, however... In the template I've now added a checkbox to every object that will be generated within each "post" and the idea is that the user should be able to select a variety of posts at their leisure (no one wants to do 2,396 yogapositions in one go I've come to realise...) and then hit a submit button, and then get redirected to a new page where the now filtered out posts will be displayed in a js driven "movie clip" with a timer. The goal is to create a personal yoga/exercise app. The template looks something like this: {% for res in results %} <h2 align="center"> {{ res.name }} </h2> <div class="" align="center"> <img src="/media/{{ res.image }}" alt="" style="width:100%; border-radius:6px;"> </div> <h4 style="margin-left:30px; margin-bottom:0px; margin-top:12px;"> What it does: </h4> <p style="margin-left:30px; margin-top:0px;"> {{ res.description }} </p> <h4 style="margin-left:30px; margin-bottom:0px;"> How to do it: </h4> <p style="margin-left:30px; margin-top:0px;"> {{ res.instruction }} </p> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> {% endfor %} <a href="{% url … -
Should app to send daily digest be a part of website solution?
I am developing a website using Django framework. I have built a solution "blogsite". I am sending daily mails as digest to subscribers. I have a python app which is being scheduled using cron-tab. Should this app be made part of my website solution for completeness or should be treated as separate project? -
Django ImageField image upload failing when uploading with Android
I set up an Item model (simplified here): class Item(models.Model): image = models.ImageField( blank=True, null=True, upload_to=user_directory_path ) with the following view class class Create(generic.CreateView): template_name = 'items/create.html' model = Item fields = [ 'image', ] and use the following template: { % extends "base.html" %} {% block title %} New Item {% endblock %} {% block content %} <form method="post" enctype="multipart/form-data" data-ajax="false"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> {% endblock %} Image upload works fine using Desktop but fails using android. There is not error message, aside from that the image can not be found by the server. The upload works fine from Desktop and displays the image. Smaller images from android also upload without issue. I set FILE_UPLOAD_MAX_MEMORY_SIZE = 10 * 1024 * 1024 in setting.py, to eliminate a filesize issue, but the behavior continues. It surely must be possible to upload files from mobile, but I have a hard time finding out what is wrong here. Any pointers are appreciated. -
Saving proccess variables on another django model
Currently I am developing a workflow aplication for my company. I have already created the flow and models for the process and everything on that regard is working fine. What i would like to do now is to save each of the proccess variables in a custom database to be able to use it later. I was trying to create a custom view in which I could pass the process parameters and save them in the new data base, but I dont know how to do this. models.py class DeliveryProcess(Process): nombre_del_entregable= models.CharField(max_length=150) fecha_inicio=models.DateField(auto_now_add=False, default=datetime.now) fecha_de_terminacion=models.DateField(auto_now=False, default=datetime.now) ejecutor=models.ForeignKey( User,on_delete=models.CASCADE, null=True, related_name='+') observaciones_asignador=models.TextField() fecha_de_ejecucion=models.DateField( auto_now_add=False, default=datetime.now) oberservaciones_ejecutor=models.TextField() finalizado= models.BooleanField(default=False) revisor=models.ForeignKey( User,on_delete=models.CASCADE, null=True, related_name='+') aprobacion_final= models.BooleanField(default=False) anadir_revisor= models.BooleanField(default=False) nuevo_revisor= models.ForeignKey( User,on_delete=models.CASCADE, null=True, related_name='+') obserservaciones_revisor= models.TextField() class Revisiones(models.Model): id_revision= models.AutoField(primary_key=True) revisor=models.ForeignKey(User,on_delete=models.CASCADE, null=True, related_name='+') obserservaciones_revisor= models.TextField() flows.py class Delivery_flow(Flow): process_class = DeliveryProcess start = ( flow.Start( CreateProcessView, fields=["nombre_del_entregable", "fecha_inicio", 'fecha_de_terminacion', 'ejecutor','observaciones_asignador'] ).Next(this.ejecutar) ) ejecutar = ( flow.View( UpdateProcessView, fields=["fecha_de_ejecucion", "oberservaciones_ejecutor", "finalizado","revisor"], task_description="Ejecutar" ).Assign(lambda act: act.process.ejecutor ).Next(this.revisor_check) ) revisor_check = ( flow.View( views.ReView, fields= ["aprobacion_final",'anadir_revisor',"revisor",'oberservaciones_revisor'] ).Assign(lambda act: act.process.revisor) .Next(this.split) ) split =( #If(lambda activation: activation.process.aprobacion_final) flow.Switch() .Case(this.end, cond=(lambda act: act.process.aprobacion_final)) .Case(this.revisor_check, cond=(lambda act: act.process.anadir_revisor)) .Case(this.ejecutar, cond=(not(lambda act: act.process.aprobacion_finale) and (lambda act: act.process.anadir_revisor))) ) end = flow.End() … -
Django search autocomplete on table´s new line
I implemented Django Search Autocomplete from https://medium.com/@ninajlu/django-ajax-jquery-search-autocomplete-d4b4bf6494dd and its working just fine. Im using it on a table input. views.py: def autocompleteModelMaterial(request): if request.is_ajax(): q = request.GET.get('term', '') search_qs = Material_tabela.objects.filter(nome_material__istartswith=q) results = [] print( q) for r in search_qs: results.append(r.nome_material) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) urls.py: url(r'^ajax_calls/searchMaterial/', views.autocompleteModelMaterial), JQuery: <link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" media="all" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script> javascript that calls ajax: $(document).ready(function(){ $("#nome_material").autocomplete({ source: "/ajax_calls/searchMaterial/", minLength: 2, open: function(){ setTimeout(function () { $('.ui-autocomplete').css('z-index', 99); }, 0); } }); }); html -> form: <form action="" method="post" enctype="application/x-www-form-urlencoded"> {% csrf_token %} {{ form.as_p }} <table id="leituras_table" class="table table-striped table-hover vertical-scroll tablesorter" onscroll="rolarOutraBarra('leituras_table', 'scroller');"> <thead> <tr id="linha1"> <th>Nome material</th> <th>Empresa 1</th> <th>Valor 1</th> <th>Empresa 2</th> <th>Valor 2</th> <th>Empresa 3</th> <th>Valor 3</th> <th>Valor a utilizar</th> </tr> </thead> <tbody> <tr> <td><input style="text-align:center;" id="nome_material" class="form-control input-group-lg" type="text" name="nome_material1"></td> <td><input style="text-align:center;" id="empresa1_1" class="form-control input-group-lg" type="text" name="empresa1_1"></td> <td><input style="text-align:center;" id="valor1_1" class="form-control input-group-lg" type="text" name="valor1_1"></td> <td><input style="text-align:center;" id="empresa1_2" class="form-control input-group-lg" type="text" name="empresa1_2"></td> <td><input style="text-align:center;" id="valor1_2" class="form-control input-group-lg" type="text" name="valor1_2"></td> <td><input style="text-align:center;" id="empresa1_3" class="form-control input-group-lg" type="text" name="empresa1_3"></td> <td><input style="text-align:center;" id="valor1_3" class="form-control input-group-lg" type="text" name="valor1_3"></td> <td><input style="text-align:center;" id="valorFinal_1" class="form-control input-group-lg" type="text" name="valorFinal_1"></td> </tr> </tbody> </table> <br> <center> … -
django rest Framework : Abstractbaseuser
Actually i'm about learning django, im trying to build a rest api for authentication and i choosed to create a custom user model based on AbstractBaseUser. can any one tell me how to proceed? thanks. -
Why won't nginx show static content with django and gunicorn?
I am trying to run the django admin app using gunicorn 19.19.0 and nginx 1.10.3 on a raspberry pi 3 (raspian 9) with python 3.5.3 and django 2.1.7. Nginx seems to be working properly and the nginx and gunicorn error logs are empty. The app will not display any static content however. I checked the nginx.conf file I ran collectstatic and checked that all the files are there. I can point a browser to 192.168.1.20/static and it shows the right directory. I can also browse to all the files I tried following the path in the nginx.conf file with a '/' All functions of the admin app work fine. just no static content I've googled and read/tried every forum fix that i can find. nginx.conf file events{} http { server { listen 80; server_name localhost; location /static { autoindex on; alias /home/pi/DigitalClock/dcvenv/static; } location / { error_log /home/pi/DigitalClock/dcvenv/nginx_err.log; access_log /home/pi/DigitalClock/dcvenv/nginx_acc.log; proxy_pass http://127.0.0.1:8000; } } } gunicorn start command gunicorn dcweb.wsgi:application --bind localhost:8000 django project settings file STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static/') last entries of ngnix_acc.log (*_err.log is empty) 192.168.1.10 - - [18/Feb/2019:12:45:18 -0800] "GET / HTTP/1.1" 200 227 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) … -
Creating a view function that charges the card using the already successfully created token with stripe.js
I'm using stripe elements from the official documentation to create a token. Now I'm trying to build a charge function in my view.py to charge the credit card. But how do I properly get the token from stripe.js in my views.js because "request.POST.get('stripeToken'):" doesn't work in my code. I'm trying to set up a user sign up form in django where the user needs to pay a single fee when he signs up (not saving the token for recurring payments). I'm now trying to build a charge function in my views.py which charges the card with the already successfully created token. The reason why I want to use stripe elements with stripe.js is the good looking form. I am relatively new to this environment and because of that I don't know how to go on. Thanks for your help already in advance! views.py import stripe def charge(request): # Set your secret key: remember to change this to your live secret key in production # See your keys here: https://dashboard.stripe.com/account/apikeys stripe.api_key = "sk_test_..." # Token is created using Checkout or Elements! # Get the payment token ID submitted by the form: if request.POST.get('stripeToken'): print(request.POST) token = request.POST.get('stripeToken') charge = stripe.Charge.create( amount=999, … -
Common start for url in all paths in team
I'm just working on a project in Django 1.11. I have a problem with how to make a common beginning of the url. For example, after creating a team, the address for all members should look like this: domain.com/name_of_team domain.com/name_of_team/blog domain.com/name_of_team/blog/title_of_post Main url file in project: www/urls.py urlpatterns = [ url(r'', include('blog.urls', namespace='blog')), url(r'^accounts/', include('accounts.urls', namespace='accounts')), url(r'^admin/', admin.site.urls), ] Urls in blog: blog/urls.py url(r'^$', login_required(RedirectToHome.as_view()), name='redirect_home'), url(r'^t/(?P<pk>[0-9]+)/$', login_required(BlogHome.as_view()), name='blog_list'), url(r'create/$', login_required(BlogCreate.as_view()), name='blog_create'), url(r'^(?P<pk>[0-9]+)/delete/$', login_required(BlogDelete.as_view()), name='blog_delete'), url(r'^(?P<pk>[0-9]+)/update/$', login_required(BlogUpdate.as_view()), name='blog_update'), url(r'^(?P<pk>\d+)?/?$', login_required(BlogDetail.as_view()), name='blog_detail'), Maybe there are some good practices for dealing with url addresses? -
Django - ERROR: ORA-01017: invalid username/password; logon denied
I am using an Oracle db backend in my django project. I am able to connect to my remote Oracle db using sqlplus from the CMD line and using an Oracle SQL developer. Whenever I try to use python manage.py dbshell it returns the oracle error. SP2-0751: Unable to connect to Oracle. Exiting SQL*Plus Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\dbshell.py", line 22, in handle connection.client.runshell() File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\oracle\client.py", line 12, in runshell subprocess.check_call(args) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 341, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['sqlplus', '-L', 'system/\\"password\\"@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=host)(PORT=8080))(CONNECT_DATA=(SID=temp)))']' returned non-zero exit status 1. Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'temp', 'USER': 'system', 'PASSWORD': 'password', 'HOST': 'host', 'PORT': '8080', } } I modified the DB information for security purposes but the settings.py information should match the stack trace error. Any suggestions as to what I should try or maybe I am forgetting to set something? -
How to store private key for cleardb ssl cert on heroku
I am using ClearDB on Heroku for my python-django app. What is a good way to store my private key file for the SSL connection to ClearDB server? I was hoping I can store the key itself in a config Var on heroku , but then how do i pass the key to the ssl dict in the connection string for mysql (connection string takes path to the key file, not the key itself). I know i can use S3 to store the pem file and pull from there as needed. But was hoping to avoid that if possible. -
Validators do not work as they should. Django
I am trying to add a validator in accordance with the Django documentation to my field but I can not get the effect, every time i can sent e-mail even though there is no "fred@example.com" in the field. Do I have to add any additional lines of code in the view? any help will be appreciated. class EmailContactForm(forms.Form): e_mail = forms.EmailField() tresc_wiadomosci = forms.CharField(widget=forms.Textarea) def clean_recipients(self): data = self.cleaned_data['e_mail'] if "fred@example.com" not in data: raise forms.ValidationError("You have forgotten about Fred!")