Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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', … -
DRF:Updating particular fields in database
I have created an api to create users. But now I require to update their information based on their id.(I want to create a new api for this task). So I wrote the following: views.py class ProfileView(APIView): permission_classes = (AllowAny,) serializer_class = ProfileSerializer def update(self, request, *args, **kwargs): instance = self.get_object() instance.branch = request.data.get("branch") instance.year = request.data.get("year") instance.save() serializer = self.get_serializer(instance) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Account In my model I have fields as username, email, branch, year, full name. If at time of registration user fills few fields and after some time he gets to fill other fields(branch, year). How do I make it possible -
Why aren't the images of an inlineformset_factory being saved?
I have two models: Profile and CredentialImage. I am trying to allow each Profile to upload, optionally, up to 5 maximum images(CredentialImage). I've decided to use an inlineformset_factory for the images because on the UpdateView users will be given the option of updating their general Profile information as well as their 5 select images. The code goes without error, but the images do not save to the database. Here are the two models: class Profile(models.Model): ... def get_absolute_url(self): return reverse("profile:profile_detail", kwargs={"username": self.user}) class CredentialImage(models.Model): profile = models.ForeignKey(Profile, default=None) image = models.ImageField(upload_to=credential_photo_upload_loc) The modelforms + initialization of the inlineformset_factory: from django.forms.models import inlineformset_factory class ProfileUpdateForm(ModelForm): class Meta: model = Profile fields = [ "introduction", "biography", ] class CredentialImageForm(ModelForm): image = ImageField() class Meta: model = CredentialImage fields = ['image', ] CredentialImageFormSet = inlineformset_factory(Profile, CredentialImage, fields=('image', ), extra=4) A class-based UpdateView for updating a Profile: class ProfileUpdateView(LoginRequiredMixin, UpdateView): form_class = ProfileUpdateForm template_name = 'profile/profile_edit.html' def get_context_data(self, **kwargs): context = super(ProfileUpdateView, self).get_context_data(**kwargs) if self.request.POST: context['credential_image'] = CredentialImageFormSet(self.request.POST) else: context['credential_image'] = CredentialImageFormSet() return context def get_object(self, *args, **kwargs): user_profile = self.kwargs.get('username') obj = get_object_or_404(Profile, user__username=user_profile) return obj def form_valid(self, form): data = self.get_context_data() formset = data['credential_image'] if formset.is_valid(): self.object = form.save() formset.instance = self.object … -
Does django-fsm call save() method after state changed?
I am using django_fsm to manage state in my model. My model looks like: from django.db import models, from django_fsm import FSMField, transition class MyModel(models.Model): STATES = ( ('pending', _('Pending')), ('active', _('Active')) ) state = FSMField(choices=STATES, default='pending', protected=True) @transition(field=state, source='pending', target='active') def change_state(self): pass Should I add self.save() to change_state? Will it be called? -
Django query using datetime flter
In my (Post) model I have published = models.DateField(null=True) My urls include the year/month/day eg /post/category-1/2017/11/06/some-post/ which I am capturing through kwargs in my urls.py In my view my query is model = Post.objects.get(slug=kwargs['slug'],published__year=kwargs['year'], published__month=kwargs['month'],published__day=kwargs['day']) However, this is not working. The only date element which works is for year. I've read some posts here which talk about unsetting USE_TZ in settings.py which is obviously not a solution. I have tried using a DateTime field as well, but that makes no difference. Any help much appreciated. -
How to filter csv file?
I have csv file which have random data But I want to filter data from file. I want filter row which have data with starts $ and end with # 2017-09-07 03:11:03,5,hello 2017-09-07 03:11:16,6,yellow 2017-09-07 03:11:22,28,some other stuff with spaces 2017-09-08 20:24:36,157, 2017-10-28 04:39:25,54,$SITE0011,1654,0000,0000,0000,00000000,000000^A^A^A^A^A^A^@^@# 2017-10-28 04:39:48,108,$SITE0011,1654,0000,0000,0000,00000000,000000^A^A^A^A^A^A^@^@#$SITE0011,1654,0000,0000,0000,00000000,000000^A^A^A^A^A^A^@^@# 2017-10-28 04:40:26,54,$SITE0011,1654,0000,0000,0000,00000000,000000^A^A^A^A^A^A^@^@# 2017-10-28 04:40:29,54,$SITE0011,1654,0000,0000,0000,00000000,000000^A^A^A^A^A^A^@^@# -
django.db.utils.IntegrityError: column submittedby_id is not unique
I am having a hard time getting around this error. This is how my model looks like right now. class trendingideas(models.Model): submit = models.CharField(max_length=10) iname = models.CharField(max_length=15, unique = True) idea = models.TextField(unique = True) support = models.PositiveSmallIntegerField() submittedon = models.DateTimeField() readbyadmin = models.BooleanField() feasibilitycheck = models.BooleanField() def __str_(self): return str(self.iname) class trendingidea_admin(admin.ModelAdmin): list_display = ('submit','iname','idea','support','submittedon','readbyadmin','feasibilitycheck') submit defined above was before defined as: submittedby = models.ForeignKey(User) I made some changes and now no matter what i do, I keep getting the error: return self.cursor.execute(sql, params) File "/usr/lib64/python3.4/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: column submittedby_id is not unique. if I do inspectdb i see the poblematic column(stale entry) class HomeTrendingidea(models.Model): id = models.IntegerField(primary_key=True) # AutoField? iname = models.CharField(unique=True, max_length=15) idea = models.TextField(unique=True) submittedon = models.DateField() support = models.PositiveSmallIntegerField() readbyadmin = models.BooleanField() feasibilitycheck = models.BooleanField() submittedby = models.ForeignKey(AuthUser, models.DO_NOTHING) assignedto = models.ForeignKey(AuthUser, models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'home_trendingidea' How can i get it working back? thank you in advance. -
Django Post.objects.all() does not show object
Hi I'm learning Django based on the Django girls tutorial. I'm stuck in chapter 9 when I am trying to display all of my Post objects in the python shell. from blog.models import Post Post.objects.all() It should display [<Post: Title>, <Post: Title2>] but instead it displays [<Post: Post object>, <Post: Post object>] I was trying to find the solution for this but all say may be the cause of the error is in the models.py. I checked my blog\models.py and it seems to be good. It contains __str__ method with the indentation. I'm using Python 3.6.0 and Dajngo 1.11.6. Please help me My blog/models.py is the following from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() 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.title -
Django UpdateView doesn't get the values of the object and get blank instead
So I'm creating a django website and I have an Edit Button. The edit shows a pop up with a few forms to edit. The problem is that the forms to edit are blank! instead of having the previous data. e.g- ServerName="Yossi" When I click edit instead of having "Yossi" in the form I have nothing. What do I need to add to the index.html or the Class of PostEdit so I will have the previous data in the forms and not blank forms? models.py - from django.db import models # Create your models here. class serverlist(models.Model): ServerName = models.CharField(max_length = 30) Owner = models.CharField(max_length = 50) Project = models.CharField(max_length = 30) Description = models.CharField(max_length = 255) IP = models.CharField(max_length = 30) ILO = models.CharField(max_length = 30) Rack = models.CharField(max_length = 30) Status = models.CharField(max_length = 30) #date = models.DateTimeField(auto_now=True) views.py - # Create your views here. from django.shortcuts import render_to_response from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView from DevOpsWeb.forms import HomeForm from DevOpsWeb.models import serverlist from django.core.urlresolvers import reverse_lazy from simple_search import search_filter from django.db.models import Q class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = … -
Display specific table field (blog text) using Django
Hopefully a simple one, but I can't find what's wrong myself. I have a simple blog app, and I can display the posts titles, in a weird format, but can't pull through the posts body/text - all I get is a blank row. /models.py from django.db import models from django.utils import timezone class Post(models.Model): title = models.CharField(max_length=200) body = models.TextField() pub_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title /views.py from django.shortcuts import render from .models import Post def index(request): posting = Post.objects.filter() context = { 'posting':posting, } return render(request, 'posts/index.html', context) /templates/posts/index.html <li>{{posting}}</li> <li>{{posting.body}}</li> <li>test text</li> The output to the page is similar to (apologies not exact due to html formatting, but note blank middle line) : QuerySet [Post: First Post>, Post: Second Post>, Post: Third Post>]> test text Thank you. -
Testing django with jquery on the page for empty select fields?
I have been using the following test for the django admin and it has been working really well. Recently I added django-smart-selects to the project and the chained selects do not have options and are empty. def test_invalid_duration_entry(self): '''Ensure error if duration is greater than 24''' response = self.app.get( reverse('admin:entries_entry_add'), user=self.super_user ) form = response.form form['date'] = '2017-11-03' form['project'] = self.project.id form['user'] = self.user.id form['task'] = self.task.id form['duration'] = '24.25' response = form.submit() self.assertEqual( response.status_code, 200 ) self.assertFormError( response, 'adminform', 'duration', 'Ensure this value is less than or equal to 24.' ) When I inspect the value is empty: ipdb> form.get('user') <Select name="user" id="id_user"> ipdb> form.get('user').options [] ipdb> form['user'] = self.user.id *** ValueError: Option 14 not found (from ) jquery is adding the options when the project field is changed. How can I test this now. -
CORE issue for specific type of url .AJAX [duplicate]
This question already has an answer here: Why does my JavaScript get a “No 'Access-Control-Allow-Origin' header is present on the requested resource” error when Postman does not? 31 answers While making ajax call I am getting below error . Get request to "http://*****/api/profile/2" is not working , however a GET request to "http://*****/api/profile/" is working fine(The diff is adding 2 at last" . My web api server is configured to handle CORE . Failed to load http://*****/api/profile/2: Redirect from 'http://*****/api/profile/2' to 'http://*****/api/profile/2' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. Code: $.ajax({ type: 'GET', url: 'http://*****/api/profile/2', success: function(profiles){ $.each(profiles,function(i,profile){ Alert("Success"); }); }, -
Django: DateTimeField taking UTC format only, not others
The time that is being inserted in database is default UTC, not the timezone based time..I do not understand why is this happening, even though I am particularly specifying, in the query, the time that I want to be inserted. In my Model I have class leave(models.Model): date_created = models.DateTimeField(auto_now_add=True) In my settings I have TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True In my views i am setting timezone based on employee country 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') And then I am creating leave and updating timezone based on country 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=datetime.now(tzone)) new_leave.save() Thanks in Advance.