Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django inline formset inside a modal - delete field
I am creating an edit view inside a modal. My view consists of a regular django form and inline formset. I have used django-dynamic-formsets for adding and deleting new formsets and this is where I have a problem. When formset is displayed inside a modal, the "remove" field is blank and I cannot delete a formset. For a quick example I'm using Daniel Chen's "Django Inline formsets example: mybook". my html: <button id="myBtn">Open Modal</button> <div id="myModal" class="modal"> <div class="modal-content"> <span class="close">&times;</span> <div class="col-md-4"> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <table class="table"> {{ familymembers.management_form }} <thead> <th>One</th> <th>Two</th> <th>Three</th> <th></th> <th><i class="glyphicon glyphicon-remove"></i></th> </thead> <tbody> {% for form in familymembers.forms %} <tr class="{% cycle row1 row2 %} formset_row"> {% for field in form.visible_fields %} <td> {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </tbody> </table> <input type="submit" value="Save"/> <a href="{% url 'profile-list' %}">back to the list</a> </form> </div> </div> </div> my js: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="{% static 'formset/jquery.formset.js' %}"></script> <script> $('.formset_row').formset({ addText: 'add formset', prefix: 'familymember_set' }); var modal = document.getElementById('myModal'); var btn = … -
how to add non-ascii characters into filename?
I have problem when I trying to download pdf file, which contain Russian words into filename. I am used pdfkit tool. def get_pdf_document(request, code): host = request.scheme + "://" + request.META["HTTP_HOST"] uri = reverse('documents:view_signed_document', kwargs={'code': code}) + "?is_pdf=true" obj = get_object_or_404(DownloadCode, code=code) options = { 'page-size': 'A4', 'encoding': "UTF-8", 'no-outline': None, 'margin-bottom': '17', 'margin-left': '10', 'margin-right': '10', 'margin-top': '10', 'footer-html': host + reverse('api:pdf-footer', kwargs={'code': code}), } if obj.doc_type == ACTS_TYPE or obj.doc_type == LISTS_TYPE: options['orientation'] = 'Landscape' result = pdfkit.from_url(host + uri, False, options=options) response = HttpResponse(result, content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename=\"{}-{}.pdf\"'.format(GET_DOC_TYPE[obj.doc_type], code) response['Content-Length'] = response.tell() return response and i have those constant variables: PDF_INVOICE = u"СЧЕТ-ФАКТУРА" PDF_ACT = u"АКТ" PDF_LIST = u"НАКЛАДНАЯ" PDF_PAYMENT = u"СЧЕТ НА ОПЛАТУ" PDF_RECON = u"АКТ СВЕРКИ" PDF_COMMON = u"НЕФОРМАЛИЗОВАННЫЙ" GET_DOC_TYPE = { INVOICE_TYPE: PDF_INVOICE, ACTS_TYPE: PDF_ACT, LISTS_TYPE: PDF_LIST, PAYMENTS_TYPE: PDF_PAYMENT, RECONS_TYPE: PDF_RECON, COMMONS_TYPE: PDF_COMMON, } and my error message: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) and I don't know to how to resolve this problem. pls help -
TemplateSyntaxError at /accounts/profile/
I got an error,TemplateSyntaxError at /accounts/profile/ must be the first tag in the template. I wrote base.html {% load staticfiles %} <html lang="ja"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% load staticfiles 'bootflat/css/bootflat.min.css' %}"> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> </head> <body> <nav class="navbar navbar-default" role="navigation"> <div class="navbar-header"> <p class="navbar-text">HELLO</p> {% if user.is_authenticated %} <p class="navbar-text">{{ user.get_username }}</p> {% endif %} </div> </nav> <div class="container"> {% block content %} {% endblock %} </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> </body> </html> profile.html is {% load staticfiles %} {% extends "registration/accounts/base.html" %} {% block content %} <html lang="ja"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static 'bootflat/css/bootflat.min.css' %}"> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> </head> <body> <a href="{% url 'kenshinresults'%}">SEE YOUR PHOTO</a> <div class="container"> <form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <p>SEND PHOTO</p> <input type="file" name="files[]" multiple> <input type="hidden" value="{{ p_id }}" name="p_id"> <input type="submit" value="Upload"> </form> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </body> </html> {% endblock %} I found only base.html was showed accurately, but when I tried base.html inherit profile.html,this error happens.Before,these 2 files are loaded accurately, but when I added href="{% static … -
How do I return this JSON in django without it being escaped?
In my Django project, I am trying to return a JsonResponse but the data being returned is being escaped 'somewhere'. When I run the code through Jupyter Notebook I don't have a problem. My DataFrame structure is: My Django response reads in my DataFrame pickle and processes it like this: def API_FTEs_month(request, storeCode): df1=pd.read_pickle(storeCode+'.pickle') result=(df1.groupby(['Date','Job Role'], as_index=False) .apply(lambda i: i[['Department', 'Team', 'Days']].to_dict('r')) .reset_index() .rename(columns={0: 'Assignments'}) .to_json(orient='records')) return JsonResponse(result, safe=False) I'm not sure why, but the response gets escaped like this: "[{\"Date\":\"2017-12-31\",\"Job Role\":\"Junior\",\"Assignments\":[{\"Department\":\"Electronics\",\"Team\":\"A\",\"Days\":12.8311126233},{\"Department\":\"Electronics\",\"Team\":\"B\",\"Days\":9.7797036952},{\"Department\":\"Electronics\",\"Team\":\"C\",\"Days\":12.4532628859},{\"Department\":\"Household\",\"Team\":\"A\",\"Days\":13.2005991473},{\"Department\":\"Household\",\"Team\":\"B\",\"Days\":11.2217690247},{\"Department\":\"Household\",\"Team\":\"C\",\"Days\":9.9799650502}]},{\"Date\":\"2017-12-31\",\"Job Role\":\"Senior\",\"Assignments\":[{\"Department\":\"Electronics\",\"Team\":\"A\",\"Days\":12.3088204188},{\"Department\":\"Electronics\",\"Team\":\"B\",\"Days\":11.6027520428},{\"Department\":\"Electronics\",\"Team\":\"C\",\"Days\":8.4242249342},{\"Department\":\"Household\",\"Team\":\"A\",\"Days\":10.2680664459},{\"Department\":\"Household\",\"Team\":\"B\",\"Days\":10.7355819544},{\"Department\":\"Household\",\"Team\":\"C\",\"Days\":14.4751405746}]},{\"Date\":\"2018-01-31\",\"Job Role\":\"Junior\",\"Assignments\":[{\"Department\":\"Electronics\",\"Team\":\"A\",\"Days\":9.8390990646},{\"Department\":\"Electronics\",\"Team\":\"B\",\"Days\":7.8840336082},{\"Department\":\"Electronics\",\"Team\":\"C\",\"Days\":7.4098884623},{\"Department\":\"Household\",\"Team\":\"A\",\"Days\":6.5804561812},{\"Department\":\"Household\",\"Team\":\"B\",\"Days\":7.9109739164},{\"Department\":\"Household\",\"Team\":\"C\",\"Days\":7.6766255979}]},{\"Date\":\"2018-01-31\",\"Job Role\":\"Senior\",\"Assignments\":[{\"Department\":\"Electronics\",\"Team\":\"A\",\"Days\":5.9779944185},{\"Department\":\"Electronics\",\"Team\":\"B\",\"Days\":7.8300778676},{\"Department\":\"Electronics\",\"Team\":\"C\",\"Days\":7.9050436379},{\"Department\":\"Household\",\"Team\":\"A\",\"Days\":6.9225874658},{\"Department\":\"Household\",\"Team\":\"B\",\"Days\":7.6001780124},{\"Department\":\"Household\",\"Team\":\"C\",\"Days\":6.5897367619}]}]" Recreating the attempt in Jupyter Notebook I seem to get valid JSON: Notebook: I was assuming it's something in my to_json() or JsonResponse that is the problem but I have tried inserting other JSON attempts into my JsonResponse such as the following which gives me valid JSON (but not the required structure) without escaping: def nested_dict(): return collections.defaultdict(nested_dict) result=nested_dict() for row in df4.itertuples(): result[row.Index[0]][row.Index[1]][row[1]][row[2]]['sales'] = row.Days json.dumps(result) -
Django: Login inside another login
I'm currently building a site in django. The company that I work for sells "channels" with a preloaded catalogue of products, and a set of users that can use the channel. Those users are provided by the client. In order for our clients to use that channel. They must be asked to provide a set of credentials to log into their channel. For example: www.mysite.com/channel/clienta if client A wants to log into the channel for their user to use it a log in page must appear. Once inside the channel the client's users can use the channel to search for products and view them. If one of the users associate to the channel wants to perform a task or action on any product in the catalogue. That user must log into the channel for that. Hence the login inside another login. My question is how can I do that. The only thing I can think of is giving a user to log into the channel and when a user associated to the channel wants to perform an action logout the user from the channel and log the other user. Any help would be much appreciated. Thanks. -
Can't import Serializer class between two files
File1 and File2 contain Serializer classes for different models I get a import error if File1 imports a Serializer class from File2 and File2 imports a Serializer class from File1 , it only seems to work if only one of the files imports Serializer classes from the other (only can import one way). Is this to prevent circular imports like in django models?, and is there a way to get around this. error: ...\project\src\app\api\serializers.py" ImportError: cannot import name 'SerializerClass' -
Django admin Model name "s"
class Customer(BaseModel): Name = models.CharField(max_length=250, verbose_name="İsim") Surname = models.CharField(max_length=250, verbose_name="Soyisim") Email = models.EmailField(max_length=70, blank=True, null=True, unique=True,verbose_name="E-Mail") Adress = models.CharField(max_length=600, verbose_name="Adres") FaxNumber = models.CharField(max_length=600, verbose_name="Fax Numarası") class meta: verbose_name = "Customer" i have a model as you can but this model name seems with "s" character in django admin panel picture -
django - MySQL strict mode with database url in settings
I'm using a database URL string in my settings like: DATABASES = { 'default': "mysql://root:@localhost:3306/mydb" } When I migrate I get this warning: MySQL Strict Mode is not set for database connection 'default' Now my question: How can I combine the two things? I cannot use the "regular" way to set the database settings with a dictionary because my database url comes from an environment variable. Thx in advance! -
dateutil parse does not correctly parse timezone
Given the following code. See how on line 73, the tzinfo is UTC while on line 74 the tzinfo is tzlocal(). How can I parse a isoformat string and have the timezone be correct? In [72]: import dateutil.parser In [73]: timezone.now() Out[73]: datetime.datetime(2017, 9, 27, 6, 29, 31, 452211, tzinfo=<UTC>) In [74]: dateutil.parser.parse(timezone.now().isoformat()) Out[74]: datetime.datetime(2017, 9, 27, 6, 29, 56, 64495, tzinfo=tzlocal()) -
foreign key in testing django with factory boy doesn't work
I have a problem with foreign key in library factory boy. My test doesn't execute I thinking that the problem in foreign key. I try to test user model which is in user.models that is how my code look like class Task(models.Model): title = models.CharField(max_length=255, verbose_name='Заголовок') description = models.CharField(max_length=255, verbose_name='Описание') cost = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='Цена') assignee = models.ForeignKey('users.User', related_name='assignee', null=True, verbose_name='Исполнитель') created_by = models.ForeignKey('users.User', related_name='created_by', verbose_name='Кем был создан') def __str__(self): return self.title I test it with factory boy that is how my factory boy class looks like class UserFactoryCustomer(factory.Factory): class Meta: model = User first_name = 'Ahmed' last_name = 'Asadov' username = factory.LazyAttribute(lambda o: slugify(o.first_name + '.' + o.last_name)) email = factory.LazyAttribute(lambda a: '{0}.{1}@example.com'.format(a.first_name, a.last_name).lower()) user_type = 1 balance = 10000.00 class UserFactoryExecutor(factory.Factory): class Meta: model = User first_name = 'Uluk' last_name = 'Djunusov' username = factory.LazyAttribute(lambda o: slugify(o.first_name + '.' + o.last_name)) email = factory.LazyAttribute(lambda a: '{0}.{1}@example.com'.format(a.first_name, a.last_name).lower()) user_type = 2 balance = 5000.00 class TaskFactory(factory.Factory): class Meta: model = Task title = factory.Sequence(lambda n: 'Title {}'.format(n)) description = factory.Sequence(lambda d: 'Description {}'.format(d)) cost = 5000.00 assignee = factory.SubFactory(UserFactoryExecutor) created_by = factory.SubFactory(UserFactoryCustomer) That is the example of my test class ApiModelTestCase(TestCase): def test_creating_models_instance(self): executor = factories.UserFactoryExecutor() customer = … -
azure app service django deploy keep failing
it's been 1 month and I still can't figure out what's wrong with me or app service in azure I used python 2.7 and django 1.11.3, with this requirements.txt beautifulsoup4==4.6.0 certifi==2017.7.27.1 chardet==3.0.4 Django==1.11.5 idna==2.6 olefile==0.44 Pillow==4.2.1 pytz==2017.2 requests==2.18.4 urllib3==1.22 when I deploy with Local Git Repository to Azure Web Service(Python2.7, Windows) it doesn't seems to install the requirements I tried wheel but it doesn't do anything, and via scm powershell I failed to do install any of the requirements, example: Python -m pip install django give me no permission error -
How to retrieve transaction details from paypal using django-paypal standard ipn?
How can i retrieve all of the transaction details from the standard paypal ipn and save it to the database migrated which is the paypal_ipn im using django and i have installed django-paypal and i just followed the tutorial here http://django-paypal.readthedocs.io/en/stable/standard/ipn.html#. I'm a little bit confused what does the signals do in my system? does the signals can save transaction details when the payment is completed? -
Updating an HTML fragment with ajax response Django using CBV(ListView)
So I have a homepage that consists of a base listview which includes all of the objects from my db(as shown in the cbv .all() query). What I wanted to do is include a search filter, hence I thought it would be a good idea to isolate it into a separate "list.html" fragment in order to make it reusable later on. Currently, I have an ajax call that sends information to the cbv and the return is a render to list.html fragment. However, when I visit the homepage, the page doesn't get rendered to begin with. Help or advice would be very much appreciated, thank you again. urls.py urlpatterns = [ url(r'^$', exp_view.DrugListView.as_view() , name = 'drug_list')] here is my CBV template: views.py class DrugListView(ListView): context_object_name = 'drugs' model = Drug template_name = 'expirations/drug_list.html' def get(self, request): if self.request.is_ajax(): text_to_search = self.request.GET.get('searchText') print(text_to_search) return render(request, "expirations/list.html", {'drug':Drug.objects.filter(name__contains = text_to_search).order_by('name')}) else: return render(request, "expirations/list.html", {'drug':Drug.objects.all().order_by('name')}) here is drug_list.html {% extends 'expirations/index.html' %} {% block content %} {% include 'expirations/list.html' %} {% endblock %} {% block javascript %} <script> $(document).ready(function(){ var input = $("#searchText") input.keyup(function() { $.ajax({ type: "GET", url: "{% url 'drug_list' %}", data: {'searchText' : input.val()}, success: function(data){ $("#list_view").load("expirations/list.html") } … -
How to retriev the specific filed name from a list of data?
"education": [ { "school": { "id": "133332226690099", "name": "Govt. High School" }, "type": "High School", "id": "184985051845318" } ], using mongo db and json. i need retriv the data from a large list -
How to call external python script in django from a dropdown button on click event in the html
I need to run the jenkins job from frontend through python. So have made a header html which have dropdown button.From many posts i came to know that I can do that through AJAX.can someone please tell me how to do that with example snippets of view.py and how to redirect it to HTML when firing the on click event. I am very new to Django,so please bare if I am doing wrong. home.html <div class="row"> <div class="col-sm-2"> <br> <br> <!-- Great, til you resize. --> <!--<div class="well bs-sidebar affix" id="sidebar" style="background-color:#fff">--> <div class="well bs-sidebar" id="sidebar" style="background-color:#fff"> <ul class="nav nav-pills nav-stacked"> <h4>Application B <span class="badge badge-secondary"></span></h4> </ul> </div> <!--well bs-sidebar affix--> </div> <!--col-sm-2--> <div class="col-sm-10"> <h3>ACTIONS ALLOWED</h3><br> <div> <div class="dropdown"> <button class="btn btn-success btn-md" type="button" onclick="" data-toggle="dropdown">List of scripts available <span class="caret"></span></button> <ul class="dropdown-menu"> <li><a href="#">Healthcheck</a></li> <li><a href="#">Regresseion Testing</a></li> <li><a href="#">Functional Testin</a></li> <li><a href="#">Unit Testing</a></li> <li class="divider"></li> </ul> <button class="btn btn-warning btn-md">Cick to see the results</button><br> </div> </div> </div> </div> <script> $(document).ready(function(){ $('.btn-success').tooltip({title: "Execute", animation: true}); $('.btn-warning').tooltip({title: "Results!@", animation: false}); }); </script> </div> from django.shortcuts import render,redirect from django.http import HttpResponse,HttpResponseRedirect import datetime from jenkin_test import jobrun from django.core.urlresolvers import reverse def index(request): today=datetime.datetime.now().date() print jobrun() return render(request,'webapp/home.html',{"today":today}) urls.py from … -
Accessing database Model from HTML Template in DJango
In the below code Instead of {{ i.user }} I want to access a value from another table with {{ i.user }} as matching value. How to done it within HTML {% for i in obj reversed %} <div class="container"> <blockquote> <header> {{ i.topic }} {{ i.user }} </header> <p> {{ i.desc }} </p> <footer> {{ i.time }} </footer> </blockquote> {% endfor %} </div> Here are My Models from django.db import models class Accounts(models.Model): name=models.CharField(max_length=30) phone=models.CharField(max_length=20,unique=True) mail=models.EmailField() password=models.CharField(max_length=20) def __str__(self): return self.name class BlogPost(models.Model): user=models.CharField(max_length=30) topic=models.CharField(max_length=100) desc=models.CharField(max_length=1000) likes=models.IntegerField(null=True,default=0) time=models.DateTimeField(null=True) def __str__(self): return self.user And I want to get value from Accounts using Blogspot.user i.e {{ i.user }} in template Thanks in Advance... -
Using existing table for AUTH_USER_MODEL is it possible for a Django model field name to refer to database field name that is different
As the title suggests, I am playing with using an existing table for the AUTH_USER_MODEL using AbstractUser. Have to --fake the migration. Any additional columns I have to add to the DB manually and then to the model as some errors come up. Not ideal. Anyway, when I got to ./manage.py createsuperuser I get errors related to fields not existing that it requires: is_superuser, is_staff, etc. The thing is there are fields in the table for this already, just have a slightly different name. I could just change the name. But it got me wondering if there is something built in to Django to cast an ORM field name to a table field name. Something like: class Meta: db_table = 'Users' Where Django assumes the name, unless it is otherwise specified. My quick glimpse through the documentation didn't immediately yield anything. https://docs.djangoproject.com/en/1.11/ref/models/options/ from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. # Extend the User model class User(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=255, blank=False, null=False, unique=True) first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) phone = models.CharField(max_length=255, blank=True, null=True) password = models.CharField(max_length=255, blank=True, null=True) cono = models.IntegerField(blank=False, null=False) … -
Update bokeh graph that is rendered through Django via bokeh widgets
Currently, I have created a plot in Django using data from the database lets say name of the plot is p1. It is being rendered to a html file lets say abc.html Now I have added a widget to the plot and now it is being rendered as script , (div1 , div2) = components((p1 , options)) 'options' is the name of widget. Now the problem is how can I access the change value of the widget and update the plot accordingly from my view.py of Django? -
I wanna set type's number to id of select tag
I wanna set type's number to id of select tag. My ideal html in browser is <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> <option value="0">---</option> <option value="1">a</option> <option value="2">b</option> </select> <select name="type" id="type1"> <option value="1">a1</option> <option value="2">a2</option> </select> <select name="type" id="type2"> <option value="5">b1</option> <option value="6">b2</option> </select> Now actual html in browse is <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> <option>---</option> <option>a</option> <option>b</option> </select> <select name="type" id="type"> <option value="0">---</option> <option value="1">a1</option> <option value="2">a2</option> </select> <select name="type" id="type"> <option value="5">---</option> <option value="6">b1</option> <option value="7">b2</option> </select> id="type" of does not have each number but I do not know how to add these number by using Django's template. I wrote in index.html <form method="post" action=""> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option>{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id=type> {% for counter, value in values %} <option value="{{ counter }}">{{ value }}</option> {% endfor %} </select> {% endfor %} </form> What should I write it?How can I fix this? -
getting multi-tiered JS object into Python via Django
I am building a Django app. I need to build a JS object that is pretty simple, looks like this: data = {0: {t1: v("#t1"), p1: v("#p1")}, 1: {t2: v("#t2"), p2: v("#p2")}, 2: {t3: v("#t3"), p3: v("#p3")}, 3: {t4: v("#t4"), p4: v("#p4")}, 4: {t5: v("#t5"), p5: v("#p5")}, 5: {t6: v("#t6"), p6: v("#p6")}, 6: {t7: v("#t6"), p7: v("#p6")}, 7: {t8: v("#t8"), p8: v("#p8")}, numTickers: 8 }; FYI, v() is just a function that would be a macro in other languages...all it does is reduce typing to get values from tags. It works, so that is not the issue: on the console, I have the right JS object with proper key/value pairs nested right. Before AJAX I do a: var xmitData = JSON.stringify(data); Since that gets me closest. My AJAX call looks (right now) like this: $.ajax({ type : 'POST', headers: {'X-CSRFToken': '{{ csrf_token }}'}, data: xmitData, url: 'ajax/data', dataType : 'json', success : function(data) { However, what I get in Python after Django handles this is a querydict that looks munged: <QueryDict: {'{"0":{"t1":"1","p1":"100"},"1":{"t2":"","p2":""},"2":{"t3":"","p3":""},"3":{"t4":"","p4":""},"4":{"t5":"","p5":""},"5":{"t6":"","p6":""},"6":{"t7":"","p7":""},"7":{"t8":"","p8":""},"numTickers":8}': ['']}> To me, this says that JS/JQuery used ALL of the multi-level key/value pairs as a big key, with the value [''] (note the single quotes). I have … -
Django CSS not working on live site
This site is live and hosted with Digital Ocean. I finally got it to work properly, however the css won't work for the site? Here's what I have setup, there are no errors, just the css won't work. I have this in my settings.py: STATIC_URL = '/static/' STATIC_ROOT = '/static/' STATIC_DIR = os.path.join(BASE_DIR,'static') STATICFILES_DIRS = [ STATIC_DIR, ] Here are my project urls.py: from django.conf.urls import url from django.contrib import admin from django.conf.urls import include from blog import views from users import views from feed import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',views.HomeView.as_view(),name='index'), url(r'^user/',include('users.urls',namespace='users')), url(r'^feed/',include('feed.urls',namespace='feed')), url(r'^blog/',include('blog.urls',namespace='blog')), url(r'^accounts/', include('allauth.urls')), ] File structure: - django_project - /allauth/ - /blog/ - /django_project/ - /feed/ - manage.py - /media/ - req.txt - /static/ - /css/ - /templates/ - /users/ - gunicorn.socket I have run python manage.py collectstatic -
Login and Logout view not working in django auth system
I am using the Django auth system for my app. I have made a CustomUser table using AbstractUser functionality to add some more fields. //models.py from django.contrib.auth.models import AbstractUser from django.contrib.sessions.models import Session class CustomUser(AbstractUser): addr1= models.CharField(max_length=20) addr2= models.CharField(max_length=20) city= models.CharField(max_length=20) state= models.CharField(max_length=20) class UserSession(models.Model): user= models.ForeignKey(settings.AUTH_USER_MODEL) session=models.ForeignKey(Session) //views.py from .models import UserSession from django.contrib.auth.signals import user_logged_in def login(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect('/Student_home.html') # Redirect to a success page. else: return HttpResponse("disabled account") # Return a 'disabled account' error message else: return HttpResponse("invalid login")# Return an 'invalid login' error message. def logout(request): logout(request) return HttpResponseRedirect('/Student_home.html')# Redirect to a success page. def user_logged_in_handler(sender,request,user, **kwargs): UserSession.objects.get_or_create( user= user, session_id= request.session.session_key ) user_logged_in.connect(user_logged_in_handler, sender=CustomUser) def delete_user_sessions(CustomUser): user_sessions=UserSession.objects.filter(user=CustomUser) for user_session in user_sessions: user_session.session.delete() //forms.py from django.contrib.auth.forms import AuthenticationForm from django import forms class LoginForm(AuthenticationForm): username = forms.CharField(label="Username", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'})) password = forms.CharField(label="Password", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'password'})) //project/urls.py(the outer one) from django.contrib.auth import views from swaracharya.forms import LoginForm url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'), url(r'^logout/$', views.logout, {'next_page': '/login'}), //login.html <div class="container"> <section id="content"> <form action="{% url 'login' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} … -
Python-Django project ideas
I learned python and Django , watching videos and reading some books. I also developed small applications on Django, like login page application. I want to implement any project on Django, which i can put on my resume. So that it will be helpful for me to find internship. Can somebody please help me out with any good project idea. TIA. -
Getting back a nonexistant url in test
So I have a django web app called notes where I have a viewset. The viewset is composed of CRUD commands. When I created a test to the api it keeps redirecting to a nonexistent url instead of the Json String. Here is my code: For tests.py: def test_list(self): e = Employee.objects.get(first_name="Dylan") organ = Organization.objects.get(name='test') cl = APIClient() # cl = APIClient() c = Customer.objects.get(first_name="John") cl.credentials(HTTP_AUTHORIZATION='Token ' + organ.token.key) response = cl.post('/api/notes/list', {'customer_id': c.uuid}, follow=True) #cl.login(username = "Dylan", password="Snyder") pprint("list: %s" % response.data) for api.py: def list(self, request): c = Customer.objects.get(pk=request.POST['customer_id']) n = Note.objects.get(customer=c, retired=False) notes = NoteListSerializer(n) return HttpResponse(notes) The results I get: .'list: {\'detail\': \'Method "GET" not allowed.\'}' in the command prompt I use. I never made a directory or have anything that contains /details/ in it -
Bootstrap is not hit to HTML
Bootstrap is not hit to HTML. I use Flat UI's Bootstrap. I wrote in index.html like {% load staticfiles %} <html lang="ja"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static './bootflat.github.io/bootflat/css/bootflat.min.css' %}"> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <style> body { padding-top: 70px; } .my-form { width: 640px; margin: 0 auto; } @media screen and (max-width: 768px) { .my-form { width: 100%; } } .errorlist li { list-style-type: none; } .errorlist { color: red; margin-left: 0; padding-left: 0; } </style> </head> <body> <nav class="navbar navbar-default" role="navigation"> <div class="navbar-header"> <p class="navbar-text">Hello</p> {% if user.is_authenticated %} <p class="navbar-text">{{ user.get_username }}</p> {% endif %} </div> </nav> <div class="container"> {% block content %} {% endblock %} </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> </body> </html> I designate folder path which has Flat UI like <link rel="stylesheet" href="{% static './bootflat.github.io/bootflat/css/bootflat.min.css' %}"> but the design is not changed.I accessed http://localhost:8000/static/bootflat.github.io/bootflat/css/bootflat.min.css,but Page not found (404) Request Method: GET Request URL error happens.So I think path is wrong. Directory structure is index.html is in accounts.accounts folder structure is What is wrong in my code?How should I fix this?