Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: ForeignKey selected Data Query in Form
I am working with automated result system app.I have five models class in models.py file. class Student(models.Model): std_name=models.CharField('Student Name ', max_length=200) CLASS_NAME=( ('6','SIX'), ('7','SEVEN'), ('8','Eight'), ('9','Nine'), ('10','Ten'), ('Ex-10','EX-Ten'), ) std_class_name=models.CharField('Class Name', max_length=7, choices=CLASS_NAME) std_roll_number=models.IntegerField('Roll Number') GENDER=( ('Male','Male'), ('Female','Female'), ) std_gender=models.CharField('Gender', max_length=7, choices=GENDER) GROUP=( ('Science','Science Group'), ('B.Studies','Business Group'), ('Arts and Humatics','Arts and Humatics'), ('General','General'), ) std_group=models.CharField('Group', max_length=17, choices=GROUP) pub_date = models.DateTimeField('Published', auto_now_add=True) std_total_subject=models.IntegerField('Total Subject', default=0) def __str__(self): return self.std_name class ExaminationName(models.Model): examination_name=models.CharField('Examination Name ', max_length=100) exam_date=models.DateTimeField('Exam Date: ') pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.examination_name class MainSubject(models.Model): main_subject_name = models.CharField('Main Subject Name', max_length=100) main_subject_code=models.DecimalField('Main Subject Code', decimal_places=0, default=0, max_digits=10) subject_full_marks = models.DecimalField('Subject Full Marks', max_digits=6, decimal_places=0, default=100) pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.main_subject_name class SubjectName(models.Model): mainsubject = models.ForeignKey(MainSubject, on_delete=models.CASCADE) subject_name=models.CharField('Subject Name', max_length=100) subject_full_marks=models.DecimalField('Subject Full Marks',max_digits=6, decimal_places=0, default=100) pub_date = models.DateTimeField('Published', auto_now_add=True) subject_gpa_point=models.DecimalField('GPA in Subject',max_digits=4, decimal_places=2, default=0) subject_gpa_grade=models.CharField('GPA Grade',max_length=5, default='F') def __str__(self): return self.subject_name class SubjectPart(models.Model): mainsubject = models.ForeignKey(MainSubject, on_delete=models.CASCADE) subjectname = models.ForeignKey(SubjectName, on_delete=models.CASCADE) subject_part_name=models.CharField('Subject Part', max_length=100) subject_part_full_marks = models.DecimalField('Full Marks', max_digits=6, decimal_places=0, default=100) subject_part_pass_marks = models.DecimalField('Pass Marks', max_digits=6, decimal_places=0, default=100) pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.subject_part_name class AddResult(models.Model): student=models.ForeignKey(Student, on_delete=models.CASCADE) examinationname = models.ForeignKey(ExaminationName, on_delete=models.CASCADE) mainsubject_name = models.ForeignKey(MainSubject, on_delete=models.CASCADE) subjectname = models.ForeignKey(SubjectName, on_delete=models.CASCADE) subjectpart = models.ForeignKey(SubjectPart, on_delete=models.CASCADE) … -
no such command django-admin.py
I have installed Django 2.0 with CMD by using py setup.py install (Note py not python) To get that command to work I had to add Python35 to the environment variables as it was saying python is not a command. C:\Users\Ryan\Desktop\django_test>py -c "import django; print(django.get_version())" 2.0 Im not able to run django-admin.py (or django-admin) I have to use the absolute file path or put it in the current folder. When I do this it returns Type 'django-admin.py help <subcommand>' for help on a specific subcommand. Available subcommands: [django] #list of commands Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.). The command I am trying to run is django-admin.py startproject myproject I have also added django-admin the the environment variables but no luck. -
Manipulating request.FILES in django POST
I have a file upload view in django. I have a model form. In POST method request.FILES contains all the files. I want to do some extra work on the uploaded files in request.FILES. I saved the files locally and do some extra work. But I can not assign the files in request.FILES. I made a dictionary like - data_dict = { 'a_file': open(tmp_dir + "/a_repro.a", 'r'), 'b_file': open(tmp_dir + "/b_repro.b", 'r'), 'c_file': open(tmp_dir + "/c_repro.c", 'r'), 'd_file': open(tmp_dir + "/d_repro.d", 'r'), } But I can not assign like - form = MyUploadForm(request.POST, data_dict) or, request.FILES = data_dict But it does not work. How can I do it? -
django restframework token Authentication fail with "invalid token"
I have a problem with token authentication. I run my django app with django built in server. $python manage.py runserver My App's urls.py from rest_framework_jwt.views import obtain_jwt_token from .views import LectureCreateView urlpatterns = [ ... url(r'^api/user_auth/$', obtain_jwt_token), url(r'^api/lecture/create/$', LectureCreateView.as_view()), ] My App's models.py from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated class LectureStartView(APIView): permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication,) def post(self, request): ... and settings.py ... INSTALLED_APPS = [ ... # Rest framework 'rest_framework', 'rest_framework.authtoken', 'myApp', ] ... REST_FRAMEWORK = { # other settings... 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } I want auth with token. I successfully issued token. POST '...api/user_auth/' { "username": "test", "password": "blahbalh123" } { "token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjIwMTMyMzA2Iiwib3JpZ19pYXQiOjE1MDk5NzA5NjcsInVzZXJfaWQiOjMsImVtYWlsIjoiaW50ZXJydXBpbmdAbmF2ZXIuY29tIiwiZXhwIjoxNTA5OTcxNTY3fQ.acwqAP4sBPZWYPC0GfgL3AZarNz4Opb_5P4RewZJYrI" } but I fail Auth with Token Request: POST ...api/lecture/create/ HTTP/1.1 Host: 127.0.0.1:8000 Authorization: Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjIwMTMyMzA2Iiwib3JpZ19pYXQiOjE1MDk5NzA5NjcsInVzZXJfaWQiOjMsImVtYWlsIjoiaW50ZXJydXBpbmdAbmF2ZXIuY29tIiwiZXhwIjoxNTA5OTcxNTY3fQ.acwqAP4sBPZWYPC0GfgL3AZarNz4Opb_5P4RewZJYrI Response: Status: 401 Unauthorized Allow →GET, POST, HEAD, OPTIONS Content-Length →27 Content-Type →application/json Date →Mon, 06 Nov 2017 12:59:17 GMT Server →WSGIServer/0.1 Python/2.7.13 Vary →Accept WWW-Authenticate →Token X-Frame-Options →SAMEORIGIN { "detail": "Invalid token." } What's wrong with my code? sorry for my english skill. -
Create django File object from online url
So I want to save some images to my django models through the shell, with the added twist that the said images would come from an online resource, a url. As per the requests documentation I can get the file to disk thus: import requests img = requests.get("image_url", stream=True) with open("name.jpg", "wb") as fd: for chunk in img.iter_content(chunk_size=128): fd.write(chunk) I could write the file to disk, then convert to a django file object like so from django.core.files import File img = File(open(choice(IMAGES), "rb")) But I need a way to bypass the read and write to/from disk while still ending up with the django File object. I've tried io.BytesIO and io.StringIO but each time I end up with an exception. -
Django viewset call serlizerer
I am trying to call serlizerer to save object from viewset This is views.py class GroupViewSet(viewsets.ViewSet): .... @detail_route(methods=['post'], url_path='task') def get_task(self, request, pk=None): group = get_object_or_404(Group, pk=pk) data = {"group": group } log_serializer = LogSerializer(data=data) if log_serializer.is_valid(raise_exception=True): log_serializer.save() This is serializer.py class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('id', 'name') class LogSerializer(serializers.ModelSerializer): group = GroupSerializer() class Meta: model = Log fields = ('group', 'created') The post responese; { "group": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got group." ] } } -
Simple Boolean decorator from a model attribute
I have extended the user profile , and i would like to have a decorator @isaffiliate which can be used if the affiliate attribute is set to TRUE . I userprofile models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) affiliate = models.BooleanField(default=False) -
Validation error failed to display in template
Validation error failed to display in template and shows source code in other environment which uses Apache via mod_wsgi and has DEBUG=False. The same code works fine in local environment . Please help. Thank you. {% if form.errors %} <h4>Please fix the following errors</h4> <ul> {% for field in form %} {% if field.errors %} {% for error in field.errors %} <li><a href="#id_{{ field.name }}" >For {{ field.name }} {{ error|escape }}</a></li> {% endfor %} {% endif %} {% endfor %} </ul> {% if form.non_field_errors %} {{ form.non_field_errors }} {% endif %} {% endif %} -
How to use IN CONDITION in django Aggregation
How can't using IN condition (example: SELECT SUM(a) FROM b WHERE a IN (1, 2, 3)) by using Django Aggregation. Example: result = qs.aggregate( amount = SUM(Case(WHEN('a IN(1, 2, 3)', then=Value(a)), default=0)) ) -
How to use Django jchart
I am new to Django and there are a lot of things I have to learn. I started a project to learn while coding. As a part of the project I want to use jcharts. I want just to follow the guide here. In this step, I have to add some code for backend part, but I do Not know where that should be added. Is it in views.py, or apps.py, anywhere else? The guide talks about chart.py. Where should it be put exactly? -
Receiving parameters with APIView
I have this routing: url(r'^article/(?P<article_id>\d+)/', views.ArticleList.as_view()) which leads to this function: class RSSList(APIView): def get(self, request, *args, **kwargs): article_id = kwargs.get('article_id') But when I try to query something like /article/34 I get this error: TypeError: get() got an unexpected keyword argument 'article_id' How can I pass article_id to get()? Thank you -
DRF jwt unable login with provided credential
i have a DRF application, which using django-rest-framework-jwt for token based authentication. here is my setting.py : INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework.authtoken', 'corsheaders', ] REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAUALT_AUTHENTICATION_CLASS': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } and when i create a new user like below: def post(self, request, format=None): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and in my urls : url('^login/', obtain_jwt_token), which user model is coming from django auth user model. but whene i request to api-token-auth following error happen: { "non_field_errors": [ "Unable to log in with provided credentials." ] } -
Django REST Framework; Problems serializing User model with 'groups' field
I'm trying to add a REST framework to my existing project. However, whenever I add 'groups' to the fields in my UserSerializer class, I get this traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/api/users/ Django Version: 1.10.7 Python Version: 3.6.3 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'blended_learning_portal.users.apps.UsersConfig', 'blended_learning_portal.taskapp.celery.CeleryConfig', 'blended_learning_portal.unit.apps.UnitConfig', 'blended_learning_portal.data.apps.DataConfig', 'debug_toolbar', 'django_extensions', 'graphos', 'ckeditor', 'ckeditor_uploader', 'webpack_loader', 'rest_framework'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback: File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/relations.py" in to_representation 378. url = self.get_url(value, self.view_name, request, format) File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/relations.py" in get_url 316. return self.reverse(view_name, kwargs=kwargs, request=request, format=format) File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/reverse.py" in reverse 50. url = _reverse(viewname, args, kwargs, request, format, **extra) File "/home/michael/blportal/lib/python3.6/site-packages/rest_framework/reverse.py" in _reverse 63. url = django_reverse(viewname, args=args, kwargs=kwargs, **extra) File "/home/michael/blportal/lib/python3.6/site-packages/django/urls/base.py" in reverse 91. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "/home/michael/blportal/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix 392. (lookup_view_s, args, kwargs, len(patterns), patterns) During handling of the above exception (Reverse for 'group-detail' with arguments '()' and keyword arguments '{'pk': 2}' not found. 0 pattern(s) tried: []), another exception occurred: File "/home/michael/blportal/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 42. response = get_response(request) File "/home/michael/blportal/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/michael/blportal/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/michael/blportal/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return … -
Django ModelAdmin - custom name of items in drop down list
I want to change a names of items (users) in drop down list in Django Admin Model. I want to do it without any changes in basic models. I just want to field 'user'(admin.py) refers to 'user' in Worker model(office.py) through username (just without Firstname and Lastname) admin.py from .models import Token class TokenAdmin(admin.ModelAdmin): model = Token fieldsets = ( (None, { 'fields': ('name', 'key', 'user') }), models.py from office.models import Worker class Token(models.Model): user = models.ForeignKey( Worker, related_name='auth_token', verbose_name=_("api.models.token.user") ) office.py class Worker(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_("User")) firstname = models.CharField( _("Firstname"), blank=False, null=False, max_length=50) lastname = models.CharField( _("Lastname"), blank=False, null=False, max_length=50) def __str__(self): return "%s %s" % (self.lastname, self.firstname) -
Single model dynamic database settings in Django
For example assume that I have 100 clients who uses WordPress and I have to write a service in Django which should return list of posts from WordPress's MySQL DB. The problem is 100 clients are having different database connection settings. I know that I can use DatabaseRouter to switch databases which are already loaded in settings. But I don't know how to make a singe model class to use different database settings. I have tried mutating settings. I also tried mutating model's app_label. But I later understood that mutating anyting in Django is meaning less. My Requirements I want to create a model and dynamically change database connection. List of connection can be in a managed database table. But I don't want to unnecessarily load all the connection settings or create multiple models. -
UpdateView restrict to current user
Hello everyone I new to django and trying to make a page where a user can edit their profile. I've managed to make that happen, but the problem I have is that anyone can edit whatever profile they like. What is the way to check if the current request.user is the same that will edit the model user? This is my view: class UpdateProfile(UpdateView): model = User form_class = MemberProfileForm template_name = 'home/member_profile_update.html' slug_field = 'username' slug_url_kwarg = 'slug' Forms: class MemberProfileForm(ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'bio') def save(self, user=None): user_profile = super(MemberProfileForm, self).save(commit=False) if user: user_profile.user = user user_profile.save() return user_profile I am extending the User Model like this: class User(AbstractUser): bio = models.TextField(max_length=500, blank=True) phone = models.CharField(max_length=30, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) www = models.TextField(max_length=60, blank=True) twitter = models.TextField(max_length=30, blank=True) facebook = models.TextField(max_length=30, blank=True) google = models.TextField(max_length=30, blank=True) My URL looks like this: url(r'^members/update/(?P<slug>[\-\w]+)/$', views.UpdateProfile.as_view(), name='update_user'), If you can redirect me to some guides or documentation for my case it will be awesome. -
How to retain user input on a regular form in Django?
It was my intention to use a Django form as a data filter, at present there are 3 filters: Label, Platform, and Category. The problem I am running into is that I cannot for the life of me retain the data after submission. Meaning that if I filter on Platform 1 and Platform 2, after submission it will revert back to all platforms (the default setting). I have found some similar questions where a ModelForm is used, but considering my data, a ModelForm is not suitable. My (simplified) code: # forms class PlatformsFilter(forms.Form): Platforms = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple() Categories = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple() Labels = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple() # views def platforms(request) platformfilter = PlatformsFilter() if request.method == 'POST': Platforms = Platform.objects.filter(id__in=request.POST.getlist('Platforms')) platformfilter = PlatformsFilter(request.POST) ## Some minor computations based on data context = {'platformfilter': platformfilter} return render(request, 'analytics/platforms.html', context) # template <form action="" method="POST"> {% for field in platformfilter %} <div class="someattribtues"> {{field}} </div> {% endfor %} <input class="btn btn-block btn-primary" type="submit" name="apply_filters" value="Filter" /> </form> -
Comparing a database field with date
I'm trying to compare a field with an actual date but I am stuck with this error "'Certificate' object is not subscriptable" if datetime.datetime.strptime(c.certificate['date_certified'], '%Y-%m-%d').date() >= datetime.date('2016-01-01'): Can anyone tell me where am I going wrong and the possible solution for it? -
Count on multiple fields in Django querysets
I have a model representing a transaction between two users, like this: class Transaction(models.Model): buyer = models.ForeignKey(User) seller = models.ForeignKey(User) product = models.ForeignKey(Product) I would like to get the number of transactions for each user (either as a buyer or a seller). If a I want to count on only one field, I can just do : Transaction.objects.values('seller').annotate(Count('seller')) but I can't manage to do it on two fields at the same time in 1 query. Is there a way to do that ? Thanks -
Django models ForeignKey return IDs
I have been trying to search forums to get an answer for this, but it seems like its a bit tricky to search. I have the following model which is pulling users from django User table: class trendingidea(models.Model): iname = models.CharField(unique=True, max_length=15) idea = models.TextField(unique=True) submittedon = models.DateTimeField() support = models.PositiveSmallIntegerField() readbyadmin = models.BooleanField() feasibilitycheck = models.BooleanField() submittedby = models.ForeignKey(User,related_name="submitted_by") assignedto = models.ForeignKey(User, blank=True, null=True, related_name="assignedto") However when i query the database and pull the information: ti=list(trendingidea.objects.values()) print(ti) [{'readbyadmin': False, 'id': 1, 'idea': 'cisco', 'feasibilitycheck': True, 'submittedby_id': 1, 'support': 1, 'submittedon': datetime.datetime(2017, 11, 6, 11, 8, 10, tzinfo=<UTC>), 'iname': 'cisoc', 'assignedto_id': 1}] in place of submittedby and assignedto it gives me submittedby_id': 1 and assignedto_id': 1. I wanted the usernames and not their IDs. is there a way to achieve this? -
How to add base64 image data as attachment?
I want to create email via EmailMultiAlternatives but I have image data as base64 - from POST data. And I want to send it as attachment via email. For now I have (view): ctx = { 'username': request.user.username, 'img': request.POST['image'] } subject, from_email, to = 'Hello', 'mailfrom@server', 'mailto@server' text_content = 'text only' html_content = render_to_string('visemail.html', ctx) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() template: <img src="{{ img }}" /> But I get email with text: <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB.... I do not see the picture in content. So I want to send this image as attachment maybe. How to do this? -
How to show form in UpdateView on Django?
I want to make Update page which change User of model information. My program is berow. #urls.py url(r'^user_edit/(?P<pk>\d+)$', views.UserEdit.as_view(), name='user_edit'), #models.py from datetime import datetime from django.db import models from django.utils import timezone from django.contrib.auth.models import User class User(User): name = models.CharField(max_length=200, default='Null') post = models.CharField(max_length=9, default='Null') bank = models.CharField(max_length=200, default='Null') mail = models.CharField(max_length=200, default='Null') address1 = models.CharField(max_length=200, default='Null') address2 = models.CharField(max_length=200, default='Null') address3 = models.CharField(max_length=200, default='Null') tel = models.CharField(max_length=15, default='Null') fax = models.CharField(max_length=15, default='Null') #views.py class UserEdit(generic.UpdateView): model = User form_class = UserForm template_name = 'invo/user.html' success_url = "invo/user_info" # get current user object def get_object(self, queryset=None): return self.request.user #user.html [Template] {% extends 'invo/base.html' %} {% block content %} <div class="gtco-section gtco-testimonial gtco-gray"> <div class="gtco-container"> <div class="row"> <div class="col-md-8 col-md-offset-2 gtco-heading text-center"> <h2>Update</h2> </div> </div> <div class="row"> <h3>User Profile</h3> <div class="row"> {% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} <form method="post"> {% csrf_token %} <table> {{ form.as_p }} </table> <input type="submit" value="change"> </form> </div> </div> </div> </div> <!-- END .gtco-services --> {% endblock%} My page is like this.It doesn't have forms This is html source code.There … -
Django different timezones in same application
I am working on a Django application on Leave Management, in which there are employees from different countries. I am storing the data of the time, when the leave is created, into DB. Now, I want this datetime that is being inserted into DB, to be the current local time of the location where that particular employee is working at. For example, let us suppose Mr. X is working at India and Y is working at Newyork. If X applies for a leave, I want it to be created at local time (created_at= what-so-ever time it is in India) and when Y applies for a leave, I want it to be created_at=what-so-ever time it is in Newyork. As of now, whatever I am inserting into DB, it is getting inserted as UTC time only. How to resolve this issue? I am trying to achieve something like this.. But it is always UTC. userid = employees.objects.get(emp_id=request.user.username) if employees.objects.get(emp_id=request.user.username).emp_loc == 'IND': tzone=pytz.timezone('Asia/Calcutta') elif employees.objects.get(emp_id=request.user.username).emp_loc == 'MLA': tzone=pytz.timezone('Asia/Manila') elif employees.objects.get(emp_id=request.user.username).emp_loc == 'MPLS': tzone=pytz.timezone('CST6CDT') timezone.activate(pytz.timezone(tzone)) tnow=timezone.localtime(timezone.now()) if request.POST['action'] == 'Save changes': new_leave = leave.objects.create(employee=employees.objects.get(emp_id = userid.emp_id), start_date=sdt, end_date=edt, ltype=ltyp, message=des, date_created=tnow) new_leave.save() Badly in need of help..... :( Thanks in advance......... :) -
django TestCase is raising NotImplementedError
I have the below test case from rest_framework.test import APIClient from django.test import TestCase from factories import UserFactory class TestUserApi(TestCase): def setUp(self): # Create or get model factory objects self.users = UserFactory() self.client = APIClient() def test_user_list(self): response = self.client.get('/api/1/users/') self.assertEqual(response.status_code, status.HTTP_200_OK) def tearDown(self): pass When I run the above test case I am getting the below error which I don't understand why? ERROR: test_user_list (test_cases.TestUserApi) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py", line 178, in __call__ self._pre_setup() File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py", line 749, in _pre_setup self._fixture_setup() File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py", line 861, in _fixture_setup if not connections_support_transactions(): File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py", line 848, in connections_support_transactions for conn in connections.all()) File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py", line 848, in <genexpr> for conn in connections.all()) File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 49, in __get__ res = instance.__dict__[self.func.__name__] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 676, in supports_transactions self.connection.leave_transaction_management() File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 324, in leave_transaction_management if managed == self.get_autocommit(): File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 331, in get_autocommit self.ensure_connection() File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 127, in ensure_connection self.connect() File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 114, in connect conn_params = self.get_connection_params() File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 86, in get_connection_params raise NotImplementedError NotImplementedError: EDIT DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'integration_tests', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '192.16x.xx.x', 'PORT': '3306', }, } -
Django REST API's for models with Foreignkey's
I want to Build an API with DRF to View the shopping cart. It works in the non API version but I get an error in the serializer that fields do not exist in the model. models.py class Product(models.Model): title = models.CharField(max_length=50, blank=False) cover_image = models.ImageField(upload_to='products/') summary = models.TextField() description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.title class Cart(models.Model): user = models.ForeignKey(User) active = models.BooleanField(default=True) order_date = models.DateField(null=True) def __str__(self): return self.user.username class Order(models.Model): product = models.ForeignKey(Product) cart = models.ForeignKey(Cart) quantity = models.IntegerField(default=1) def __str__(self): return self.product.title views.py def cartview(request): if request.user.is_authenticated(): cart = Cart.objects.filter(user=request.user, active=True) orders = Order.objects.filter(cart=cart) total = 0 count = 0 for order in orders: total += (order.product.price * order.quantity) count += order.quantity context = { 'total': total, 'cart': orders, 'count': count, } return render(request, 'store/cart.html', context) else: return redirect('index:index') api/views.py class CartAPIView(ListAPIView): permission_classes = [IsAuthenticated] serializer_class = CartSerializer def get_queryset(self, **kwargs): cart = Cart.objects.filter(user=self.request.user, active=True) orders = Order.objects.filter(cart=cart) total = 0 count = 0 for order in orders: total += (order.product.price * order.quantity) count += order.quantity context = { 'total': total, 'cart': orders, 'count': count, } return context serializers.py class CartSerializer(ModelSerializer): class Meta: model = Cart fields = [ 'title', 'cover_image', 'summary', …