Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using save() in Django model produces TypeError
*****Working with Django 1.11.x and Python 3.6***** I'm trying to learn how to use the save() method in a Django model (models.py). There are two fields here that I want to become custom, 'calculated' fields (unique_id and age). First I initiate the field variables, then define methods/properties based on existing fields, then I try to save the method results into the fields that I created. from django.db import models from dateutil.relativedelta import relativedelta from datetime import datetime class Person(models.Model): unique_id = models.CharField(max_length=6, primary_key=True) age = models.IntegerField() last_name = models.CharField(max_length=25) birth_date = models.DateField() city_of_birth = models.CharField(max_length=25) @property def get_unique_id(self): a = self.last_name[:2].upper() #First 2 letters of last name b = self.birth_date.strftime('%d') #Day of the month as string c = self.city_of_birth[:2].upper() #First 2 letters of city return a + b + c @property def get_age(self): return relativedelta(self.birth_date.days, datetime.date.now()).years def save(self, *args, **kwarg): self.unique_id = self.get_unique_id() self.age = self.get_age() super(Person, self).save(*args, **kwarg) def __str__(self): return self.unique_id First, I create 5 fields. 2 of them are placeholders: unique_id and age. Then I define two @property methods and each return a different type of result. The "get_unique_id" function works, but I can't get the result stored in the database. The "get_age" function may or may … -
many-one field of foreign key Django
My timesheet.html will have the variables of ID, name, startDate and endDate. I wish to display all these fields in a table in list_timesheet.html. But i have a problem of displaying the same ID and same name several times with different start and end date. Does anyone has any idea on what i should do on my models.py ? models.py #consists of all the details in the timesheet class Timesheet(models.Model): studentID = models.CharField("Student ID", max_length=8, primary_key=True, default="") studentName = models.CharField("Student Name", max_length=500, default="") startDate = models.DateField("Start Date", max_length=8) endDate = models.DateField("End Date", max_length=8) def __str__(self): return self.studentID #consists of all the details of the timesheet under 'View Timesheets' class LTimesheet(models.Model): timesheet = models.OneToManyField(Timesheet, on_delete=models.CASCADE, primary_key=True) status = models.CharField("Status", max_length=100) -
ElasticBeanstalk: Environment in an unhealthy state(Codeship Pro, Jets)
I am trying to deploy a django app using Codeship Pro to Elasticbeans talk(using docker of course). Running this step fails when when deploying codeship-steps.yml: - name: deployment tag: aws-docker service: awsdeployment command: codeship_aws eb_deploy ./deploy my-project staging my-bucket docker-compose.yml services: app:... db:... awsdeployment: image: codeship/aws-deployment encrypted_env_file: aws-deployment.env.encrypted environment: - AWS_DEFAULT_REGION=eu-central-1 volumes: - ./:/deploy Error: Info: I am trying to setup a CI/CD environment for the project(staging/production env) -
Get pk of foreign key from object when rendering detail view
Im trying to get the id of the foreign key relationship to perform to filter through a list of models. However Im getting an error that states: 'ForwardManyToOneDescriptor' object has no attribute 'id'. Is this the right way to go about this problem or am I missing something in my understanding of how all this works? I created a detail view from this model: class Collection(models.Model): title = models.CharField(max_length=32, null=True) slug = models.SlugField(unique=True, blank=True) category = models.ForeignKey(Category) @models.permalink def get_absolute_url(self): return ('collection_detail', (), { 'slug' :self.slug, }) def __unicode__(self): return u'%s %s ' % (self.category.id, self.title ) This is the code from the detail view: class collection_detail(DetailView): model = Collection def get_context_data(self, **kwargs): context = super(collection_detail, self).get_context_data(**kwargs) a = self.category.id context['collection_list'] = Product.objects.filter(categories=a).order_by('id') return context -
How can we have Foreign Key to a Model Mixin?
I have a mixin named CommentMixin Now i want to have it's Foreign Key in Answer model to have multiple Comments. Any example or source would also be appreciated. -
How to input phone numbers without the leading +1
In the PhoneNumber field for django, how do you allow users to input phone numbers without the leading +1 in the beginning? -
How to create Django API without any framework
Currently I am having a requirement for a project, in which I need to develop django API without using any frameworks. So inorder to proceed I would like to know how can I do creation of API without framework -
A special model for general permissions only
Django==1.11.2 I have three user groups: commentators, contributors, observers. So far I'm going to check only whether a user can comment, contribute or observe. Those who don't have a permission even to observe will not be able to see anything. I'm going to use PermissionRequiredMixin in each of my views. Well, so far only three general permissions. And they are really general: they are not connected to any model in particular but to all my models. I have written a special model whose only purpose is to organize permissions. And I perform migrations. class PermissionsModel(models.Model): class Meta: permissions = (("can_observe", "Can observe"), ("can_comment", "Can comment"), ("can_contribute", "Can contribute"),) Then I have created a special django-admin command that creates the three groups and assigns permissions to them. Well, the result is satisfactory. What troubles me is whether this way is clumsy or not. Could you tell me whether this is acceptable. And if it is not, what is the better way? -
Django Rest Framework, updating nested serialized data
I'm new to using the Django Rest Framework and serialized data, I'm trying to update a nested serializer but ran into a wall, I've looked around but most people have problems in the serializers.py side while I can't even get into def update without an error, these are my classes: Views.py from django.shortcuts import render from rest_framework import generics from api.serializers import ProfileSerializer from django.contrib.auth.models import User from api.models import Profile from django.http import JsonResponse class ProfileView(generics.ListCreateAPIView): def get(self, request): profile = Profile.objects.filter(user_id=request.user.id) serializer = ProfileSerializer(profile, many=True) return JsonResponse(serializer.data, safe=False) def post(self, request, *args, **kwargs): profile = Profile.objects.filter(user_id=request.user.id) data = request.POST serializer = ProfileSerializer(profile, data=data, partial=True) if serializer.is_valid(): serializer.save() else: print(serializer.errors) return JsonResponse(serializer.data, safe=False) Serializers.py from rest_framework import serializers from django.contrib.auth.models import User from api.models import Profile class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','username','first_name','last_name','email','last_login','date_joined','is_active') class ProfileSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Profile fields = ('id','phone','birth_date','user') def update(self, instance, validated_data): #Cant get here print("hey") return instance Sample structure [ { "id": 3, "phone": "XXXXXX", "birth_date": "2017-06-29", "user": { "id": 1, "username": "xxxxx", "first_name": "XXXXX", "last_name": "XXXX", "email": "xxxxxxx@gmail.com", "last_login": "2017-06-29T15:16:11.438818Z", "date_joined": "2017-06-23T16:48:38Z", "is_active": true } } ] My current error: (Post Data: phone = 0000000) AttributeError … -
Instanciate inside the template view instead inside the function
I'd like to instanciated req from this method inside the template view where it is used. @staff_member_required @csrf_exempt def ajax_send(request, req=None, folder_id=None): folder = Folder.objects.get(pk=folder_id) request_folders = folder.all_files.all() context = [] for doc in request_folders: if hasattr(doc.meta.state, 'rejected'): context.append(doc) if not context: ctx = {'request': req} EmailFromTemplate('document-refusal', extra_context=ctx)\ .send_to(req.customer.user) In the urls.py, I have # -*- coding: utf-8 -*- from django.conf.urls import url from django.contrib.auth.decorators import login_required #, permission_required from loanwolf.documents.views import (UpdateMetaView, FileDeleteView, ajax_upload, ajax_select, ajax_send) app_name = 'documents' urlpatterns = [ ... url(r'^send/(?P<folder_id>[0-9]+)/$', ajax_send, name='ajax-send'), ] and the template is <a href="#" id="id_select_request_document" title="{% trans "Send email - rejected file(s)" %}" class="btn btn-icon select-button" data-turbolinks="false" data-save-label="{% trans "Ok" %}" data-close-label="{% trans "Cancel" %}" data-copy-to="{{ folder.pk }}" data-reload="true" data-url="{% url "documents:ajax-send" folder_id=object.customer.folder.pk %}"> <i class="material-icons">assignment_late</i> </a> So the question is... How could I instanciated req inside the template without needing to do it inside the function ajax_send? -
Django mail attachment is blank
I am trying to send a mail with an attachment using Django, the attached file is sent to the server from a user submitted form. My code is shown below form = RequestForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.info(request, '') subject = '' message = "" attachment = request.FILES['attachment'] mail = EmailMessage(subject, message, '', ['']) mail.attach(filename=attachment.name, mimetype=attachment.content_type, content=attachment.read()) mail.send() I am receiving the mail, but the attachment in the mail is blank, i.e it doesn't contain any content. What am I missing here? -
Django save data from forms to database
Hi i am relatively new to Django. I am currently trying to store values into database. Timesheet.html is basically my form and i have tried to do the validation but it doesn't work. I have searched everything i can but the data being filled out wont be saved into database. Is there anywhere to check that the checkbox has been ticked before user can submit it ? timesheet.html <form method="POST" onsubmit="return validation()" action=""> {% csrf_token %} <div class="content-wrapper"> <div class="sub-content"> <div> <p>Student ID: {{timesheet.studentID}}</p> <input id="sid" type="field" name="studentid"> </div> </div> <div class="sub-content"> <div> <p>Student Name: {{timesheet.studentName}}</p> <input id="sname" type="field" name="studentname"> </div> </div> <div class="sub-content"> <div> <p>Start Date: {{timesheet.startDate}}</p> <input id="sdate" type="date" name="startdate"> </div> </div> <div class="sub-content"> <div> <p>End Date: {{timesheet.endDate}}</p> <input id="edate" type="date" name="enddate"> </div> </div> </div> <div class="end-content"> <div class="center-align"> <div class="checklist"> <p>By checking this box I agree that I have satisfied all requirements to continue receiving my scholarship allowance.</p> <input id="agree" type="checkbox" name="checkbox" class="tick-att"> </div> <br> <div class="align-right"> <input type="submit" class="button" name="submit" value="submit" > </div> </div> </div> </form> models.py class Timesheet(models.Model): studentID = models.CharField("Student ID", max_length=8, primary_key=True, default="") studentName = models.CharField("Student Name", max_length=500, default="") startDate = models.DateField("Start Date", max_length=8) endDate = models.DateField("End Date", max_length=8) def __str__(self): return self.studentID … -
Best way to handle a django request that will take a long time to process
I have a single page app I'm building in Python and Django that requires a substantial processing time to execute some functions (20+ minutes). I'd like to user to be able to 'kick off' the process and then receive a notification when it is done (and possibly some progress updates as it executes). One option is to make a view and then make an ajax POST to that view... but that means they can't leave the page or navigate the rest of the site while the request executes. What is the best solution for something like this? -
Django ORM query | Calculate score from number of votes and days passed
I am currently working on a 9gag-like site, where users submit content, and then upvote/downvote the content. On the front page, I would like to show all articles, that were published no later that 5 days ago and have at least 2 votes. My UserArticle model has a published_at field(A DateTimeField), and I have a model called UserVote which stores the votes for the article. I have accomplished that with the following code: def article_index(request): time_threshold = timezone.now() - timedelta(days=5) articles =(UserArticle.objects.annotate(num_votes=Sum('uservote__value')) .filter(num_votes__gte=2, published_at__gte=time_threshold) .order_by('-num_votes') ) My only problem left is how the posts are sorted. It is currently sorted in descending order with the highest number of votes first. In addition to being sorted by the highest number of votes, I would like to penalize older articles by the factor of days since it was published. Something like: num_votes + age_in_days_since_publication*(-2) -
How to update modifications after a page reload on Docker?
I've got an issue using Docker, I'd like to update changes on my page whenever I change my css file instead of restarting all containers on docker. Whenever I save an HTML page the changes are made automatically but somehow whenever I change a static file things don't work as planned. I'm using Docker Toolbox on windows & Django. Docker-compose.yml : version: '2' services: nginx: restart: always image: nginx:latest container_name: NGINX ports: - "8000:8000" volumes: - ./src:/src - ./config/nginx:/etc/nginx/conf.d - /static:/static - /media:/media depends_on: - web web: restart: always build: . container_name: DJANGO command: bash -c "python manage.py collectstatic --noinput && python manage.py makemigrations && python manage.py migrate && gunicorn oqtor.wsgi -b 0.0.0.0:8000" depends_on: - db volumes: - ./src:/src - /static:/static - /media:/media expose: - "8000" db: image: postgres:latest container_name: PSQL Am I doing something incorrectly ? -
Internal Server Error when upgrading from django 1.9 to django 1.11
I have upgraded from django 1.9 to django 1.11. As I run python manage.py runserver after the upgrade I got an error due to the import of patterns. I realised it made sense, since patterns is depracted. So I changed my urls.py from if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if not settings.DEBUG: urlpatterns += patterns('', (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), ) to if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if not settings.DEBUG: urlpatterns = [ url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), ] By running python manage.py runserver it works just fine, but when pushing it to Heroku, the website shows and Internal Server Error. And I receive this message: Internal Server Error: / TypeError at / view must be a callable or a list/tuple in the case of include(). By just removing the if not settings.DEBUG part, the website from the server loads without Internal Server Error, but there is no CSS. Any idea of what is causing the error? -
Cannot import Vue from instance saved in another directory
I am learning to integrate Vue.js in to a Django project (multi-page application). My goal is to be able to split my frontend code up among my different apps within my project However, I am unable to create a Vue instance from my profiles app because webpack fails to find Vue during import. The error ERROR in ../apps/profiles/frontend/profiles/browse.js Module not found: Error: Can't resolve 'vue' in '/home/me/dev/myproject/apps/profiles/frontend/profiles' My django project structure (truncated) manage.py myproject/ webpack.config.js frontend/ home.js components/ Home.vue apps/ profiles/ frontend/ profiles/ browse.js Multiple entry points in webpack.config.js entry: { 'vendor': [ "vue", "vue-resource", ], 'home': [ './frontend/home.js', 'webpack/hot/only-dev-server', 'webpack-dev-server/client?http://' + dev_server_addr + ':' + dev_server_port, ], 'profiles_browse': [ '../apps/profiles/frontend/profiles/browse.js', 'webpack/hot/only-dev-server', 'webpack-dev-server/client?http://' + dev_server_addr + ':' + dev_server_port, ], }, Also vue is resolved as an alias in webpack.config.js resolve: { alias: { 'vue$': 'vue/dist/vue.common.js', }, }, My browse.js Vue instance import Vue from 'vue' <-- Error occurs here new Vue({ el: '#browse', data: { foobar: "hello browse" }, delimiters: [ "[[", "]]" ] }); And finally my django template for profiles browse <div id="browse"> [[ foobar ]] </div> {% render_bundle 'vendor' %} {% render_bundle 'profiles_browse' %} I had thought that since vue has an alias defined that I … -
rendor_to_response is not defined error in django
This is my views.py code. from __future__ import unicode_literals from django.template import RequestContext from django.shortcuts import render_to_response def index(request): context = RequestContext(request) context_dict = {'bold-message': "I am bold font from the context"} return render_to_response('rango/index.html', context_dict, context) After starting the project when I run this in server, I am getting the following exception. Global name 'rendor_to_response' is not defined Please tell what I did wrong. -
Storing runtime variables in Django models
I would like to store a runtime variable in the 'self' dictionnary of a Django model like in this pseudocode : class Account(models.Model): somefield = models.CharField(...) api = None def fetch_from_api(self): if not self.api: self.api = API() api.get_data() I want this variable to be bound to a model instance at runtime and not to be stored in database. How could I do so? -
Django. Ignore task from autodiscover_tasks OR or load tasks manually
Hello how can i achieve ignoring tasks from autodiscover_tasks OR load them manually in Django. This should be particularly useful if we have a python package full of tasks and we need to somehow ignore some of them. -
Passing parameters to view from submitted form
I'm trying to pass some parameters received from a submitted form (POST) to a ListView so that I can generate the relevant queryset based on those parameters. I'm not clear if the parameters should be specified in the URL in addition to the View? From current View: area = form.cleaned_data['area'] service = form.cleaned_data['service'] usage = form.cleaned_data['usage'] return redirect('users:results', area=area, service=service, usage=usage) urls.py url(r'^results/$', views.ResultsView.as_view(), {}, name="results", ), views.py class ResultsView(ListView): template_name = 'site/results.html' paginate_by = 20 context_object_name = 'results' def get_queryset(self, area, service, usage): results = Results.objects.filter(area=area, service=service, usage=usage) return results -
S3 storage for django app on EC2 not working correctly (subfolders missing)
I have deployed a django app to EC2 using elastic beanstalk. Now I want to use an S3 bucket as storage. I installed boto3 in the virtual environment, and django-storages. I added the following code to my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'autocomplete-light', 'storages', ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') AWS_STORAGE_BUCKET_NAME = 'BUCKET-NAME' AWS_ACCESS_KEY_ID = 'AWS-KEY-ID' AWS_SECRET_ACCESS_KEY = 'AWS-SECRET-ACCESS-KEY' AWS_S3_FILE_OVERWRITE = True AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME # the sub-directories of media and static files STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' # a custom storage file, so we can easily put static and media in one bucket STATICFILES_STORAGE = 'ebdjango.custom_storages.StaticStorage' DEFAULT_FILE_STORAGE = 'ebdjango.custom_storages.MediaStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) Where I changed BUCKET-NAME to the name of the s3 Bucket, that I have created. AWS-KEY-ID and AWS-SECRET-ACCESS-KEY are the security credentials of an AWS IAM User that I created. When I run collectstatic, django will put the files into a folder called ./static/. Into that folder I manually put my style.css. In the folder I have autocomplete-light and admin subfolders. When I deploy only these two folders are copied to the bucket, but not the style.css. I am new to … -
Displaying Django-Parler TranslatableModel ForeignKey field in Django Admin
Some context: I have a Django-Parler TranslatableModel called City. I have a non-translatable model called User. The User model has a ForeignKey field to City. The User Admin Form does not render any fields, only the submit buttons. City model: class City(TranslatableModel): translations = TranslatedFields( name=models.CharField(max_length=255, null=True, blank=True), slug=models.SlugField(max_length=255, unique=True), official_name=models.CharField(max_length=255, null=True, blank=True) ) User model: class User(AbstractUser): name = models.CharField(max_length=255, null=False, blank=False) city = models.ForeignKey(City, blank=True, null=True) User admin: @admin.register(User) class UserAdmin(admin.ModelAdmin): model = User list_display = ('name', 'email', 'city', 'interests') The code above renders a Django admin form with no fields, only the submit buttons and no errors or exceptions are thrown, making it very hard to track the source of the problem... The code below where I exclude the field 'city' from the admin, renders the form perfectly (without the city field, which I need to render): @admin.register(User) class UserAdmin(admin.ModelAdmin): model = User list_display = ('name', 'email', 'city', 'interests') exclude = ('city',) However, I need to display the 'city' field! How can I achieve this? My guess is that I need to use an admin inline to display the city field, but Django-Parler documentation is very unclear about this. Thank you in advance for your help! -
Field from a form disappearing on validation errors
I have an issue that I can seem to understand. I have a simple form for an update on a page where I want to check if the current user is the owner of the instance of the object of the form. I do something like this : {% if perms.core.change_training or user == form.instance.owner %} <button type="submit" name="_submit" class="waves-effect waves-light btn right"> <i class="material-icons right">done</i>{% trans 'Validate' %} </button> {% endif %} And my view is : class TrainingUpdate(IsTrainingOwnerOrViewerPermission, UpdateView): model = Training form_class = TrainingForm def get_success_url(self): messages.add_message(self.request, messages.INFO, _('Update done for ') + self.object.name) return reverse('to-list') The thing is whenever I have validation issues, the owner is set to None. When i do : {{ form.instance }} {{ form.instance.owner }} The instance is still set but the owner is showing "None", hence my button does not pop up, and I'm stuck. The owner field in the model is : owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True) And is of course set, since when I first put the page, the button does show up. What am I missing here? -
How to login into Graphene Django app using curl?
I downloaded django app which has regular django api. App is really big and I decided to implement django graphene module and to make more flexible api. I have a graphene view which allow sending requests and receiving responses. My problem is that I want to add authentication on graphene view, so every user needs to provide token or username and password to be able to fetch the records. I found some solution here: Adding LoginRequiredMixin in new view My problem is I can't login into django app using curl to execute some grapql query. What I tried so far: curl -u admin:password123 -X GET http://localhost:8003/graphql?query=query%7B%20types%20%7B%20edges%20%7B%20node%20%7B%20name%20%7D%20%7D%20%7D%20%7D using jwt_auth curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwidXNlcl9pZCI6MSwiZW1haWwiOiIiLCJleHAiOjE0OTg3NDA4OTR9.FvofAxyhvjTGNZBUUSRF1kmXfgTNja6U52NynLhBGeo" http://localhost:8003/graphql?query=query%7B%20types%20%7B%20edges%20%7B%20node%20%7B%20name%20%7D%20%7D%20%7D%20%7 default app way to login on existing api to my graphene view curl -H "Authorization: Token 2867936fff9d738ee5fc8a807c86a96e59ab648d" http://localhost:8003/graphql?query=query%7B%20types%20%7B%20edges%20%7B%20node%20%7B%20name%20%7D%20%7D%20%7D%20%7D