Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
lxml etree replaces <em></em> with <em/>
I have a blog where I save blog posts as a HTML string (basically text of html elements) on a database. Ex: I created a blog post which resulted in following string as my blog post content. <p>asdasd</p><p><em></em><div>another string</div> When a user comes to view the post, I retrieve above content from DB and use lxml etree to do some stuff with content (which has nothing to do with my question) and return the content to browser. from lxml import etree as ET obj = ET.parse(StringIO.StringIO(self.text), parser=ET.HTMLParser()) #self.text holds the html string of blog post return ET.tostring(tree) # return the html string to browser now the problem is the content that is sent to browser as follows <p>asdasd</p><p></em /><div>another string</div> This causes all sort of problem with chrome browser, forinstance, at the users broswer, above html will be displayed as followed (after chrome automatically trying to fix it) <p>asdasd</p><p></em><div>another string</div></em> Is there a way to prevent lxml etree from changing the html content when parsing? it seems like etree does this to all empty html elements. ie if I put a <div></div> then that will be replaced with <div /> -
Django REST Framework ManyToMany Serializer
I've searched through the existing questions/answers, DRF documentation, and tried multiple examples to get where I'm at with this. The issue I have is that the ShowtimeSerializer is not getting populated. This looked the most promising but I couldn't figure it out Also tried to use this as a non DRF way of doing it I parse a few API's to get this JSON which contains film details with showtimes: {u'poster_path': u'/bEAoNvtqvO0c2lItNkKlKUqhPuw.jpg', u'production_countries': [{u'iso_3166_1': u'US', u'name': u'United States of America'}], u'revenue': 0, u'overview': u"After moving to a new town, troublemaking teen Jim Stark is supposed to have a clean slate, although being the new kid in town brings its own problems. While searching for some stability, Stark forms a bond with a disturbed classmate, Plato, and falls for local girl Judy. However, Judy is the girlfriend of neighborhood tough, Buzz. When Buzz violently confronts Jim and challenges him to a drag race, the new kid's real troubles begin.", 'youtube': 'Rwh9c_E3dJk', 'is_3d': False, u'video': False, u'id': 221, 'category': u'C', u'genres': [{u'id': 18, u'name': u'Drama'}], u'title': u'Rebel Without a Cause', u'tagline': u'The bad boy from a good family.', u'vote_count': 124, u'homepage': u'', u'belongs_to_collection': None, u'original_language': u'en', u'status': u'Released', u'spoken_languages': [{u'iso_639_1': u'en', u'name': … -
Django url - No reverse match
Okay, to be clear I've searched and read, followed the official docs, tried multiple solutions from SOF, nothing seems to be working so I have to resort to shamefully asking for help. I'm simply trying to generate urls the proper way. urls.py: app_name = 'main' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^vieworder/(?P<order_id>[0-9]+)/$', views.vieworder, name='vieworder'), ] template file: <td><a href="{% url 'main:vieworder' order.id %}">View</a></td> Error: Reverse for 'vieworder' with arguments '(1,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['|/vieworder/(?P<order_id>d+)/$'] I don't understand why this is not working. I tested the regex against vieworder/1/ in a regex tester and it works fine. Django even tells me in the error that it tried the correct url pattern, however the error really isn't very clear on what is actually wrong. -
Django form - using variable from database
I have the following form which is working perfectly: # coding=utf-8 from django import forms from straightred.models import StraightredTeam from straightred.models import UserSelection class SelectTwoTeams(forms.Form): cantSelectTeams = UserSelection.objects.filter(campaignno=102501349) currentTeams = StraightredTeam.objects.filter(currentteam = 1).exclude(teamid__in=cantSelectTeams.values_list('teamselectionid', flat=True)) team_one = forms.ModelChoiceField(queryset = currentTeams) team_two = forms.ModelChoiceField(queryset = currentTeams) However, as you can see the campaignno is hard written into the query. Ideally I would like to select the maximum campaignno from a mysql table and use that as the campaigno instead of the 102501349 as above. The mysql table and model is as follows: mySQL table: mysql> desc straightred_userselection; +-------------------+----------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------------+----------------------+------+-----+---------+----------------+ | userselectionid | int(11) | NO | PRI | NULL | auto_increment | | campaignno | varchar(36) | NO | | NULL | | | teamselection1or2 | smallint(5) unsigned | NO | | NULL | | | fixtureid | int(11) | YES | MUL | NULL | | | teamselectionid | int(11) | NO | MUL | NULL | | | user_id | int(11) | NO | MUL | NULL | | +-------------------+----------------------+------+-----+---------+----------------+ Django Model: class StraightredSeason(models.Model): seasonid = models.IntegerField(primary_key = True) seasonyear = models.CharField(max_length = 4) seasonname = models.CharField(max_length … -
Styling ModelMultipleChoiceField Django
I'm having trouble styling my django form with a ModelMultipleChoiceField. Heres my form: class SkriptenSelect(forms.Form): skripten = StyledModelMultipleChoiceField( queryset=None, widget=forms.CheckboxSelectMultiple, ) def __init__(self, *args, **kwargs): choices = kwargs.pop('choices') super(SkriptenSelect, self).__init__(*args, **kwargs) self.fields['skripten'].queryset = choices class StyledModelMultipleChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return mark_safe('<ul class="list-inline" style="display: inline;">' \ '<li>{name}</li>' \ '<li>{semester}</li>' \ '<li>professor</li>' \ '</ul>'.format(name=escape(obj.name), semester=escape(obj.prefix)) ) And I used this for html: <form action="." method="post"> <ul class="list-group"> {% for skript in result_form.skripten %} <li class="list-group-item"> {{ skript }} </li> {% endfor %} </ul> {% csrf_token %} <input type="submit" value="Submit Selected" /> This requires me to put my HTML in my forms file, which is not a very mvc way. Also it restricts me heavily in how i can style the list (i.e making table of the model instance fields) Is there anyway to make this smarter? I'd like to access {{ skript.name }}, {{ skript.checkbox }} or something in my {% for skript in result_form.skripten %} loop, but thats sadly not possible... -
Can we serializer_class attribute with APIView(django rest framework)?
As per the DRF documentation, serializer_class attribute should be set when using GenericAPIView. But why does the serializer_class attribute even works with APIView? Here is my API code: class UserView(APIView): serializer_class = SignupSerializer @transaction.atomic def post(self, request): When i browse this API in browser it does show the email and password fields as input but if i don't set this serializer_class attribute, no input fields are shown. Ideally, this serializer_class attribute should not work with APIView. I have searched a lot but there is nothing available related to this. Can anyone please provide explanation to this behavior? Thanks. -
Django: View Tests Passing but Form Not Working in Page?
I have a page with two forms: a SearchForm and a QuickAddForm. Processing two forms on the same page in Django is not easy, and I'm spent the past two or three days trying to get it to work. I have several unittests that I've been using: a test for each form to make sure it's displaying on the page, a test that a submission of a valid search to the searchform returns the correct results, and three tests for the quickadd form testing that 1) a submission of valid fields results in a new Entry saving to the database; 2) that after an entry is saved, the form redirects to the same page; and 3) that the success message is displayed on that page. For example: def test_quick_add_form_saves_entry(self): self.client.post('/editor/', {'quickadd_pre-hw' : 'كلمة'}, follow=True) self.assertEqual(Entry.objects.count(), 1) After a lot of work (and helped greatly by the answers and comments on this page: [Proper way to handle multiple forms on one page in Django). I finally got the form working, so that the submitted entry was successfully saved in the database and was redirecting after post. Yay! Except ... When I open up the page in a browser and try to … -
Django add forms to formset in a view
I'm stuck in a design problem. Imagine an Order model,which may contain several materials in it. In my view I added a add material submit button , which will redirect user to material listing page, user choices one or more materials and adds them to order, this is fundementally will work like django actions with intermediate forms. Redirecting to material listing page, I may have current formset items, or post data in cache. Upon redirectiong user to order view, I have to repopulate cached formset and add items to order. Lets say user had 3 items in order, and I cached its formset/instance ... , and user selected 2 more materials, I have to add these 2 instances to formset and will have 5 forms in my formset. I searched internet and got js solutions form adding forms, I have to do it without js and modify its fields before templating, I may have a standart price for a material and I may add these to newly added items. Thanks. -
How to force application version on AWS Elastic BeansTalk
I'm trying to deploy a new version of my Python/Django application using: eb deploy It unfortunately fails due to unexpected version of the application. The problem is that somehow eb deploy screwed up the version and I don't know how to override it. The application I upload is working fine, only the version number is not correct, hence, Elastic BeansTalk marks it as Degraded. When executing eb deploy, I get this error: "Incorrect application version "app-cca6-160820_155843" (deployment 161). Expected version "app-598b-160820_152351" (deployment 159). " The same says in the health status at AWS Console. So, my question is the following: how can I force Elastic Beanstalk to make the uploaded application version the current one so it doesn't complain? -
Is it possible to use jQuery and Django on the same page?
I'm trying to just a jQuery function to show a table on a Django page. When I test the script on jsfiddle, it works great but it's not working on my Django site. Do I need to import something into Django to make it work? This is what I have thus far: html file: <table class="panel"> <tr> <td colspan=3 class="tblheader"><h1>Statistics</h1></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> </table> <button class="spoiler">Click for Spoilers</button> javascript file: $(document).ready(function() { $('.spoiler').click(function() { $('.panel').slideToggle('slow'); }); }); -
bypass validation for form field django
class PostForm(forms.ModelForm): description = forms.CharField(widget=PagedownWidget(show_preview=False)) class Meta: model = Post fields = [ 'title', 'image', 'video', 'description', 'public', 'tags', ] I am trying to bypass the required field for 'video' but having difficulty doing so. Any suggestions would be appreciated. -
about django channels WebSocket DISCONNECT
I use channels bulid a websocket sever on LAN, when android client connet,django print this error: totalconnect=125 [2016/08/28 03:02:18] WebSocket CONNECT /android/AB-0078 [10.11.5.41:51494] [2016/08/28 03:02:18] WebSocket CONNECT /android/AB-0002 [10.11.1.23:43642] 2016-08-28 03:02:18,652 - WARNING - ws_protocol - WebSocket force closed for websocket.send!BCaXvpkY due to connect backpressure 2016-08-28 03:02:18,654 - WARNING - ws_protocol - WebSocket force closed for websocket.send!AaJxPMOc due to connect backpressure totalconnect=126 totalconnect=127 [2016/08/28 03:02:18] WebSocket DISCONNECT /android/AB-0048 [10.11.4.35:48175] [2016/08/28 03:02:18] WebSocket DISCONNECT /android/AB-0017 [10.11.1.16:53972] i don't know how to fix this!! this is my code: totalconnect=0; @channel_session def ws_connect(message): global totalconnect try: prefix, mid = message['path'].decode('ascii').strip('/').split('/') totalconnect=totalconnect+1 print('totalconnect=' + str(totalconnect)) except ValueError: return @channel_session def ws_message(message): try: data = json.loads(message['text']) except ValueError: pass return @channel_session def ws_disconnect(message): return -
Django Project Setup on Google VM
I am trying to setup a django project on a VM by Google Compute Engine. I have done all the installations & have copied the project on my VM. But I am not able to do the Apache/mod_wsgi Or Gunicorn/Nginx linking to make the project run end to end on the final IP address of VM. I have two queries: 1) Which one is better Apache/mod_wsgi OR Gunicorn/Nginx OR any other ? 2) Can someone please explain in simple step by step way to do this linking? Any one way Or some good Reference Link would also be appreciated ? Thanks, -
Django and Celery, task running very slow all of a sudden
Normally one task would finish under 0.05 seconds, but now they take 15/30/45 seconds to finish. Yes, they are all multiples of 15. Sometimes it would restore normal speed, but it only lasts for a few minutes before it become slow again. Theses tasks are finished successfully although slow, no network or database errors. The system had been running for several month without a problem, I have no clue why this is happening all of a sudden. I'm running a Django app, redis as broker. What might caused this problem? -
Django oauth2 token request fails on Swift Alamofire
I am building both an iOS client and a django backend service. The connection made between the systems is OAUTH2, implemented by the django-oauth2-toolkit. Although the following command done in curl works (returns an access token): curl -X POST -d "grant_type=password&username=<user>&password=<password>" http://<clientID>:<clientSecret>@localhost:8000/o/token/ The following Swift snippet, that uses Alamofire, receives "invalid_client", as a response. let request = "http://\(Authentication.clientId):\(Authentication.clientSecret)@localhost:8000/o/token/" var URLRequest = NSMutableURLRequest(URL: NSURL(string: request)!) URLRequest.HTTPMethod = "POST" let parameters = ["grant_type": "password", "username": in_username.text!, "password": in_password.text!] let encoding = Alamofire.ParameterEncoding.URL (URLRequest, _) = encoding.encode(URLRequest, parameters: parameters) URLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") Alamofire.request(URLRequest) .responseJSON { response in let data = response print(data) } I then traced the InvalidClientError in the django-oauth2-toolkit source, and found that the exception was raised in the highlighted snippet of the following file: oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.py if self.request_validator.client_authentication_required(request): log.debug('Authenticating client, %r.', request) print(request) # I included this print message to inspect the request variable in console. if not self.request_validator.authenticate_client(request): log.debug('Client authentication failed, %r.', request) raise errors.InvalidClientError(request=request) # RAISED! I included the print(request) line to inspect the differences between the request made by curl and by Alamofire. The major difference was that the curl version included an authorization key: 'Authorization': 'Basic Z3ZFSjVXejloUGgybUJmdDNRaGhXZnlhNHpETG5KY3V6djJldWMwcjpSbVNPMkpwRFQ4bHp1UVFDYXN3T3dvVFkzRTBia01YWWxHVHNMcG5JUGZCUHFjbHJSZE5EOXQzd3RCS2xwR09MNWs1bEE4S2hmRUkydEhvWmx3ZVRKZkFXUDM4OERZa1NTZ0RvS0p3WjUyejRSQ29WRkZBS01RS1lydEpsTWNXag==' and the Alamofire request didn't. I highly suspect this is … -
Celery connect to remote server broker_url
I'm daemonizing celery following the docs. My BROKER_URL has been set in the following format:- 'amqp://<user>:<password>@<ip>/<vhost>'. So, when I start celery manually, celery worker -A app_name, it connects with the remote server. But when I daemonize it, it connects with the localhost amqp. Any reason why? Here is how I create my celery object:- app = Celery('c26_search') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.update( CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend' ) print app.conf.BROKER_URL # prints remote url My settings.py file:- CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' BROKER_URL = `'amqp://<user>:<password>@<ip>/<vhost>'` Why is it acting so weirdly? Even it prints the remote IP url, but still tries to connects with the local amqp? -
Graphical map objects representation website
Sorry this question is too broad, but I need any advice, because I'm facing a task bit above my experience level. The map should be displayed with database objects like restaurants/events/etc. The suggested platform is Python/Django (which is fine both for me and customer) for both frontend and backend. As a map itself I want to use Leaflet because its (presumably) flexible and free. In the first phase there should be just one toolbar with checkboxes, allowing to choose object types to be shown on the map and time range to choose objects. My draft is the following: Leaflet (js based) as map use database for map objects with default Django admin first and add functionality when needed; use HTML and Django widgets for toolbar, checkboxes and all other stuff; The only concern is about the frontend/widgets. Is it all likely to work this way? Maybe its definetly better to switch to JS frontend for this type of application (as future planning)? -
Where do prints go with Django on Elastic Beanstalk
I am running a Django app on Elastic Beanstalk. If I put a print statement in e.g. admin.py, how can I see the result? -
Django-admin page is missing select all checkbox on deploy
I've deployed my Django project on DigitalOcean.com. I've set static folder and run python manage.py collectstatic which worked correctly. The only problem is that I can't see select all checkbox in admin page. This is in my local Django project: And this is in deployed project: I can't figure out where the problem is. Do you know? I'm attaching settings.py of deployed project: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'some key' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main_app', 'django.contrib.admin', 'django_tables2', 'import_export', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'drevo.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'drevo.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME':'/home/django/drevo/db.sqlite3', #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS … -
Django all-auth Form errors not displaying
I am using django-allauth and whenever I input a wrong password in login form,the page just reloads and doesn't show any error.This is my html code: <form class="login" method="POST" action="{% url 'account_login' %}"> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-error"> <span><b> {{error}} </b><span> </div> {% endfor %} {% endfor %} {% endif %} {% csrf_token %} <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label"> {{ form.login }} <label class="mdl-textfield__label" for="id_login">Username/Email:</label> </div> <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label"> {{ form.password }} <label class="mdl-textfield__label" for="id_password">Password</label> </div> <label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="id_remember"> {{form.remember}}<span class='mdl-checkbox__label 'align='left'>Remember me</span> </label></br> {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <a class="button secondaryAction" href="{% url 'account_reset_password' %}">{% trans "Forgot Password?" %}</a><br/></br> <button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--raised mdl-button--colored" type="submit">{% trans "Sign In" %}</button> <br/> <br/> </form> The form displays properly normally and submits normally,if the info input are correct.For sign-up form,the error messages show but it gives a weird one like '%(model_name)s with this %(field_label)s already exists.' if i try to input an email that already exists but for username it gives a normal A user with that username already exists. This is the signup.html … -
Heroku Django Deployment error : "port" option should be >= 0 and < 65536: null
I created a Django app an have created the Procfile and requirements.txt. However when I run the command heroku create I get the following error : ▸ "port" option should be >= 0 and < 65536: null How to fix it? -
hoe to resolve Nginx proxy_pass 502 Bad Gateway error
I have trying to add proxy_set_header in my nginx.conf file. When I try to add proxy_pass and invoke the URL it throws 502 Bad Gateway nginx/1.11.1 error. Not sure how to resolve this error. Can anyone help me ? upstream app-server { # connect to this socket server unix:///tmp/alpasso-wsgi.sock; # for a file socket } server { server_name ; listen 80 default_server; # Redirect http to https rewrite ^(.*) https://$host$1 permanent; } server { server_name ; listen 443 ssl default_server; recursive_error_pages on; location /azure{ proxy_pass http://app-server; } ssl on; ssl_certificate /etc/nginx/server.crt; ssl_certificate_key /etc/nginx/server.key; ssl_client_certificate /etc/nginx/server.crt; ssl_verify_client optional; } -
NoReverseMatch at /polls/upload/ Reverse for 'imageupload' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I am tried to upload image. Upto select photo it worked fine but when I clicked upload it gave following errors: Django Version: 1.10 Python Version: 3.5.1 Installed Applications: ['polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "D:\virtualEnv\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\virtualEnv\mysite\polls\views.py" in home 103. return HttpResponseRedirect(reverse('imageupload')) File "D:\virtualEnv\lib\site-packages\django\urls\base.py" in reverse 91. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "D:\virtualEnv\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix 389. (lookup_view_s, args, kwargs, len(patterns), patterns) Exception Type: NoReverseMatch at /polls/upload/ Exception Value: Reverse for 'imageupload' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I tried following model: class Upload(models.Model): pic = models.ImageField("Image", upload_to="images/") upload_date=models.DateTimeField(auto_now_add =True) views.py from django.shortcuts import render from uploader.models import UploadForm,Upload from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse # Create your views here. def home(request): if request.method=="POST": img = UploadForm(request.POST, request.FILES) if img.is_valid(): img.save() return HttpResponseRedirect(reverse('imageupload')) else: img=UploadForm() images=Upload.objects.all() return render(request,'home.html',{'form':img,'images':images}) Template: <div style="padding:40px;margin:40px;border:1px solid #ccc"> <h1>picture</h1> <form action="#" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <input type="submit" value="Upload" /> </form> {% for img in images %} … -
Django with HTML Forms
I know how to set up Django forms to have Django render them. Unfortunately styling forms then becomes a little less straight forward. I am interested in finding a way to have the HTML form pass its entered values to Django. The HTML form is completely programmed in HTML and CSS. Just for context, please find below a list of solutions I dismissed for several reasons: Set up custom template filter (CSS styling in Django forms) Use a for loop in order to loop through each form and render each field in turn (How to style a django form - bootstrap) Reference the form fields directly y using list items http://stackoverflow.com/posts/5930179/revisions My problem with the first two solutions is that my s inside my form rely on class attributes which sees them assigned into a left or right column (col_half and col_half col_last). The third doesn't quite work for me since my form is not using list items. If I happen to convert my form into list items, a strange border is added into the form field (see screenshot below). As such I am wondering whether there is a way to just keep my HTML template and assign its valued … -
Django rest auth register same user with different usernames but same password
I am using Django-rest-auth in my Django backend for authentication. I log in users with username and password. I register them with username, password and email. I have two frontend angularjs applications which use same backend and both have few users in common, however both applications need different usernames so that I can differentiate between them. I have a Registration check on my frontend side as: for one application usernames like yg_nitish are allowed and for other like ygnitish are allowed. Now the problem is: for common users i.e. say for nitish I can not register him as ygnitish in one app and yg_nitish in another because he has same email. Backend gives me error saying this user is already registered with this email. How can I tackle this?