Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin wont allow me to allocate permissions to Users or Groups
I am using django 1.8.6 and have a new application created in a virtualenv using python manage.py startproject. I have set up my INSTALLED APPS and my database settings (postgresql) and I have run migrate to create the backend. So far all seems fine. I then created a superuser using the createsuperuser command and that all seemed to go fine too. My admin.py file is in place and the content of which is as follows: from django.contrib import admin from django.contrib.admin import AdminSite from myapp.models import mymodel Class mymodelAdmin(admin.ModelAdmin): list_display = {col1, col2, col3} admin.site.register(mymodel, mymodelAdmin) All what appears to be fairly simple standard stuff, so far so good. I'm using apache to render my webpages and having configured my virtualhost stuff I can happily log in to my admin page and see everything I have registered plus the default django admin stuff. I can create a new user with no problem and I can create a new Group with no problem. Where I am running into trouble is I ma not able to assign any standard permissions to with my new user or my group. I can see the list of permissions from my database with no problem but … -
token issue while creating and updating an user
In my app I ask a user to invite a teammate by inviting him to the appli. I did it by giving the user that ability to create a user that stay inactive until the teammate sign into the application. The worflow is the following: 1) User create a Teammate user using only the Email 2)a random password is generate 3)the user is saved into the database as inactive 4) An email is sent to the teammate to sign in 5) The teammate update his profile give a First name, last name update his password and is now active on the app. I do not know why it does not update the right user but the user with pk=1 Could you have a look and tell me what is wrong with my code please ? url.py: from django.conf.urls import url, include from registration import views app_name = 'registration' urlpatterns = [ url(r'^hr_register/$', views.registerHR, name='hr_register'), url(r'^auth_HRlogin/$',views.HR_login,name='HRlogin'), url(r'^update/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',views.CandidateSignIn,name='CandidateSignIn'), url(r'^auth_logout/$',views.user_logout,name='logout'), url(r'^auth_team_register/$', views.TeamRegister, name='team_register'), email sent: {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, http://{{ domain }}{% url 'registration:CandidateSignIn' uidb64=uid token=token %} {% endautoescape %} views.py def CandidateSignIn(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user … -
mechanics of django WSGI POST object
I have a django form with POST method in index.html, with multi-checkboxes enabled for the field "preferences". in Views.py, I have the following code: preferences = request.POST print(preferences) preferences = request.POST.get("preferences") print(preferences) Output in console: food why does the output only select the latter element ("food") instead of ['drink','food']? Also, please help me understand how to achieve the output of all preferences. thank you! -
if and elif doesn't work in template django
if and elif doesn't work in my template django index.html <a style="{% if show.Ages == 19 %}background:#ff3636;{% elif show.Ages == 17 %}background:#fb9c92;{% elif show.Ages == 13 %}background:#ffb466;{% else %}background:#4aff68;{% endif %};border-radius: 15px;width: 140px;height: 42;margin-right: 831px;margin-top: -200;" class="button">رده سنی:+{{ show.Ages }}</a> views.py def index(request): shows = show.objects.all() context = { 'shows':shows } return render(request,'index.html', context) models.py class show(models.Model): Ages = models.CharField(max_length=10,default='',null=True) what is the problem? -
Correctly wiring volumes for serving static files using nginx and Django
I am having issues correctly linking up the different parts of the application to correctly serve static files to users. This is the scenario: I have an existing Django website that I want to "dockerize". My problem is probably that I'm very confused as to how volumes/containers work, and I've tried to read up about it but I cannot get it working. I have created the following directory structure: project/ nginx/ Dockerfile nginx.conf web/ << django website >> Dockerfile docker-compose.yml project/docker-compose.yml deploys the Django application and, via Gunicorn, makes it available at 0.0.0.0:8080, albeit without being able to load static files. The project/web/Dockerfile runs a collectstatic operation on the Django app and collects all static files in /usr/src/app/static_files. By running a bash shell on the web container I have confirmed that these files are indeed here. version: '3.3' services: web: restart: always build: ./web expose: - "8080" ports: - "8080:8080" volumes: ## something goes here? command: /usr/local/bin/gunicorn wsgi:application --workers 2 --bind 0.0.0.0:8080 depends_on: - postgres nginx: restart: always build: ./nginx ports: - "80:80" volumes: ### something goes here? depends_on: - web postgres: image: postgres:9.2 restart: always volumes: - pgdata:/var/lib/postgresql/data ports: - "5432:5432" volumes: pgdata: How do I modify the docker-compose … -
creating relationship between two apps in django
I have a post and a category app in my django project. I have user authentication and users can create categories as well as posts. I am at a point where I am out of ideas and help would be appreciated. I want users to be able to reference only their own category and create posts in their categories not in another persons own. That is if a user creates more that one category he should be able to select from the list of his created category and not see another persons own. category model class Category(models.Model): name = models.CharField(max_length = 120) slug = models.SlugField(unique= True) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) post model class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1,related_name='posts_created') #blank=True, null=True) title = models.CharField(max_length = 120) slug = models.SlugField(unique= True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category_created', null= True) addition codes would be provided immediately on request. Thanks -
How to insert data into database overwriting the header in Django
Not sure whether the title is correct but I'll show you an example: I have the django model: class testDb(models.Model): date = models.DateField(verbose_name="Date") hour_1 = models.CharField( max_length=5, verbose_name="Hour_1" ) hour_2 = models.CharField( max_length=5, verbose_name="Hour_2" ) hour_3 = models.CharField( max_length=5, verbose_name="Hour_3" ) hour_4 = models.CharField( max_length=5, verbose_name="Hour_4" ) hour_5 = models.CharField( max_length=5, verbose_name="Hour_5" ) def __str__(self): return str( self.date ) And all what I want to do is insert data into this table based on current hour, for an instance: currentHour = '4' b = testDb(data=Today, hour_currentHour='23') b.save() Was trying to find solution using Google but unsuccessfully. Thanks in advance, -
custom Django Rest Framework json output format(CBV)
What do I want? For Success: { "data": { "id": 123, "name": "Django" } } For Errors (serializer errors or other exceptions): { "error": { "name": ["this field is required"] } } My Code: renderer_classes = [CustomJSONRenderer] # adds 'data' key def get_exception_handler(self) return custom_exception # adds 'error' key to output for errors My Output: for Success: (Good) { "data": { "id": 123, "name": "Django" } } For Error: (Wrong) { "data": { # Remove this key "error": { # this should be first key for output "name": ["This field required"] } } } -
Twisted-Python run python application with twistd -y chatserver.py, error occurs
when running this command-line twistd -y chatserver.py I get this error Traceback (most recent call last): File "/usr/local/bin/twistd", line 7, in <module> import _preamble ImportError: No module named '_preamble' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/bin/twistd", line 9, in <module> sys.exc_clear() AttributeError: module 'sys' has no attribute 'exc_clear' what should I do. -
Django pre_save is not triggered
I'm creating an instance of a model (Container), and it seems like the pre_save function is not triggered. This is the class in the 'signals': class ContainerCreatedMixin(object): @staticmethod @receiver(pre_save, sender=Container) def container_pre_save(sender, instance, **kwargs): # create container folder if not created yet if instance.folder_created_at is None: is_folder_created = ContainerCreatedMixin().create_folder(instance) if is_folder_created: instance.folder_created_at = now() def create_virtual_folder(self, container): try: ...... -
Askbot - a Django Q&A forum platform
export var UserSchema: Schema = new mongoose.Schema( { createdAt: Date, email: { type: String, required: true, trim: true, unique: false, }, firstName: { type: String, required: false, trim: true }, lastName: { type: String, required: false, trim: true }, password: { type: String, trim: true, minlength: 6 }, tokens: [{ access: { type: String, required: true }, token: { type: String, required: true } }] }); and I've a instance method like: UserSchema.methods.generateAuthToken = () => { console.log("generateAuthToken"); var user = this; console.log(user); var access = 'auth'; console.log(user._id); }; Askbot - a Django Q&A forum platformAskbot - a Django Q&A forum platformAskbot - a Django Q&A forum platformAskbot - a Django Q&A forum platformAskbot - a Django Q&A forum platformAskbot - a Django Q&A forum platformAskbot - a Django Q&A forum platformAskbot - a Django Q&A forum platformAskbot - a Django Q&A forum platformAskbot - a Django Q&A forum platformAskbot - a Django Q&A forum platformAskbot - a Django Q&A forum platformAskbot - a Django Q&A forum platformAskbot - a Django Q&A forum platformAskbot - a Django Q&A forum platformAskbot - a Django Q&A forum platformAskbot - a Django Q&A forum platformAskbot - a Django Q&A forum platformAskbot - a … -
Redirection issue using django
I have an issue, I do not know why it is happening and how to solve it; My app ask a user to create a project and is redirect directly to the project detail page. On that detail page if a team_id is empty I ask the user to create a team and when the team is created the user is redirected again to the project detail page to now be able to populate his team. I used the code {% if Project.team_id == None %} when the user is redirected after creating his team but it is not working .. could you please help ? my html: {% extends 'base.html' %} {% block body %} <div class="container"> <div class="jumbotron"> <h2>Welcome to your Project {{ project.name }} Detail page</h2> </div> {% if Project.team_id == None %} <div class="invite-team"> <div class="jumbotron"> <div class="jumbo-text"> <h3>It is time to link a team to your project now create a new team and add team members</h3> </div> <div class="jumbo-button"> <a href="{% url 'website:add_team' %}" class="btn btn-success" role="button"><span class="glyphicon glyphicon-plus"></span> Create a new team</a> </div> </div> {% else %} <div class="invite-teammembers"> <div class="jumbotron"> <div class="jumbo-text"> <h3>The team {{ project.team_id }} has beed created, we now need … -
How to over ride save button to get inline object in django admin?
I am quite new.How to over ride save button to get inline object in django admin, just like in normal model save button in models.py file? -
How to prevent download of media(Videos, Photos) from a AWS s3 signed url?
I want to display photos and videos in my mobile/web app. I have used short lived signed urls to serve content privately. I want that a person should be able to only view the video in my apps and is not able to download the media even if he sniffs the signed url. -
Tables referencing each other with One-To-Many relationship
I have these 2 models in my django app. It's basically clone of IMDB. I have title and it has type field that defines if it's a film or TV Series. And if it's TV series it has many seasons. And many seasons have many titles as well. So I came up with this solution and it's working for the moment. But I don't know if it's the way to approach this. My models are here: class Title(models.Model): FILM = 'FL' TV_SERIES = 'TV' SHORT_FILM = 'SH' EPISODE = 'EP' name = models.CharField(max_length=255) description = models.TextField() release_date = models.DateField() duration = models.PositiveSmallIntegerField(blank=True, null=True) genres = models.ManyToManyField(Genre) type = models.CharField(max_length=2, choices=( (FILM, 'Film'), (TV_SERIES, 'TV Series'), (SHORT_FILM, 'Short Film'), (EPISODE, 'Episode')), default='FL') poster = models.ImageField(upload_to='posters/%Y/%m/%d', default='posters/Placeholder.png') cast = models.ManyToManyField(Person, through='crew') season = models.ForeignKey('Season', related_name='episodes', on_delete=models.CASCADE, blank=True, null=True) episode = models.PositiveSmallIntegerField(null=True, blank=True) @property def rating(self): return self.reviews.all().aggregate(Avg('rating'))['rating__avg'] or "0" @property def release_year(self): return self.release_date.year @property def genre_list(self): return ', '.join([genre.name for genre in self.genres.all()]) def __str__(self): return self.name class Meta: verbose_name_plural = 'Media' class Season(models.Model): name = models.CharField(max_length=100, null=True, blank=True) release_date = models.DateField() number = models.PositiveSmallIntegerField() title = models.ForeignKey(Media, related_name='seasons', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return "%s - Season %s" % (self.media.name, … -
client.send(channel_name, message) throw exception (Django, centrifugo)
@receiver(models.signals.post_save, sender=Order) def on_bonus_balance_updating(sender, instance, *args, **kwargs): if kwargs.get('created'): try: from core.serializers import OrderSerializer channel_name = "public:bonus_balance#" + str(instance.payer.pk) serializer = OrderSerializer(instance) message = serializer.data if instance.payment_method == 1: client = Client() client.publish(channel_name, message) print("lololo") response = client.send() print('sent to channel {}, got response from centrifugo: {}' .format(instance.get_cent_channel_name(), response)) except BaseException: print("Error in on_bonus_balance_updating payer!") In logs I see "lololo" and "Error in on_bonus_balance_updating payer!" So, only client.send() doesn't work. Message and channel_name are normal, I have checked it. I have not get idea what's is wrong. If you help me I will be very happy! -
how to serialize django.conf.settings to json
I am getting this error... Object of type 'Settings' is not JSON serializable Here is my code from django.conf import settings import json def get_settings(request): responce = settings.__dict__ return HttpResponse(json.dumps(responce),content_type='application/json') -
Django Rest Framework JWT "Authentication credentials were not provided."}
I am trying to write a simple API that uses JWT tokens to authenticate. My settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.IsAdminUser' ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), 'PAGE_SIZE': 10 } And my View looks like this: class ExampleView(APIView): permission_classes = (IsAuthenticated,) authentication_classes = (JSONWebTokenAuthentication,) def get(self, request, format=None): return JsonResponse({"username":str(request.user)}) Which really does nothing, but I don't even get there. I have registered the JWT Token provider as in the documentation with url(r'^api-token-auth/', obtain_jwt_token) and I receive a token when I call this endpoint. However, when I then make a request against my APIView (which contains the header Authorization: JWT <my_token> I always receive the following error: [Response]: 403 [Data]: {"detail":"Authentication credentials were not provided."} What am I missing? Thanks in advance! -
Django ModelForm: Exclude a field which is not in Model
I am having hard time debugging this. I want to exclude confirm_password of RegModelForm in an extended modelform UpdateRegModelForm. I have tried to use exclude in the Meta class of UpdateRegModelForm but it seems to show confirm_password while rendering UpdateRegModelForm anyways. Not sure how to move forward. class RegModelForm(forms.ModelForm): org_admin_email = forms.CharField( label='If you know who should be the Admin, please add their email address below.' ' We\'ll send them an email inviting them to join the platform as the organization admin.', required=False, widget=forms.EmailInput(attrs=({'placeholder': 'Email'})) ) organization_name = forms.CharField( max_length=255, label='Organization Name', widget=forms.TextInput( attrs={'placeholder': 'Organization Name'} ) ) confirm_password = forms.CharField( label='Confirm Password', widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'}) ) class Meta: model = ExtendedProfile fields = ( 'confirm_password', 'first_name', 'last_name', 'organization_name', 'is_currently_employed', 'is_poc', 'org_admin_email', ) labels = { 'is_currently_employed': "Check here if you're currently not employed.", 'is_poc': 'Are you the Admin of your organization?' } widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'First Name'}), 'last_name': forms.TextInput(attrs={'placeholder': 'Last Name'}), 'is_poc': forms.RadioSelect() } class UpdateRegModelForm(RegModelForm): class Meta(RegModelForm.Meta): exclude = ('confirm_password',) -
django uwsgi no module named site
First of all, I'm aware many related question exists but non of them solved my problem. I installed uwsgi using sudo pip3 install uwsgi on centOs 7 when my virtualenv is activated. I try to run it with command uwsgi --http :8000 --module ashpazi.wsgi --ini ../ini_files/ashpazi.ini I get this error ImportError: No module named site this is my ashpazi.ini file [uwsgi] chdir = /root/projects/ashpazi home = /root/projects/venv module = ashpazi.wsgi:application master = true processes = 5 uid = root gid = nginx env = DJANGO_SETTINGS_MODULE=ashpazi.settings plugin = python3.6 socket = /root/projects/sockets/ashapazi.sock chmod-socket = 777 vacuum = true Running which uwsgi returns /usr/bin/uwsgi which is not in virtualenv directory And running sudo pip3 show uwsgi will return this. Name: uWSGI Version: 2.0.15 Summary: The uWSGI server Home-page: https://uwsgi-docs.readthedocs.io/en/latest/ Author: Unbit Author-email: info@unbit.it License: GPL2 Location: /usr/lib/python2.7/site-packages which states that uwsgi is in python2.7 folder and not python3.6 I'm using in my django project. how can i solve this? -
data table pagination with django rest post api
I have a rest api generated by django rest framework which in fact a simple date range search api , given below, @api_view(['POST']) @permission_classes((StaffOnly,)) def ledger_detail(request): if request.method == 'POST': paginator = PageNumberPagination() paginator.page_size = 10 account = Account.objects.get(id=request.data['account']) transactions = account.transaction.filter( account=account, date_created__gte=request.data['start_date'], date_created__lte=request.data['end_date'], deleted=False ).order_by('date_created') result_page = paginator.paginate_queryset(transactions, request) serializer = TransactionSerializer(result_page, many=True) return paginator.get_paginated_response(serializer.data) and api generate below given data within a certain date range {"count":4,"next":null,"previous":null,"results":[{"id":5574,"account":"Cash","account_type":"0","transaction_type":"0","description":"Advance Unearned (Revenue)","amount":"1500.00","transaction_reference":null,"approved":true,"date_created":"2017-09-17T05:16:58Z","realized":false,"reference_id":"17090044","deleted":false,"deleted_by":null},{"id":5576,"account":"Cash","account_type":"0","transaction_type":"0","description":"Advance Unearned (Revenue)","amount":"100.00","transaction_reference":null,"approved":true,"date_created":"2017-09-17T05:18:18Z","realized":false,"reference_id":"17090044","deleted":false,"deleted_by":null},{"id":5593,"account":"Cash","account_type":"0","transaction_type":"0","description":"Room Sales Revenue","amount":"377.00","transaction_reference":null,"approved":true,"date_created":"2017-09-17T05:48:30Z","realized":false,"reference_id":"17090044","deleted":false,"deleted_by":null},{"id":5596,"account":"Cash","account_type":"0","transaction_type":"0","description":"Advance Unearned (Revenue)","amount":"3000.00","transaction_reference":null,"approved":true,"date_created":"2017-09-17T05:58:12Z","realized":false,"reference_id":"17090045","deleted":false,"deleted_by":null}]} and below is my jquery data table code which works fine if i remove pagination code part in my api <script type="text/javascript"> $(document).ready(function () { $("#question_form").off('submit').on('submit', function (e) { e.preventDefault(); var dtOption = { "columns": [ {"title": "Transaction Id", "data": "id"}, {"title": "Reference Id", "data": "reference_id"}, {"title": "Transaction Type", "data": "transaction_type"}, {"title": "Transaction Ref ID", "data": "transaction_reference"}, {"title": "Accounting Head", "data": "account"}, {"title": "description", "data": "description"}, {"title": "Amount", "data": "amount"}, {"title": "Balance", "data": "balance"}, {"title": "Date Created", "data": "date_created"} ], "destroy": true, "columnDefs": [ { render: function (data) { return (data == 0) ? "Debit" : "Credit" }, targets: 2 }, { targets: 8, render: function (data, a, b) { console.log(data); return moment(data).format('YYYY-MM-DD hh:mm A'); } } ] }; var table = $('#journal_list').DataTable(dtOption); … -
Changing Django login validation
I want to alter the login_required method but I do not get the method I have done, someone could help me, I try to validate because I have different types of users. Python 3.6.1 & Django 1.11 def login_dece(function): def _inner(request, *args, **kwargs): u = request.user actual_decorator = user_passes_test( u.is_authenticated and Dece.objects.filter(id=u.id).exists(), login_url=settings.LOGIN_URL, redirect_field_name=REDIRECT_FIELD_NAME ) if function: return actual_decorator(request, *args, **kwargs) return function(request, *args, **kwargs) return _inner url(r'^sgd$', login_dece(sys.sgd), name='sgd'), -
Django - get related objects
I have these models where one book can have many contents in different languages: class Book(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) class BookContent(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) book = models.ForeignKey(Book, on_delete=models.CASCADE) content = models.TextField() language = models.TextField() How should i fetch Book and its related BookContent? -
I am getting 'attribute error': 'module' object has no attribute 'split_stopwords' in django-python application
Please do not mark this question as 'duplicate'. I have tried all other solutions but still I am getting this error. Hello friends, I am developing a sms spam checker web application using django-python in Pycharm. I am getting 'attribute error'. When I run this program on Terminal it's working fine, but when I run this program on pycharm I am getting this error. Can anyone answer to this ? SmsSpamCheck.py file import nltk from nltk.corpus import stopwords from nltk.tokenize import wordpunct_tokenize import cPickle import csv import os import pandas as pd from django.shortcuts import render from sklearn.cross_validation import StratifiedKFold, train_test_split from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.grid_search import GridSearchCV from sklearn.metrics import classification_report, confusion_matrix from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import Pipeline from sklearn.svm import SVC from textblob import TextBlob from spamchecker.models import TextEntry # add path to NLTK file #STOP = set(stopwords.words('english')) nltk.data.path.append('nltk_data') # load stopwords stopwords = set(stopwords.words('english')) SPAMMESSAGES = pd.read_csv('/home/gaurav/PycharmProjects/spamchecker/spamchecker/SMSSpamCollection', sep='\t',quoting=csv.QUOTE_NONE, names=["label", "message"]) # Preprocessing def split_tokens(message): message = unicode(message, 'utf8') return TextBlob(message).words def split_lemmas(message): message = unicode(message, 'utf8').lower() words = TextBlob(message).words return [word.lemma for word in words] def split_stopwords(message): message = unicode(message, 'utf8').lower() words = TextBlob(message).words return [word.lemma for word in words if word not … -
flow based visualization - drag and drop elements for workflow with ports and nodes
Can web apps like the below ( Azure ML studio ) be created if using flask/django with Python.