Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
If template variable is null, hide it's nesting html element
Here's my template: <li><a href="/{{ user_settings.room2 }}" id="room2">/{{ user_settings.room2 }}</a></li> <li><a href="/{{ user_settings.room3 }}" id="room3">/{{ user_settings.room3 }}</a></li> <li><a href="/{{ user_settings.room4 }}" id="room4">/{{ user_settings.room4 }}</a></li> If the value of {{ user_settings.room2 }} is null, hide its <li> parent. If the value of {{ user_settings.room3 }} is null, hide its <li> parent. What is an efficient way this can be done? -
Django Model.objects.create() DB exception doesn't filter up
I'm trying to test constraint validation in Django with a py.test unit test by creating a child object for which the parent does not exist. @pytest.mark.django_db def test_child_with_missing_parent(): with pytest.raises(django.db.utils.IntegrityError): Child.objects.create(parent_id=1337) The exception is thrown, but can't be caught -- it just shows in stderr. I'm using pytest.mark.xfail for now, but it is effectively just a "skip" -- 1 xfailed, 1 xpassed is the result. How could I catch such an error in an expected scenario like this? -
ImportError: cannot import name 'AdminPasswordChangeForm'
any chance to find out what could be the problem? Django version: 2.0.2. Appears after: Error appears after attempt to define my own custom user model, when I deleted my custom profiles app and went back to default, the error is now present. Appears: When trying to makemigrations or simply runserver, I get the following error. C:\myprojects\morpheum1\master>python manage.py makemigrations . Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\stani\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\stani\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Users\stani\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\stani\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 120, in populate app_config.ready() File "C:\Users\stani\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready self.module.autodiscover() File "C:\Users\stani\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\stani\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\stani\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\stani\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\admin.py", line 6, in <module> from django.contrib.auth.forms import ( ImportError: cannot import name 'AdminPasswordChangeForm' In django.contrib.auth.admin class I have everything set as … -
Form not showing with {% csrf_token %} {{ cart_product_form }} Django
So I am trying to show a dropdown menu with django 2.something (latest version) for an ecommerce site that allows you to select the quantity of an item before adding to cart but the quantity form is not showing. I have a shop app and a cart app and the form is in the cart app. Here is what it looks like: No quantity drop down menu is showing how do i get it to show? html <form action="{% url "cart:cart_add" product.id %}" method="post"> {% csrf_token %} {{ cart_product_form }} <input type="submit" value="add to cart" class="btn btn-primary"> </form> shop views.py from django.shortcuts import render, get_object_or_404 from .models import Category, Product from cart.forms import CartAddProductForm from django.template import RequestContext def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = Product.objects.filter(category=category) context = { 'category': category, 'categories': categories, 'products': products } return render(request, 'shop/product/list.html', context) def product_detail(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) cart_product_form = CartAddProductForm() context = { 'product': product, 'cart_product_form': cart_product_form } return render(request, 'shop/product/detail.html', context) shop urls.py from django.conf.urls import re_path from . import views app_name = 'shop' urlpatterns = [ re_path(r'^$', views.product_list, name='product_list'), re_path(r'^(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_by_category'), … -
Unit test for Django Model
hello i am new to Django and Python programming. Currently i am trying build a simple Blog site in Django. I have completed most of the task over here. And now i want to perform Unit testing. So, i want to write Unit test for Djngo. Can you please help me to write unit testing for Django. # custom model manager class PublishManager(models.Manager): def get_queryset(self): return super(PublishManager, self).get_queryset() \ .filter(status='published') \ .order_by('-created') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'published'), ) title = models.CharField(max_length=200) author = models.ForeignKey("auth.User", related_name='blog_post') body = models.TextField() photo = models.ImageField(blank=True, null=True) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') # meta information class Meta: ordering = ('-publish',) # order by publish date # creating object of manager object = models.Manager() published = PublishManager() # used as custom manager # string representation def __str__(self): return self.title class Comment(models.Model): post_id = models.ForeignKey('Post', related_name='post_comment', on_delete=CASCADE) name = models.CharField(max_length=200) email = models.EmailField(blank=True, null=True) comment_body = models.TextField() def __str__(self): return self.name class Profile(models.Model): name = models.OneToOneField(User, on_delete=CASCADE) # this field is required email = models.EmailField(blank=True, null=True) address = models.CharField(max_length=50) phone = models.CharField(max_length=30) image = models.ImageField(blank=True, null=True) def __str__(self): return 'Profile of user: {}'.format(self.name.username) def … -
Django migration not calling overridden save() method?
I have a model SessionCategory which is similar to the following: from django.db import models from django.utils.text import slugify class SessionCategory(models.Model): name = models.CharField(max_length=255, unique=True) name_slug = models.CharField(max_length=255, null=True) def save(self, *args, **kwargs): if not self.name_slug: self.name_slug = slugify(self.name) super().save(*args, **kwargs) So the name_slug field, which I'd like to add, is a slugified version of the name field. I've run the following data migration: from __future__ import unicode_literals from django.db import migrations, models def generate_name_slugs(apps, schema_editor): SessionType = apps.get_model('lucy_web', 'SessionType') for session_type in SessionType.objects.all(): session_type.save() class Migration(migrations.Migration): dependencies = [ ('lucy_web', '0163_auto_20180627_1309'), ] operations = [ migrations.AddField( model_name='sessioncategory', name='name_slug', field=models.CharField(max_length=255, null=True), ), migrations.RunPython( generate_name_slugs, reverse_code=migrations.RunPython.noop), ] However, if I check the database afterward, the name_slug fields are all null: I've also reversed the migration and re-run it setting a trace (import ipdb; ipdb.set_trace()) in the overridden save() method, but it didn't cause Python to drop into the debugger, confirming that that method is not called. Why is the overridden save() method not getting called? Do I have to replicate the code in the generate_name_slugs function? -
Django shell script definition error
I have a file test.py with this code: def getTrue(): return True def getSome(): return getTrue() somevar = getSome() print(somevar) When I run the script using python manage.py shell < test.py I get the error: NameError: name 'getTrue' is not defined After adding import unicodedata to the top of the file and then try using some function from unicodedata I get this error: NameError: name 'unicodedata' is not defined When I run the file normally with python3 /path/to/file/test.py there is no problem and True is printed like expected. Any idea what is going on? -
override rest-auth UserDetailsSerializer
I am struggling with overriding UserDetailsSerializer. It shows me that 'User' object has no attribute 'UserProfile'. I have tried many methods but the update function seems incorrect and it blocks the process. class UserProfile(serializers.ModelSerializer): class Meta(object): """Meta options.""" model = UserModel fields = ( 'model_pic', 'address', 'city', 'country', ) class UserSerializer(UserDetailsSerializer): ss = UserProfile(required=False) class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ('ss',) def update(self, instance, validated_data): profile_data = validated_data.pop('ss') profile_image = profile_data.get('profile_image') address = profile_data.get('address') city = profile_data.get('city') country = profile_data.get('country') instance = super(UserSerializer, self).update(instance, validated_data) # get and update user profile profile = instance.profile_data if profile_data: if profile_image: profile.profile_image = profile_image if address: profile.address = address if city: profile.city = city if country: profile.country = country profile.save() return instance model.py class UserModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=1) model_pic = models.ImageField(upload_to = 'media/', default = '400.jpg') address = models.CharField(max_length=255, default='') city = models.CharField(max_length=155, default='') country = models.CharField(max_length=155, default='') def __str__(self): return self.user.username -
Problems with nginx configuration for a django website?
I am running django on my local machine and wanted to redirect nginx request to my local ip to my django urls. But for some reason nothing is working. location / { proxy_pass http://localhost:3000; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; # Enables WS support proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; } location /category { proxy_pass http://localhost:3000/tests/category; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; # Enables WS support proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; } But for some reason I keep getting a 404 . My goal is lets says my server ip is 1.1.1.1 and I have my dns mapped to this ip as http://www.etc.com So, when i enter http://www.etc.com/, it should route to django localhost:3000/ When i enter http://www.etc.com/category, it should route to django localhost:3000/tests/category How can i do that ? What am i missing out? I am really confused -
Can you skip a record on bulk import when a duplicate record shows up?
I'm diving into some code written by others and I'm running into a duplicate record issue. I understand why the duplicate issue is popping up (I added the unique_together constraint). This code below is wrapped with the @transaction.atomic decorator so if any part fails it rolls back. I want to have the serializer is_valid() function skip over the duplicates, just move on, and not raise the ValidationError. How can I do this and is this the best practice? The code makes use of the Django Rest Framework serializers and validators. serializer_class = globals().get(table + 'Serializer') if serializer_class is None: raise SerializerNotFound(table) serializer = serializer_class(data=data, many=True) serializer.is_valid(raise_exception=True) serializer.save() I also added this code to the Serializer class: class Meta: model = CoolModelName validators = [ validators.UniqueTogetherValidator( queryset=CoolModelName.objects.all(), fields=('field', 'list', 'names', 'here') ) ] -
Django url pattern string
I would like to make a lists page with item such as /lists and have items such as /lists/node-js The url pattern I'm using is this - url(r'^lists/(?P<foo>[\w\-]+)/$', views.lists_template, name='lists_template'), but due to this /lists does not work and shows a page not found error.How do I solve this? -
r'^$' in url.py causing routes in emails to not work
So this has been the urls.py the last several months I have been working on this application: from django.conf.urls import url, include from django.contrib import admin from django.views.generic.base import TemplateView from home.views import GetHomeAPIView urlpatterns = [ # Admin URL url(r'^admin', admin.site.urls), # API authentication entry point url(r'^api/auth/', include('authentication.urls', namespace='signin')), # API /home entry point url(r'^api/home/', GetHomeAPIView.as_view(), name='home'), # API entry point for documents url(r'^api/report/(?P<report_id>[0-9]+)/', include('documents.urls', namespace='documents')), # API entry point for results url(r'^api/report/(?P<report_id>[0-9]+)/', include('results.urls', namespace='results')), # API /contact entry point url(r'^api/contact/', include('contact.urls', namespace='contact')), # API /users entry point url(r'^api/users/', include('users.urls', namespace='users')), # Any requets that come through serve the index.html url(r'', TemplateView.as_view(template_name='index.html')), ] That was for the dev environment. Pretty much what should be happening is url(r'', TemplateView.as_view(template_name='index.html')), should catch all traffic so that routing can be done on the FE with react-router-dom. The other API routes are only called when the FE sends a request to them. Now I'm trying to setup for production and running into all kinds of issues. First, I kept getting an Uncaught SyntaxError: Unexpected token < error. Asked about it here on SO and the: url(r'', TemplateView.as_view(template_name='index.html')), Was causing it. I modified it to: url(r'^$', TemplateView.as_view(template_name='index.html')), And the web application is functioning for … -
Django designing wallet
I am designing a free credits system for my app. Let's say a user has free credits balance upto INR 10000. Now he opens my website in 2 different machines(laptops). On machine1, he is going to purchase an item worth 11000 and in other he is going to purchase another item say 12000. Both the machines will show credit balance of 10000. The system goes to third party for payment and then returns with success or failure. When should I reduce the free credits or more importantly how should I design my system to avoid race conditions -
Django REST Framework - submitting with jQuery returns missing required fields
My code is trying to send JSON data to a Django REST Framework endpoint I created. The funny thing is, when trying to do it through jQuery, I get a 400 error, telling me there are empty required fields. But if I open the endpoint URL and paste the same JSON data in the Browsable API form, I get a status 200. This is the Javascript part that sends the data: jQuery.ajax({ type: 'PUT', dataType: 'json', data: put_json, beforeSend:function(xhr) { xhr.setRequestHeader("X-CSRFToken", jQuery("[name='csrfmiddlewaretoken']").val()); }, error: function(xhr, status, error) { var err = JSON.parse(xhr.responseText); console.log(err); }, url: "https://myasb.asbarcelona.com/afterschool/api/v1/registration/" + registration_id + "/" And this is the data I'm trying to send: {"id":"314","username":"fleon","parentname":"Fidel","parentlast":"Xxx Yyy","parentmail":"fleon@xxxxxxxxx.com","parentphone":"0000000","parentphone2":"000000","studentactivities":[{"id":13963,"schedule":["X"],"activity":9,"student":4662}]} This is the view that processes the request: class RegistrationMainDetail(generics.RetrieveUpdateAPIView): queryset = RegistrationMain.objects.all() serializer_class = RegistrationMainSerializer permission_classes = (permissions.IsAuthenticated, IsParent, IsOwner) and this is the RegistrationMainSerializer (which is "work in progress" and not complete): class RegistrationMainSerializer(serializers.ModelSerializer): studentactivities = RegistrationActivitySerializer(many=True, read_only=False) class Meta: model = RegistrationMain fields = ('id', 'username', 'registrationdate', 'parentname', 'parentlast', 'parentmail', 'parentphone', 'parentphone2', 'is_proposal', 'studentactivities') def create(self, validated_data): registration_activities_data = validated_data.pop('studentactivities') registration_main = RegistrationMain.objects.create(**validated_data) for registration_activity_data in registration_activities_data: RegistrationActivity.objects.create(parent=registration_main, **registration_activity_data) return registration_main def update(self, instance, validated_data): # Not finished registration_activities_data = validated_data.pop('studentactivities') registration_main = instance for registration_activity_data … -
Update a file Django
I have the code to upload a file into a specific directory but when I want to update it, the file is not copy it, I want to store the updated file in the root that i put and change it in django, I can change it in django but it not uploaded to my media_root this is my code to upload def generate_path(instance, filename): section=instance.title.historical_set.last().id_section year=str(section.year.number) course=(section.course.name) section=str(section.number) course=course.encode('utf-8').decode('utf-8') return os.path.join(year,course,section,filename) class UseExistingStorage(FileSystemStorage): def save(self,name, content, max_length=None): if not self.exists(name): return super(UseExistingStorage, self).save(name, content, max_length) return name models.py class File(models.Model): title=models.ForeignKey(Document,on_delete=models.CASCADE,null=True) file = models.FileField(null=True,blank=True, upload_to=generate_path,storage=UseExistingStorage()) How can i make that the updated file is storage in the same path when I upload a file? -
i am getting all users data instead of getting single user in django rest framework token base auth
at the right side, u can see i am getting all users instead of getting only one how can i solve this issue with Django token-based authentication system m using simple json web tokens from git hub how can i use it to have the current user only or at least payload the token REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', )} -
Django 1.7 ContentType vs apps
I'm using django 1.7 and i want to know the difference between using ContentType.objects.get(app_label="app_name", model="model_name") versus apps.get_model('doctors' 'Doctor'). Do they both grab the same information from the model? what are the benefits of using apps.get_model? -
Don't show home page in the navigation menu on Django CMS
I have a Django CMS site, and I want to display every page in the navigation menu, except for the home page, because it'll have a separate link elsewhere. How can I do it? The pages I have are separated, no subpages or stuff like that. And I'm currently displaying the menu using the show_menu tag. Thanks. -
how to override the .create() method inside a generic view (example: ListCreateAPIView) in django-rest-framework?
I wanted to override the create method in class-based view which implements the ListCreateAPIView , not generally while overriding methods like the get_queryset(self) method, the requests, the url **kwargs are accessed from self, but I wanted to override the .create() method of the CreateModelMixin, so I took a look at the code to find the signature as create(self, request, *args, **kwargs) what does django pass in the **kwargs, *args of this function? are these url **kwargs by any chance? How do I go about overriding the create method in the generic view asthe request in any function of the generic view is accessed from the self but the signature of the create function explicitly requires a request argument. -
dJango query duplicated items excluding the first
I tried to do the migration in dJango to rename all the duplicated name in database and set the name field to be unique. I have read the question here: Django select only rows with duplicate field values and wrote the same code. My code is: # Find all the duplicated items name duplicate_names = Image.objects.values('name').annotate(Count('id')).order_by().filter(id__count__gt=1) # Find the duplicated objects by their name duplicate_objects = Image.objects.filter(name__in=[item['name'] for item in duplicate_names]) # Change each duplicated name for duplicated in duplicate_objects: duplicated.name = duplicated.name + '-' + str(duplicated.id) duplicated.save() This works great and fast, but it renames all the replicated items. I want to keep one of them with the original name. I tried: # Find all the duplicated items name duplicate_names = Image.objects.values('name').annotate(Count('id')).order_by().filter(id__count__gt=1) for item in duplicate_names: # Find the duplicated objects by their name exclude the first duplicate_objects = Image.objects.filter(name__in=[item['name']])[1:] for duplicated in duplicate_objects: duplicated.name = duplicated.name + '-' + str(duplicated.id) duplicated.save() It works but fairly slow. Is there a way to query the duplicated items and exclude one of the duplicated item without nested loop? -
Django InconsistentMigrationHistory: Migration X is applied before its dependency Y on database 'default'
This question is similar to Django manage.py: Migration applied before its dependency and django.db.migrations.exceptions.InconsistentMigrationHistory, except that I haven't squashed migrations; I also find the answers to those questions not very specific. I have an app lucy_web for which python manage.py showmigrations yields lucy_web [X] 0001_initial [X] 0002_auto_20170614_2116 [X] 0003_auto_20170614_2139 [X] 0004_auto_20170614_2228 [X] 0005_auto_20170614_2329 [X] 0006_auto_20170615_2326 [X] 0007_auto_20170616_1827 [X] 0008_family_birth_parent [X] 0009_auto_20170621_2035 [X] 0010_family_account_holder [X] 0011_auto_20170621_2218 [X] 0012_auto_20170621_2219 [X] 0006_auto_20170616_0008 [X] 0007_auto_20170616_0016 [X] 0008_auto_20170616_0441 [X] 0009_merge_20170619_1835 [X] 0013_merge_20170621_2225 [X] 0010_auto_20170621_0101 [X] 0014_merge_20170626_1858 [X] 0010_family_user [X] 0014_merge_20170623_1748 [X] 0015_merge_20170627_0605 [X] 0016_auto_20170710_1447 [X] 0017_auto_20170710_1448 [X] 0018_session_expert_type [X] 0019_auto_20170726_1641 [X] 0020_auto_20170727_1457 [X] 0021_auto_20170727_1511 [X] 0022_auto_20170727_1518 [X] 0023_auto_20170728_1300 [X] 0024_auto_20170730_0939 [X] 0025_auto_20170730_1011 [X] 0026_auto_20170731_1433 [X] 0027_auto_20170731_2117 [X] 0026_category [X] 0028_merge_20170801_0732 [X] 0029_auto_20170801_0736 [X] 0030_family_lucy_guide [X] 0031_family_baby_name [X] 0032_auto_20170801_2215 [X] 0033_auto_20170801_2218 [X] 0034_auto_20170801_2230 [X] 0035_remove_expert_activation_date [X] 0035_category_inactive [X] 0036_merge_20170802_1543 [X] 0037_auto_20170802_1544 [X] 0038_auto_20170803_2127 [X] 0039_family_profile_link [X] 0040_family_account_holder_string [X] 0041_auto_20170808_0825 [X] 0024_expertsessiontype_packagesessiontype [X] 0042_merge_20170808_1302 [X] 0043_auto_20170808_1311 [X] 0044_auto_20170809_0750 [X] 0045_auto_20170809_1119 [X] 0046_auto_20170810_1159 [X] 0047_auto_20170811_0851 [X] 0048_auto_20170811_0851 [X] 0049_auto_20170811_0857 [X] 0050_auto_20170816_0821 [X] 0051_auto_20170817_1358 [X] 0052_auto_20170823_1317 [X] 0053_auto_20170831_1415 [X] 0054_session_requested_timeframe [X] 0055_userapn [X] 0055_auto_20170919_1103 [X] 0056_merge_20170920_1206 [X] 0057_auto_20171003_1506 [X] 0058_auto_20171016_2025 [X] 0059_auto_20171017_1233 [X] 0060_auto_20171017_1448 [X] 0061_notification [X] 0062_auto_20171019_1322 [X] 0063_family_tz_string [X] 0064_auto_20171019_1357 [X] 0065_auto_20171023_2251 [X] 0066_auto_20171027_1512 [X] 0067_auto_20171108_1719 [X] … -
403 response Ionic 4 + Django Api rest on the same server?
I built an Ionic 4 App which uses Django API REST endpoints. The app has been tested on iPad and on my localhost using ionic-app-scripts serve. Now I want to deploy it as a webapp, and I'm doing this by building for the browser platform (ionic cordova build browser --prod --release) and serving the index.html on the same Django App in which the API REST is on. Static files (js, assets, etc, are hosted on an Amazon S3 Bucket) Now both on iPad and localhost I have no problems with the API REST POST requests. But when I run the app on the live server (even if the request is being sent from the same server than the API REST!!) I get 403... The only difference I see when I compare the request Headers is that the one sent on the live server does not have an "Origin" parameter: ON LIVE SERVER: Accept application/json, text/plain, */* Accept-Encoding gzip, deflate Accept-Language en-US,en;q=0.5 Cache-Control no-cache Connection keep-alive Content-Length 62 content-type application/json Cookie _ga=GA1.2.1002502516.149305462…eay6lysy1w44vawa94lug20hpek2n Host example.com Pragma no-cache Referer http://example.com/front/ User-Agent Mozilla/5.0 (Macintosh; Intel …) Gecko/20100101 Firefox/60.0 ON LOCALHOST: Accept application/json, text/plain, */* Accept-Encoding gzip, deflate Accept-Language en-US,en;q=0.5 Connection keep-alive Content-Length 62 content-type … -
Django ORM: computed field
I've got a model in Django ORM, which is used for storing kinda Item-like objects. They have a price and a discount. I want a field on a model, e.g. price_with_discount which would use a simple expression (e.g. price * (1 - discount / 100). What I currently have is class Item(models.Model): objects = ItemManager() price = models.DecimalField(...) discount = models.DecimalField(...) And in the manager's get_queryset def get_queryset(self): qs = super().get_queryset() qs = qs.annotate( price_with_discount=Case( When(discount=None, then=F('price')), default=F('price') * (1 - F('discount') / 100), output_field=DecimalField(max_digits=20, decimal_places=2) ) ) This gives the behaviour when I query directly for Items, but in Django REST framework's serializers, when I invoke the serializer directly on a related field of some other model (e.g. shop, which has many items), ItemSerializer raises an exception AttributeError: Got AttributeError when attempting to get a value for field price_with_discount on serializer ItemSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Item instance. Original exception text was: 'Item' object has no attribute 'price_with_discount'. I have tried used a custom related manager, annotating the queryset class Item(...): class Meta: base_manager_name = 'ItemRelatedManager' # both this one and the next line base_manager_name = 'related_manager' … -
View example for djangorestframework-csv?
I'm not clear on how a view should render a csv to json automatically, do I have to use models? -
Register form won't work
I created a register form which has worked great, allowing me to create users and sign in with them. Recently, I have been trying to implement email verification before signing up a user to the system. I've been using SendGrid to send the emails, and a token to activate the user. The form hasn't been saving, redirecting the user to the activation page, or even sending the email. I can't figure out what's wrong. Any help would be appreciated! views.py def parent_sign_up(request): if request.method == 'POST': form = ParentSignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your account.' message = render_to_string('acc_active_email.html', { 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() else: form = ParentSignUpForm() form = ParentSignUpForm() context = {'form' : form} return render(request, 'accounts/parent_sign_up.html', context) def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return redirect('home') return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') settings.py EMAIL_USE_TLS = True EMAIL_HOST …