Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implicitly wiring an HTML document to a Django Rest Framework API View
I'm following along with this tutorial. I have the back-end ready to go, but the author has wired up a base.html to the DRF view and it seems to be dynamically resolving. There isn't a hardcoded reference to an HTML file in the entire project, but he's loading multiple files as if by magic. This is not explained in the tutorial, and I can't seem to invoke this behaviour in Django. How do I point a DRF API view to an html document without actually defining a path to the file? -
Are there any tutorials or videos on Django-dash
I want to build a python powered dashboard. After doing some research i felt that Django-dash would suit my need pretty well. However i have not been able to get it running. I have gone throught the instructions on the Git hub page. I also tried to follow the instructions and install the example but that did not work either. There are so many errors that it gets frustrating. I am using a windows machine and for starters would like to get it installed on windows. I am relatively new to django but am aware of the basics. -
Unable to save the Userprofile after post_save
I am following a tutorial and for some reason i am not able to make the connection between user and user profile. I followed the django docs but to no avail. Models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfileManager(models.Manager): def get_queryset(self): return super(UserProfileManager, self).get_queryset().filter(city='London') class UserProfile(models.Model): user = models.OneToOneField(User) bio = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') image = models.ImageField(upload_to='profile_image', blank= True) # this how to associate the UserProfileManager to the user profile houston =UserProfileManager() objects = models.Manager() def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) Admin.py from django.contrib import admin from accounts.models import UserProfile # Register your models here. admin.site.register(UserProfile,UserProfileAdmin) class UserProfileAdmin(admin.ModelAdmin): list_display = ('user', 'cityfrom', 'bio') #grabs the list and displays it on the admin def cityfrom(self, obj): return obj.city def get_queryset(self, request): queryset =super(UserProfileAdmin, self).get_queryset(request) queryset = queryset.order_by('user') return queryset views.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, UserChangeForm from accounts.models import UserProfile __all__ = [UserProfile] class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] … -
Cannot run Django heroku app locally on Windows
So, I want to test my all locally, but something goes wrong. After installing virtualenv, activating it, installing requirements.txt and running collectstatic I try to run app with heroku local web -f Procfile.windows I get [OKAY] Loaded ENV .env File as KEY=VALUE Format And that's all. I wait for about 30 mins and then stop execution. Then I get 16:07:33 web.1 | Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x042BEF60> 16:07:33 web.1 | Traceback (most recent call last): Traceback is empty. This is all output. Sometimes, when I wait for about only 1-2 minutes no messages appear at all. File Procfile.windows looks like: web: python manage.py runserver 0.0.0.0:5000 What's wrong? Why this exception occurs? -
django-settings-export not passing variables
I am using Django 1.11 and django-settings-export, but it is not working for this view: from django.shortcuts import render_to_response def foo(request): return render_to_response('foo.html', {}) -
django makemigration won't recognize GenericRelation field
I'm trying to add a GenericRelation field to my model and then run : from django.contrib.contenttypes.fields import GenericRelation class FAQ(models.Model): # the rest of my model fields answer = GenericRelation(SomeModel) after adding the last line to the code I run: python manage.py makemigrations < appname > but I get the "no changes detected" message.I get results when I add other fields like models.CharField() to the Model. Also I tried GenericModel with other models and it still didn't work. is there any reason I can't make this migration?? is makemigrations supposed to recognize this change at all or does django not create a column in the table for this field at all?? thanks in advance. -
Django Query : keep only the earliest records with references to a particular instance
I have a Match object which has ReferenceFields to a Player1 and Player2 (Player objects) and a DateTimeField. I want to create an optimized query that returns only the most recent upcoming match for each team. Imagine, for instance, the list of upcoming games are as follows: Tomorrow Player A vs Player B 2 weeks Player A vs Player C 3 weeks Player B vs Player C The expected result of the 'next match' query would only return Player A vs Player B, because the other matches contain a player who is in an earlier upcoming match. At present I am doing this through a non-Django filter (just a basic filtering function). But the problem is that it's quite expensive on DB hits. Would prefer to do it through a QuerySet if possible. -
Python Django returning 400 GET messages on script and images
I have a python server running. And at the onset, it runs the application perfectly loading the images and scripts. If I leave it running for 24hrs, I discover that it gives a GET 400 error messages of not loading the images/scripts. I also observed that if I replace all the applications altogether with the backup, then it likely starts running perfectly again. My settings.py: 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 = 'e#-^aknk(5k)ej6rh#h$i(%h(m9)-j*lwrc_1dxnk=a@-mixlt' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'uploads.core', ] 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 = 'uploads.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'uploads/templates'),], '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', 'django.template.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'uploads.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.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 … -
201 created status code sent by django rest framework interpreted as failiure by jquery $.ajax call
I am simply using django-rest-frameworks CreateAPIView which returns a response containing a 201 status code. I would expect this to work with the standard javascript/jquery ajax functions. But apparently it does not. Here is a similar issue where Retrofit throws an error. Any Ideas on how to debug this on jquery? -
RecursionError: when using factory boy
I can't use factory boy correctly. That is my factories: import factory from harrispierce.models import Article, Journal, Section class JournalFactory(factory.Factory): class Meta: model = Journal name = factory.sequence(lambda n: 'Journal%d'%n) @factory.post_generation def sections(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of groups were passed in, use them for section in extracted: self.sections.add(section) class SectionFactory(factory.Factory): class Meta: model = Section name = factory.sequence(lambda n: 'Section%d'%n) and my test: import pytest from django.test import TestCase, client from harrispierce.factories import JournalFactory, SectionFactory @pytest.mark.django_db class TestIndex(TestCase): @classmethod def setUpTestData(cls): cls.myclient = client.Client() def test_index_view(self): response = self.myclient.get('/') assert response.status_code == 200 def test_index_content(self): section0 = SectionFactory() section1 = SectionFactory() section2 = SectionFactory() print('wijhdjk: ', section0) journal1 = JournalFactory.create(sections=(section0, section1, section2)) response = self.myclient.get('/') print('wijhdjk: ', journal1) self.assertEquals(journal1.name, 'Section0') self.assertContains(response, journal1.name) But I get this when running pytest: journal1 = JournalFactory.create(sections=(section0, section1, section2)) harrispierce_tests/test_index.py:22: RecursionError: maximum recursion depth exceeded while calling a Python object !!! Recursion detected (same locals & position) -
Errno 13 Permission denied: '/var/www/.config' - biopython
I have tried everything out there to try and get rid of this error including this stack post Tried setting media root as mentioned elsewhere. This post seems to have outlined the problem but no solution was given. Any help would be greatly appreciated. TIA :) [Errno 13] Permission denied: '/var/www/.config' Request Method: POST -Django Version: 1.11.3 Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: '/var/www/.config' Exception Location: /home/--/myproject/myprojectenv/lib/python3.5/os.py in makedirs, line 241 Python Executable: /home/--/myproject/myprojectenv/bin/python Python Version: 3.5.2 Python Path: ['/home/--/myproject', '/home/--/myproject/myprojectenv/lib/python35.zip', '/home/--/myproject/myprojectenv/lib/python3.5', '/home/--/myproject/myprojectenv/lib/python3.5/plat-x86_64-linux-gnu', '/home/--/myproject/myprojectenv/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/home/--/myproject/myprojectenv/lib/python3.5/site-packages'] Server time: Sat, 12 Aug 2017 12:08:02 +0000 Error details from the server. Seems to be emanating from biopython trying to write to var/www/ folder raise exception ... ▼ Local vars Variable Value __module__ 'Bio.Entrez.Parser' __qualname__ 'DataHandler' local_dtd_dir '/var/www/.config/biopython/Bio/Entrez/DTDs' local_xsd_dir '/var/www/.config/biopython/Bio/Entrez/XSDs' /home/---/myproject/myprojectenv/lib/python3.5/site-packages/Bio/Entrez/Parser.py in DataHandler os.makedirs(local_dtd_dir) # use exist_ok=True on Python >= 3.2 ... ▼ Local vars Variable Value __module__ 'Bio.Entrez.Parser' __qualname__ 'DataHandler' local_dtd_dir '/var/www/.config/biopython/Bio/Entrez/DTDs' local_xsd_dir '/var/www/.config/biopython/Bio/Entrez/XSDs' /home/---/myproject/myprojectenv/lib/python3.5/os.py in makedirs makedirs(head, mode, exist_ok) ... ▼ Local vars Variable Value exist_ok False head '/var/www/.config/biopython/Bio/Entrez' mode 511 name '/var/www/.config/biopython/Bio/Entrez/DTDs' tail 'DTDs' /home/---/myproject/myprojectenv/lib/python3.5/os.py in makedirs makedirs(head, mode, exist_ok) ... ▼ Local vars Variable Value exist_ok False head '/var/www/.config/biopython/Bio' mode 511 name '/var/www/.config/biopython/Bio/Entrez' tail 'Entrez' … -
Defining a Django query set with a many-to-one relationship with calculation
I have three models: Assets, AssetTypes and Services. Assets need to get serviced every n months, and have a many-to-one relation with services. class AssetType(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(verbose_name="Asset Type", max_length=100) service_period = models.PositiveSmallIntegerField(verbose_name="Service Period (in months)", null=True, blank=True, default=12) class Asset(models.Model): id = models.AutoField(primary_key=True) type = models.ForeignKey(AssetType, on_delete=models.PROTECT) def service_period(self): return AssetType.objects.get(pk=self.type.id).service_period def service_history(self): return self.service_set.all().order_by('-date') def service_due_date(self): if self.service_period()==None: return None elif self.service_history().count()==0: return datetime.strptime('2017-01-01', '%Y-%m-%d').date() else: last_service_date = self.service_history().latest('date').date return last_service_date + timedelta(self.service_period()*30) def service_overdue(self): return ((self.service_due_date()!=None) and self.service_due_date() < date.today()) class Service(models.Model): id = models.AutoField(primary_key=True) date = models.DateField() asset = models.ForeignKey(Asset, on_delete=models.CASCADE) I'm trying to work out how to make a query set that would return a list of assets that are overdue for their service. I feel like using a model method is a red herring, and that I would be better off defining a query set filter? I need the list of overdue assets to be a query set so I can use further query set filters on it. Any assistance would be greatly appreciated! -
Get email in another model after user is created in django
I am a beginner in django. When admin creates a user, I am trying to save some fields in EmailAddress model.But for some reason the email field is always blank. Is there any way I can update the instance with email in UserProfile or EmailAddress model. models.py looks like this User._meta.get_field('email').blank = False User._meta.get_field('email')._unique = True class EmailAddress(models.Model): user = models.OneToOneField(User, unique=True, related_name ='address') verified = models.BooleanField(verbose_name=_('verified'), default=True) primary = models.BooleanField(verbose_name=_('primary'), default=True) class Meta: db_table = 'account_emailaddress' class UserProfile(models.Model, HashedPk): user = models.OneToOneField(User, unique=True, related_name ='profile') job_title = models.CharField(max_length=128, blank=True, null=False, default="") website = models.URLField(max_length=255, blank=True, null=True) organisation = models.CharField(max_length=50, blank=True, null=True, default="") phone_number = PhoneNumberField( blank=True, null=True) @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) EmailAddress.objects.create(user=instance) forms.py looks like this -- class SignUpForm(forms.Form): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) phone_number = PhoneNumberField(label=_("Phone (Please state your country code eg. +44)")) organisation = forms.CharField(max_length=50) email = forms.EmailField() password1 = forms.CharField(max_length=20) password2 = forms.CharField(max_length=20) captcha = ReCaptchaField(attrs={'theme' : 'clean'}) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] up = user.profile up.phone_number = self.cleaned_data['phone_number'] up.organisation = self.cleaned_data['organisation'] user.save() up.save() Any help is highly appreciated. -
Reverse_lazy and URL Loading?
I'm trying to wrap my head around Django concepts, but I struggle with the URLResolver reverse_lazy(). As far as I know, I have to use reverse_lazy() when I want to reverse to an URL that has not been loaded. So when I create a CBV and state a success_url, I use reversy_lazy. This means that the url is not imported when the file executes. This is confusing to me because I think the server loads all the URLs while starting before executing anything. So how come the URL is not loaded in time of execution? I would be very happy if someone would give me an answer to this. -
Sent JSON data to DJANGO. Now I can't get it back
Good day. I sent JSON data to my server (js to Django) and in the server, I just saved the data (still in JSON format) directly to the database without converting it to string. Now I want to retrieve that same data but it's not working. Here is my code: $.ajax({ url: '/submitdata/', type: 'POST', dataType: 'text', data: JSON.stringify(userdata), contentType: 'application/json; charset=utf-8', success: function (){ alert('success'); }, error: function (){ alert('sorry, an error occurred'); )}; And in the server def submitdata(request): if request.is_ajax(): If request.method == 'POST': save_data = my_model( username='michael', userdata = request.body) save_data.save() It worked fine. It got saved into the database. The problem I have now is retrieving it. I tried this: In my client $.ajax({ url: '/getdata/', type: 'POST', data: { user_name: 'michael' }, success: function (result){ JSON.parse(result); }, error: function (){} )}; And in my server if request.method == 'POST': user_name = request.POST['user_name'] datum = my_model.objects.get(username=user_name) return HttpResponse(datum) It doesn't work. It gives me an error: Unexpected character at line 1 column 1 of JSON data Note: I tried to use JSON.parse on the returning data -
Getting TypeError: 'NoneType' object is not iterable when sending ajax post request django views
I want to print the list of all my checked choices in my django view function,but when i send throught ajax selected data,i get the following error in my console: Traceback (most recent call last): File "C:\Users\lislis\DJANGO~2\DJANGO~1.2\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\lislis\DJANGO~2\DJANGO~1.2\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\lislis\DJANGO~2\DJANGO~1.2\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\lislis\Django-VEnvs-Projects\django 1.11.2\src\rapport_sante\papa\views.py", line 78, in stat_ajax for d in tb_ids: TypeError: 'NoneType' object is not iterable [12/Aug/2017 11:53:07] "POST /sante/stat-ajax/ HTTP/1.1" 500 19573 Here is a part of my ajax post request: var data =[]; $(":checkbox:checked").each(function() { data.push($(this).val()); }); if(data.length==0) { alert("Veuillez cocher au moins une dps"); alert(data.length); } else { $.ajax({ url: "{% url 'papa:stat-ajax' %}", type:"post", data: {dpsID:data,csrfmiddlewaretoken: '{{ csrf_token }}'}, success:function(data) { //Some code } }); Here is my view function,where i would like to display all the data contained in the dpsID of my ajax POST request: def stat_ajax(request): tb_ids=request.POST.get('dpsID') for d in tb_ids: print(d) -
The word "action" in an iframe causes xxs warning
I have built a bulk-emailer for the Django admin, It's been in production for two years. I use Sendgrid to send the emails. The admin part is divided into a two step form. In step one, you enter subject, recipients etc and then the content in a Tinymce WYSIWYG. Step two fetches the template from Sendgrid and displays the email in the Sendgrid template via an iframe as a preview... Fine, everything works great and as I said has done for two years... Except for today when I tried sending an email containing the sentence: "Extending the interrogation of the brief to the interrogation of the client—assessing if there’s enough action being taken by the client to contain the situation and enable an effective reputation management exercise." This causes Chrome/Opera (not tested elsewhere yet) to complain about XSS: This page isn’t working Chrome detected unusual code on this page and blocked it to protect your personal information (for example, passwords, phone numbers and credit cards). Try visiting the site's homepage. ERR_BLOCKED_BY_XSS_AUDITOR Remove the word "action" and it works as intended. Remove the whole sentence and replace with the word "action" and it works as intended.... Anyone got any idea at … -
No changes detected when i excute pyhon manage.py makemigrations and migrate
i am try to make migration using python manage.py migrations tithe nothing is detected .i have even changed my database to postgres but nothing have changed .even python manage.py migrate is not working what could be the problem @localhost church]$ python manage.py migrate tithe Operations to perform: Apply all migrations: (none) Running migrations: No migrations to apply. this my model.py code from __future__ import unicode_literals from django.utils import timezone from django.contrib.auth.models import User from django.conf import settings from django.contrib.auth import get_user_model from django.core.signals import setting_changed from django.dispatch import receiver from django.db import models # Create your models here. class tithe(models.Model): member_code = models.ForeignKey(settings.AUTH_USER_MODEL) member = models.CharField(max_length=45) receipt_code = models.CharField(max_length=45, unique=True) tithes = models.IntegerField() combinedoffering = models.IntegerField() campmeetingoffering = models.IntegerField() churchbuilding = models.IntegerField() conference = models.IntegerField() localchurch = models.IntegerField() funds = models.IntegerField() total = models.IntegerField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.receitcode class Meta: abstract = True -
How to get all the django formset choices in jquery
Following is a part code where I'm asking the user to enter n number of choices/options for a choice based question. Now since correct choice will be one among the entered choices in the forms of formset. So, I want to dynamically populate my correct choice select field using jquery. But for that I need all the values in forms of formset. Is, there any in-built method to do that. <div class="row marginTop35"> <div class=" col s5"> {{ choice_formset.management_form }} {% for choice_form in choice_formset.forms %} <div class="choice-item"> <div class="row margin0"> <label> <div class="input-field col s11"> <i id="{{ choice_form.choice.id_for_label }}_icon" class="material-icons prefix">label_outline</i> <input name="{{ choice_form.choice.html_name }}" id="{{ choice_form.choice.id_for_label }}" type="text" class="validate" value="{{ choice }}"> <label id="{{ choice_form.choice.id_for_label }}_label" for="{{ choice_form.choice.id_for_label }}" data-error="{% if email_error_message %}{{ email_error_message }}{% else %}Enter valid choice{% endif %}">Choice </label> </div> <div class="col s1 lineHeightInherit"> <a class="btn-floating red darken-1 delete-choice"> <i id="{{ choice_form.choice.id_for_label }}_icon" class="material-icons right">delete</i> </a> </div> </label> </div> </div> {% endfor %} <div class="margin0"> <a id="add-choice" class="waves-effect waves-light btn-floating indigo accent-2" style="margin-left: 42px;"> <i class="material-icons">add</i> </a> </div> </div> <div class="input-field col s5 right"> <i id="{{ form.correct_choice.id_for_label }}_icon" class="material-icons prefix">label</i> <select name="{{ form.correct_choice.html_name }}" {% block select_multiple %}{% endblock %} > <option value="" selected disabled>Choose … -
Email could not sent using Django and Python
I am facing one issue. I have implemented the reset password functionality using Django. Here I am sending the reset password link to registered email and no mail is coming to the inbox. I am explaining my code below. settings.py: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'user474@gmail.com' EMAIL_HOST_PASSWORD = '*********' EMAIL_USE_TLS = False DEFAULT_FROM_EMAIL = 'user474@gmail.com' registeration/password_reset_form.html: {% extends 'base.html' %} {% block content %} <h3>Forgot password</h3> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %} registration/password_reset_email.html: {% autoescape off %} To initiate the password reset process for your {{ user.get_username }} TestSite Account, click the link below: {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} If clicking the link above doesn't work, please copy and paste the URL in a new browser window instead. Sincerely, The Nuclear Team {% endautoescape %} Here I could not send the mail to the given email id. Please help me. -
How to add a custom button or link beside a form field
I am using django with cripspy_forms third party library. I want to add a link beside a form field like some forms in django admin app. How can I do this. Thank you in advance. -
The a tag did not goto the html in django templates
This is the template code: <div class="header-nav"> <button class="am-show-sm-only am-collapsed font f-btn" data-am-collapse="{target: '.header-nav'}">Menu <i class="am-icon-bars"></i></button> <nav> <ul class="header-nav-ul am-collapse am-in"> <li class="on"><a href="index.html" name="index">网站首页</a></li> <li><a href="productlist.html" name="show">工程案例</a></li> <li><a href="article_list.html" name="new">新闻资讯</a></li> <li><a href="about.html" name="about">关于我们</a></li> <li><a href="contact.html" name="message">联系我们</a> <div class="secondary-menu"> <ul><li><a href="message.html" class="message"></a></li></ul> </div> </li> </ul> </nav> </div> and it runs in django env-server. At first the url is : http://localhost:8000/index/ And if I I click the "工程案例": the url becomes http://localhost:8000/index/productlist.html, but the html page did not switch, still in this page. edit This is my urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', f_end_v.Index), url(r'^index/', f_end_v.Index), ] -
how to load a class in admin.py based on user permissions
I have been developing an application for song link submission in django, and I would like to make some field non-editable for the staff users in the admin area but the superusers can edit it. # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.contrib.auth.models import User # Register your models here. from .models import SongLinks class SongLinksAdmin(admin.ModelAdmin): if request.user.is_staff: readonly_fields=('ip','dedicated_to','dedicated_message') list_display = ('song_link','dedicated_to','dedicated_message','ip') else: list_display = ('song_link','dedicated_to','dedicated_message','ip') admin.site.register(SongLinks, SongLinksAdmin) this gives me an error: if request.user.is_staff: NameError: name 'request' is not defined What is wrong with this? -
Deploying python web apps using AWS and micro services?
i am a beginner to DevOps. I have only had experience in Local Development of Python apps and Heroku. I have finally completed my app and would like to deploy it on AWS. App Structure: Backend Application - Built with Django and DRF. FrontEnd - Built with Angular 2 communicating with backend REST Api. Database - PostgreSQL I have tons of questions in DevOps. I want the app to be scalabe, Will be launching future versions. I have come across Docker for containerization. Jenkins CI for Integration. Kubernetes for managing Deployment and Scaling. My Question is How does everything work together. I would like to know the setup process. Should i be using Chef or puppet? Any other tools i should learn to deploy and manage a scalable app on AWS. -
How to implement forget password functionality using Django and Python
I need one help. I need to implement the forget password functionality using Django. I am using the Django signup and login page. I am explaining my code below. login.html: {% extends 'base.html' %} {% block content %} <h2>Log in</h2> {% if form.errors %} <p style="color: red">Your username and password didn't match. Please try again.</p> {% endif %} <form method="post"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }}<br> {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} {% if field.help_text %} <p><small style="color: grey">{{ field.help_text }}</small></p> {% endif %} </p> {% endfor %} <button type="submit">Log in</button> <a href="{% url 'signup' %}">New to My Site? Sign up</a> </form> {% endblock %} views.py: class Signup(View): """ this class is used for user signup """ def get(self, request): """ this function used to get the sign up form """ form = UserCreationForm() return render(request, 'plant/signup.html', {'form': form}) def post(self, request): """ this function used for post the sign up data """ form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login') class AuthLogin(View): """ Its for login """ def get(self, request): """ this function used to get the login form """ form …