Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python NoReverseMatch for Argument
I am new to Python Django and I am struggling with URL patterns,My creating websites which has three Html pages and their three respective views,I am attchaing the images of My code and project structure Please help me to find the solution: Project Structure:- enter image description here So idea is when i click on index.html the page gets redirect to detail.html with image id like 'music/id' now i want to redirect to other html page on image click in detail.html to picturedetail.html with 'song_title' attribute Code:- Models.py:- from django.db import models class Album(models.Model): art_type=models.CharField(max_length=255) album_title=models.CharField(max_length=255) art_method=models.CharField(max_length=255) album_logo=models.FileField() def __str__(self): return self.album_title; class Picture(models.Model): album=models.ForeignKey(Album,on_delete=models.CASCADE) file_type=models.FileField() song_title=models.CharField(max_length=245) detail.html:- {% extends 'music/base.html' %} {% block title %}Album Details{% endblock %} {% block body %} <ul> {% for picture in album.picture_set.all %} <div class="col-sm-4 col-lg-2"> <div class="thumbnail"> <a href="{% url 'music:picturedetail' picture.song_title %}"> <img src="{{ picture.file_type.url }}" class="img-responsive"> </a> <div class="caption"> <h6>{{picture.song_title}}</h6> </div> </div> </div> {% endfor %} </ul> {% endblock %} urls.py:- from django.conf.urls import url from . import views app_name='music'; urlpatterns = [ url(r'^$',views.IndexView.as_view(),name='index'), # /music/id/ url(r'^(?P<pk>[0-9]+)$',views.DetailView.as_view(),name='detail'), #for PictureDetail view url(r'^(?P<pk>[0-9]+)/(?P<song_title>[A-Za-z]+)', views.PicturedetailView.as_view(), name='picturedetail'), ] 4.view.py:- from django.views import generic from .models import Album from .models import Picture class IndexView(generic.ListView): template_name … -
How to pass currently logged in user to filter.py i.e request based Filtering in django
I want to restrict the views for each user i.e a user can view only those account details that are related to him only. For this i have created a Filter where i want to pass the Logged in User details. Below is the snapshot of filter.py class networkFilterUserbased(django_filters.FilterSet): account_choice = NetworkRelatedInformation.objects.values_list('account', 'account__accountName') \ .filter(account__userName='username1').distinct() account = django_filters.ChoiceFilter(choices=account_choice) class Meta: model = NetworkRelatedInformation fields = ['month', 'year', 'account'] And i am using this filter in my views.py def UserSpecificDashBoardView(request, *args, **kwargs): month = request.GET.get('month') year = request.GET.get('year') account = request.GET.get('account') ......All Logic here.... network_list_user = NetworkRelatedInformation.objects.all() network_filter_user = networkFilterUserbased(request.GET, queryset=network_list_user) return render(request, 'personal/dashboardnew.html', {'filter': network_filter_user}) Now the problem is when i am passing hardcoded values like username of the user in above example as uername1 it is working fine, But there are 100s of users so i want to pass the value directly from request. Means when i am passing request.user in place of username it is not working. I tried multiple solutions using request based filtering but nothing works. Pls advise how can i pass the currently logged in user value to the above filter -
Django signals not working for my directory structure
I am trying to implement signals for my app and my directory structure looks like this - src - utility_apps __init__.py - posts - migrations - static - templates admin.py views.py apps.py signals.py __init__.py ...... static manage.py ...... Here posts is my app and the signals.py is inside its folder, But my signals aren't working. I have defined my signal code as - from .models import Post from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=Post) def give_group_owner_permission(sender, instance, created, **kwargs): print("coming to signal") if created: print("created") But it doesn't work. In my apps.py I have changed the ready function as class Post(AppConfig): name = 'post' def ready(self): import utility_apps.posts.signals I have even tried importing posts.signal in the ready function. What I am doing wrong here, please help -
jQuery: delete dynamically created table rows
I want to delete table row that is created dynamically. New table row is created when Add New is clicked. I could delete only the table rows that already loaded. Please help me point out the problem with code. .html <table id="fresh-table" class="table table-striped option-list table-hover table-sm"> <thead class="thead-table-list"> <tr> <th scope="col">Option</th> <th scope="col">Answer</th> <th></th> </tr> </thead> <tboy> <tr> <td><input type="text" class="form-control" value="Animal"></td> <td><input type="text" class="form-control" value="F"></td> <td><i class="material-icons option-delete">delete</i></td> </tr> <tr> <td><input type="text" class="form-control" value="Snake"></td> <td><input type="text" class="form-control" value="T"></td> <td><i class="material-icons option-delete">delete</i></td> </tr> <tr> <td><input type="text" class="form-control" value="Eagle"></td> <td><input type="text" class="form-control" value="F"></td> <td><i class="material-icons option-delete">delete</i></td> </tr> <tr> <td><input type="text" class="form-control" value="Turtle"></td> <td><input type="text" class="form-control" value="F"></td> <td><i class="material-icons option-delete">delete</i></td> </tr> <tr> <td colspan="3"><u id="add_option">Add New</u></td> </tr> </tboy> </table> .js <script type='text/javascript'> //Add option row-- QCM $("#add_option").click(function(){ $('.option-list tr:nth-last-child(2)').after('<tr><td><input type="text" class="form-control" value="Turtle"></td><td><input type="text" class="form-control" value="F"></td><td><i class="material-icons option-delete">delete</i></td></tr>'); }); //Delete option_row onClick $('td i').on('click',function(e){ e.preventDefault(); $(this).parents('tr').remove(); }); </script> Anything wrong with the code? -
How to setup the Apache with Django
I'm trying to setup Django with apache on an AWS EC2 instance. This is 000-default.conf under /etc/apache2/sites-available looks like this <VirtualHost *:80> ServerName mysite ServerAlias mysite.com ServerAdmin mysite@gmail.com DocumentRoot /var/www/mysite WSGIScriptAlias /mysite /var/www/mysite/mysite/wsgi.py ErrorLog /home/ubuntu/apache/errors/error.log CustomLog /home/ubuntu/apache/errors/custom.log combined </VirtualHost> My Django project is under /var/www/ My python location /home/ubuntu/anaconda3/bin/python When I access the site this is what I get. https://i.stack.imgur.com/j47h9.png -
Celery + gunicorn does not display the task
There is a website that, upon user request, starts to parse another site. Because parsing takes quite a long time, plus it works in multithreaded mode, I shifted responsibility for it to celery, which works in tandem with rabibitmq. The problem is that celery correctly executes the task, but then something fails and the result of the task is not displayed to the user. In the gunicorn log there was a timeout error error, but it is already fixed by the timeout parameter. To django I access through ajax-request and return json data from view. p.s. Before gunicorn im using nginx. -
Heroku Deployment brings an Application Error
After deploying my django app through Heroku, I noticed that it was somewhat able to deploy successfully except when going to the actual website it gave me a , "Application Error." I'm not too sure what's going on here. After running heroku logs --tail I receive this: Initial release by user gkatashima@gmail.com Release v2 created by user gkatashima@gmail.com 2018-07-05T23:30:45.368070+00:00 app[api]: Enable Logplex by user gkatashima@gmail.com 2018-07-05T23:30:45.235675+00:00 app[api]: Release v1 created by user gkatashima@gmail.com 2018-07-05T23:32:40.582279+00:00 app[api]: Release v3 created by user gkatashima@gmail.com 2018-07-05T23:32:40.582279+00:00 app[api]: Set SECRET_KEY config vars by user gkatashima@gmail.com 2018-07-05T23:38:37.214305+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/" host=nameless-bayou-56583.herokuapp.com request_id=2f385349-63bf-4e90-aa33-97998d0ad3af fwd="76.103.249.106" dyno= connect= service= status=502 bytes= protocol=https 2018-07-05T23:38:37.530260+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/favicon.ico" host=nameless-bayou-56583.her okuapp.com request_id=d3d472c6-3cd2-42e7-bc50-1139c132ae31 fwd="76.103.249.106" dyno= connect= service= status=502 bytes= protocol=https 2018-07-05T23:40:27.000000+00:00 app[api]: Build started by user gkatashima@gmail.com 2018-07-05T23:40:28.000000+00:00 app[api]: Build failed -- check your build logs 2018-07-05T23:40:28.000000+00:00 app[api]: Build failed -- check your build logs 2018-07-05T23:45:41.000000+00:00 app[api]: Build started by user gkatashima@gmail.com 2018-07-05T23:45:42.000000+00:00 app[api]: Build failed -- check your build logs 2018-07-05T23:45:42.000000+00:00 app[api]: Build failed -- check your build logs 2018-07-05T23:49:08.000000+00:00 app[api]: Build started by user gkatashima@gmail.com 2018-07-05T23:49:30.000000+00:00 app[api]: Build failed -- check your build logs 2018-07-05T23:49:30.000000+00:00 app[api]: Build failed -- check your build logs … -
Is it good to integrate monogodb with django [on hold]
I am beginner level django developer.Is it good to use django with monogodb. In case yes than what is best way to do this?.if not suggest me best framework for web and desktop app development. what about the METEOR ? -
What is the best way to prevent others from sending false HTTP post request bodies?
I am making a SpriteKit game on Xcode and am using Moya to handle networking calls, Heroku to host the database/server, and Django to write the backend code. Right now, game data, such as a player's new high score, is sent to the server thru the post request body in JSON from Moya requests in Xcode. How do I set up a check so that only a legitimate post request from the game app changes the score? -
Django modelformset_factory UnboundLocalError
I am getting error message the UnboundLocalError local variable 'Assumptions' referenced before assignment (after line else:). I wonder how is that even possible given that Assumptions is a model and is imported to the views.py. Any advise how to solve it would be highly appreciated. Also, I am trying to create multiple forms based on Assumptions modelform and save them into the database model Assumptions. Please advise if this code is the correct design pattern. Thank you. views.py from django.shortcuts import render from .forms import modelformset_factory, AssumptionsForm from .models import Assumptions def get_assumptions(request): if request.method == 'POST': if 'name' in request.POST: formset = modelformset_factory(Assumptions, form = AssumptionsForm, extra = 5) if formset.is_valid(): print('valid form') for form in formset: print('Looping forms') Assumptions = form.save(commit='False') Assumptions.Name = 'name' Assumptions.save() else: formset = modelformset_factory(Assumptions, form = AssumptionsForm, extra = 5) return render(request, 'assumptions.html', {'formset': formset}) assumptions.html <div class="form"> <form action="" method="post"> {% csrf_token %} {{ formset.management_form }} {{ formset.non_form_errors.as_ul }} {% for name in ['A', 'B'] %} <h1>var</h1> <table id="formset" class="form"> {% for form in formset.forms %} {% if forloop.first %} <thead><tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr></thead> {% endif %} <tr class="{% cycle 'row1' 'row2' … -
Django Form miss reference for some FileField
I have a form in Django like this: class ProfessionalForm(forms.ModelForm): name = forms.CharField(required=True, label=_("name").title()) email = forms.EmailField(required=True) avatar = forms.FileField(required=False, label=_("avatar").title()) front_document = forms.FileField(required=False, label=_("front document").title()) back_document = forms.FileField(required=False, label=_("back document").title()) class Meta: model = Professional fields = ("name", "email", "avatar", "front_document", "back_document") The problem is: In page, I put one file ('avatar', for exemple) and saved, everything works. So when I enter again in page and set another file ('front_document', for exemple), the controller loss the reference to 'avatar' and set to null this field. What's happen? My views.py def myprofile(request): if request.method == "POST": form = ProfessionalForm(request.POST, request.FILES) if form.is_valid(): professional = form.save(commit=False) professional.user = request.user professional.save() request.session['professional_avatar_url'] = \ professional.avatar.url if professional.avatar else settings.NO_IMAGE else: professional_t = Professional \ .objects \ .get_or_create(user=request.user, defaults={'name': request.user.first_name + " " + request.user.last_name, 'email': request.user.email}) professional = professional_t[0] return redirect('myprofile') else: professional_t = Professional\ .objects\ .get_or_create(user=request.user, defaults={'name':request.user.first_name + " " + request.user.last_name, 'email':request.user.email}) professional = professional_t[0] form = ProfessionalForm( instance=professional) return render(request, 'npadmin/myprofile.html', {'form':form, 'professional':professional}) And my html: <form method="post" action="{% url 'myprofile' %}" class="form-horizontal" role="form" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form-group row"> <label class="col-2 col-form-label">{{ field.label_tag }}</label> <div class="col-10"> {% render_field field class+="form-control" %} … -
Django, Multiple requests at the same time
I have a middleware.py file that records IP address on my website. x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') try: ip_address = IPAddress.objects.get(ip_address=ip,userprofile=up) # Here we can have MultipleObjectsReturned error # that's the issue Django emails me about except IPAddress.DoesNotExist: ip_address = IPAddress(ip_address=ip,userprofile=up) Because of something that goes wrong MultipleObjectsReturned, Django emails me about bug reports. But I see in all the emails many requests come from different URLs, and oddly at the same time 12:20 PM Here are some URLs: my_domain/elastik my_domain/digium my_domain/Avaya my_domain/Zyxel my_domain/cisco.cfg my_domain/SIPGateway ... As normal, these URLs don't exist on my website, they suppose to generate 404 error page, but my doubt is why at the same time? why these weird URLs? Do I need to worry about ? or Does it exist a way to avoid that kind of behavior. I host on DigitalOcean -
how to deal with two model forms (combined in one form in html) in Django
I have tow model forms (combined in one form in html). The following are those two model forms : class PostsForm(forms.ModelForm): class Meta: model = Posts fields = ['post_category', 'post_sub_category', 'post_title', 'post_detail', ] class CarsForm(forms.ModelForm): class Meta: model = Cars fields = ['price','year', 'odometer', 'car_make', 'car_model','car_image' ] the following is the view function: def post_ad(request): form_class = [PostsForm(), CarsForm(), ] template_name = 'path/to/template.html' if request.method == 'POST': form_class[0] = PostsForm(request.POST) form_class[1] = CarsForm(request.POST) if form_class[0].is_valid() and form_class[1].is_valid(): post_form = form_class[0].save(commit=False) car_form = form_class[1].save(commit = False) post_form.user = request.user post_form.save() # function to deal with multiple images def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('car_image') if form.is_valid(): # image section for f in files: instance= Cars(car_image=request.FILES['file']) instance.save() return self.form_valid(form) else: return self.form_invalid(form) car_form.save() return redirect('index') return render(request, template_name, {'form_class':form_class }) in the template I could display both forms in one html form and both of them have one single button. with no errors. However, when I submit the form I got the following error: kages/django/core/validators.py", line 349, in compare return a > b TypeError: '>' not supported between instances of 'int' and 'datetime.datetime' the error came from this line : if form_class[0].is_valid() and form_class[1].is_valid(): can … -
Can't deploy my Django webapp, Gunicorn, Supervisor adn Nginx in DigitalOcean
I followed this tutorial and I made some modifications. I used Ubuntu 16.04, but I worked with Django 2.0.5 and Python 3.5. This is my file structure: user/ |-- bin/ |-- gunicorn_start (executable) + ... |-- myproject/ |-- wsgi.py |... + settings.py |-- include/ |-- lib/ |-- local/ |-- logs/ |-- manage.py |-- pip-selfcheck.json |-- run/ |-- static/ |... |... +-- run/ I have installed Gunicorn, this my gunicorn_start file #!/bin/bash NAME="myproject" DIR=/home/user/myproject USER=user GROUP=user WORKERS=3 BIND=unix:/home/user/run/gunicorn.sock DJANGO_SETTINGS_MODULE=myproject.settings DJANGO_WSGI_MODULE=myproject.wsgi LOG_LEVEL=error cd $DIR source /home/user/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec /home/user/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- I installed Supervisor and this is my /etc/supervisor/conf.d/myproject.conf file: [program:myproject] command=/home/user/bin/gunicorn_start directory=/home/user/myproject user=user autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/user/logs/gunicorn-error.log if I run these commands I've got this error: sudo supervisorctl reread sudo supervisorctl update sudo supervisorctl status myproject myproject FATAL Exited too quickly (process log may have details) but if I run this gunicorn myproject.wsgi:application --bind <my_ip>:8000 I can access my web app perfectly (without the static files) The last step is the NGINX and this is my configuration file /etc/nginx/sites-available/myproject upstream app_server { server unix:/home/user/run/gunicorn.sock fail_timeout=0; } server { listen 80; # add here … -
ModuleNotFoundError: No module named 'heroku'
I have searched a lot regarding uploading my django project on heroku but I'm unable to do that. Please check the following structure and let me know what is wrong and why I'm getting this error: File "/app/djangosample1/settings.py", line 17, in import heroku as heroku ModuleNotFoundError: No module named 'heroku' Structure of my project: https://github.com/cabudies/djangosample2-master/blob/master/structure.png Procfile web: gunicorn djangosample1.wsgi --log-file- wsgi.py import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangosample1.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application) Also, whenever I'm running 'python manage.py runserver' even on local server, I'm getting error: SyntaxError: invalid syntax at heroku\helpers.py -
Django QuerySet is Empty while I added some stuff
Hello I am new in Django, and I decided to do a Blog page. Problem is that my queryset is empty after I create a new aplication. any idea why ? Tried with active and without active. views.py from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView, DetailView from django.http import Http404 from .models import BlogPost class BlogPostListView(ListView): queryset = BlogPost.objects.all().active() template_name = "blog.html" def get_queryset(self, *args, **kwargs): request = self.request return BlogPost.objects.all().active() def BlogPost_list_view(request): queryset = BlogPost.objects.all().active() context = { 'object_blog': queryset } return render(request, "blog.html", context) models.py import random import os from django.db import models from django.db.models.signals import pre_save, post_save from django.urls import reverse def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name, ext def upload_image_path(instance, filename): print(instance) print(filename) new_filename = random.randint(1,18341264712) name, ext = get_filename_ext(filename) final_filename = '{new_filename}{ext}'.format(new_filename= new_filename, ext=ext) return "products/{new_filename}/{final_filename}".format( new_filename= new_filename, final_filename=final_filename ) class BlogPostQuerySet(models.query.QuerySet): def active(self): return self.filter(active=True) def featured(self): return self.filter(featured=True, active=True) class BlogPostManager(models.Manager): def get_queryset(self): return BlogPostQuerySet(self.model, using=self._db) def all(self): return self.get_queryset() class BlogPost(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField() image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) objects = BlogPostManager() def get_absolute_url(self): return "{slug}/".format(slug=self.slug) # return reverse("products:detail", kwargs={"slug": self.slug}) def __str__(self): … -
Regex exclude .html from string
I am stuck with creation of regex matching my needs. Regex should include beginning of the string but not the ending (.html) Example: company.html should convert into company My attempt: url(r'^(?P<page>.+\.html)$', Is there any chance someone could advice me on this one? I need to prepare my django urls to expect over 50 companies names and it seems to be the easiest way to keep my code DRY. -
How to use a specific test database in django
I would like to know if it is possible to execute test in django against a pre-populated database. I'm using an sqlite database and I have a copied of it with some rows populated already. I would like to use this "copy database" for testing. Is it sufficient to configure the setting.py as in How to use a specific database for a single test in django? -
Is there a way to use CLI to POST data on django2 project?
I have a webapp that I created using Django2. At a high level, it will be used to process .tsv files of data and display them nicely on a screen. I want to be able to have a command line interface where I can perform a POST request to the already running webapp, and essentially add data to a model, save it, and create a unique webpage to display that data. Something like: uploadtodjangoapp <myfilename> --user='heidi' --other-options='....' uploading myfilename to myapp! done see data here: www.mysite.com/info/myfilename In this situation ^ the webpage will be running already somewhere (either locally or on a vm). Currently, I know you can create a form on the user interface to perform post requests/get user data. And I know you can also use python manage.py shell and do something like: >> from myapp.model import mymodel >> m = mymodel(data="some data here") >> m.save() .... but is this the only way? Any help would be greatly appreciated! -
Creating a Simple Line Chart with Highcharts
I'm having a bit of difficulty creating a line chart with some JSON time series data I have. My JSON data looks like this: [{'close': 30.1361, 'date': '2017-07-05'}, {'close': 29.7583, 'date': '2017-07-06'}, {'close': 29.9326, 'date': '2017-07-07'}] Additionally I am serving up my web pages via Django/Python, so the JSON data above is store in a variable that looks like this: {{ one_yr|safe }} Currently I have a blank chart with the numbers 0-140 across the y-axis and nothing on the x-axis, with no plot. My code thus far looks like this: <!doctype html> <html> <head> <meta charset="utf-8"> <title>Django Highcharts Example</title> </head> <body> <div id="container"></div> <script src="https://code.highcharts.com/highcharts.src.js"></script> <script> Highcharts.chart('container', { chart: { type: 'line' }, title: { text: 'One Year Stock Price' }, series: [{ name: '{{ stock.ticker }}', data: {{ one_yr|safe }} }] }); </script> </body> </html> I'm hoping to create a very simple line chart with dates on the x-axis and prices on the y-axis. Any help would be much appreciated, thanks. -
Scheduled Celery Task Lost From Redis
I'm using Celery in Django with Redis as the Broker. Tasks are being scheduled for the future using the eta argument in apply_async. After scheduling the task, I can run celery -A MyApp inspect scheduled and I see the task with the proper eta for the future (24 hours in the future). Before the scheduled time, if I restart Redis (with service redis restart) or the server reboots, running celery -A MyApp inspect scheduled again shows "- empty -". All scheduled tasks are lost after Redis restarts. Redis is setup with AOF, so it shouldn't be losing DB state after restarting. -
Add user to permission group when creating user in Django Admin
I would to add a User to a permission group automatically when create a User. I have hear about user.groups.add(group) and group.user_set.add(user). But it doesn't work. My final purpose is to have 3 kind of users: SuperAdmin: One superadmin to manage the site. Administrators: User administrators. Which can manage regular users. Upload photos, add new Users to manage, etc. Regular Users: The normal users which will use the aplicación. They don't have any permission, just login the site, but not the adminSite. MODELS.PY from django.db import models from django.contrib.auth.models import AbstractUser, Group from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class MyUser(AbstractUser): descripcion = models.TextField(blank=True) telefono = models.PositiveSmallIntegerField(default=000) avatar = models.ImageField(upload_to='users/avatar/', blank=True) def __str__(self): return self.username class RegularUser(MyUser): MyUser.is_staff = False MyUser.is_superuser = False class Meta: verbose_name = 'Usuario Regular' verbose_name_plural = 'Usuarios Regulares' class AdminUser(MyUser): usuarios = models.ManyToManyField(RegularUser, help_text="Selecciona los usuarios que administra") MyUser.is_staff = True class Meta: verbose_name = 'Administrador' verbose_name_plural = 'Adminsitradores' ADMIN.PY from django.contrib import admin from django import forms from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.contrib.auth.models import Group from myApp.models import MyUser, RegularUser, AdminUser # Register your models here. class UserCreationForm(forms.ModelForm): """A form for creating … -
Authorizing the BlueJeans API with a Django app
I'm trying to make a Django app automatically send invites to BlueJeans video conferences using its API (https://bluejeans.github.io/api-rest-meetings/site/index.html). However, I'm finding it not so straightforward to set this up, and their customer support staff seem to not all be completely familiar with these features either. When you request to enable API access in BlueJeans, the customer support enables an "OAuth Access" tab with a form which allows you to create an app with a name, description, and 'app key': My question is: what should I fill in for the "app key"? (I've browsed the OAuth 2.0 RFC but so far haven't been able to apply it to solve this). -
How can I change placeholder into ImageField with Django?
I have this Form: class ProfessionalForm(forms.ModelForm): name = forms.CharField(required=True, label=_("name").title()) email = forms.EmailField(required=True) avatar = forms.ImageField(required=False, label=_("avatar").title()) form_title = _("myprofile") form_hint = _("profile_hint") class Meta: model = Professional fields = ("name", "email", "avatar") And when django render response, the input has a button with label : 'Browser' and the hint: 'No file selected'. I need change it to use my translation method. I using Python 3.6 and Django 2.0. -
Custom Radio Buttons with Django forms/Django template
I'm trying to render radio buttons in my Django template with custom label tags for each of the two radio buttons. I'm trying to do this by detecting if the loop is on the first or second radio button and giving the appropriate label for each: Label 1 or Label 2 <section class="section-units"> <fieldset id="filter-units" class="mod-choices radios mod-inline"> <label>Units:</label> {% for radio in form.filter_units %} <div class="form-group"> {{ radio.tag }} {% ifequal form.filter_units.auto_id forloop.counter0 %} <label>Label 1</label> {% endifequal %} {% ifequal form.filter_units.auto_id forloop.counter1 %} <label>Label 2</label> {% endifequal %} </div> {% endfor %} </fieldset> </section> So far what I have above isn't working It should be noted that I have a model form in my forms.py: class InputForm(forms.ModelForm): class Meta: model = myModel fields = [...'filter_units',], widgets = {... 'filter_units': forms.RadioSelect( attrs={'class': 'form-control', 'id' : 'metric'} ),... } So I don't want to use the choices I have for filter_units in my model for my labels