Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django UpdateView - can't see errors in second form
I have model UserProfile which has field: languages = models.ManyToManyField('profiles.Language', through='UserProfileLanguage') The through model: class UserProfileLanguage(models.Model): userprofile = models.ForeignKey('UserProfile', ) language = models.ForeignKey('Language') level = models.CharField(max_length=50, choices=settings.USERPROFILE_LANGUAGE_LEVEL_CHOICES) class Meta: unique_together = ('userprofile','language') I'm trying to create an "update profile" page. I figured out how to add formset and everything works correctly except errors. I don't see errors when there are in the formset (not the UserProfileForm). Do you know how to make it work? The problem is probably in the post method. class UserProfileUpdateView(LoginRequiredMixin, UpdateView, ): model = UserProfile form_class = UserProfileUpdateForm template_name = 'profiles/profile/userprofile_update.html' def get_object(self, queryset=None): if self.request.user.is_authenticated(): return self.request.user.userprofile def get_context_data(self, **kwargs): context = super(UserProfileUpdateView,self).get_context_data(**kwargs) context['language_formset'] = self._get_userprofile_language_formset() return context def _get_userprofile_language_formset(self,POST=None,FILES=None): Factory = inlineformset_factory(UserProfile,UserProfileLanguage,fields=('language','level')) formset = Factory(POST or None,FILES or None,instance=self.request.user.userprofile) return formset def get_success_url(self): return reverse('profiles:profile',args=(self.request.user.userprofile.slug,)) def post(self, request, *args, **kwargs): self.object = self.get_object() formset = self._get_userprofile_language_formset(POST=request.POST,FILES=request.FILES) if formset.is_valid(): formset.save() else: # WHAT TO DO return self.render_to_response(self.get_context_data(formset=formset)) return super(UserProfileUpdateView,self).post(request,*args,**kwargs) -
Wagtail/Django App not serving images using DEFAULT_FILE_STORAGE storage backend
I have a wagtail app and using this guide I've managed to serve static files from an S3 bucket. I am trying to do the same thing for media files, however, changing DEFAULT_FILE_STORAGE and MEDIA_URL seems to have no effect on where uploads are stored, or the URLs rendered by templates. These are the relevant config settings: AWS_STORAGE_BUCKET_NAME = 'bucket-name' AWS_S3_REGION_NAME = 'eu-west-1' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME MEDIAFILES_LOCATION = 'media' MEDIA_URL = STATIC_URL DEFAULT_FILE_STORAGE = 'home.custom_storages.MediaStorage' STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'home.custom_storages.StaticStorage' STATIC_URL = "https://%s/" % AWS_S3_CUSTOM_DOMAIN And custom_storages.py: from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): location = settings.MEDIAFILES_LOCATION Static files are rendered in the admin site with the S3 url, however images still have src=/media/images/... relative urls, and they are uploaded to the host's file system rather than S3. -
Django/Wagtail/taggit - Getting model specific tag list
I have seen this: Generating a unique list of Django-Taggit Tags in Wagtail; and the solutions there have generated a list of all stored tags, i.e. image, document, etc tags. I am trying to accomplish a similar goal. On a News Index Page, have a dropdown of the News Page Tags. I can't seem to get a list of tags that are only News Page Tags, currently this gives me a list of all tags in my site, including image and document tags. from django.template.response import TemplateResponse from modelcluster.fields import ParentalKey, ParentalManyToManyField from modelcluster.tags import ClusterTaggableManager from taggit.models import TaggedItemBase, Tag from core.models import Page class NewsPageTag(TaggedItemBase): content_object = ParentalKey('NewsPage', related_name='tagged_items') class NewsPage(Page): tags = ClusterTaggableManager(through=NewsPageTag, blank=True) class NewsIndexPage(Page): def serve(self, request, *args, **kwargs): context['tags'] = Tag.objects.all().distinct('taggit_taggeditem_items__tag') return TemplateResponse( request, self.get_template(request, *args, **kwargs), context ) I have also tried: from django.contrib.contenttypes.models import ContentType # ... def serve(self, request, *args, **kwargs): news_content_type = ContentType.objects.get_for_model(NewsPage) context['tags'] = Tag.objects.filter( taggit_taggeditem_items__content_type=news_content_type ) return TemplateResponse( request, self.get_template(request, *args, **kwargs), context ) which assigns context['tags'] an empty set My template: {% if tags.all.count %} {% for tag in tags.all %} <a class="dropdown-item" href="?tag={{ tag.id }}">{{ tag }}</a> {% endfor %} {% endif %} HELP! This feels … -
How to customize CSS with django-bootstrap3
Im working on a project in Django that I installed Django-bootstrap3 on. It seems to have installed successfully and is generally working...but I'm not sure how to customize the css with this setup. Can anyone help? -
Django ModelForm with ManyToMany intermediary table
My model UserProfile has field languages: languages = models.ManyToManyField('profiles.Language',through='UserProfileLanguage') Which uses UserProfileLanguage as intermediary table: class UserProfileLanguage(models.Model): userprofile = models.ForeignKey('UserProfile', ) language = models.ForeignKey('Language') level = models.CharField(max_length=50, choices=settings.USERPROFILE_LANGUAGE_LEVEL_CHOICES) class Meta: unique_together = ('userprofile','language') When I create a ModelForm with model UserProfile, it contains multiple choice field for model Language. I would like to force user to specify a level of the language. Is there a built in way or do I have to create formset and override save method? -
ValueError at /admin/login/ - dictionary update sequence element #0 has length 0; 2 is required
I have a django project that I haven't touched in about a month. I have comeback to see an error when trying to connect to any page for the app (including admin login page). The error is: ValueError at /admin/login/ dictionary update sequence element #0 has length 0; 2 is required Here is the full traceback: Environment: Request Method: GET Request URL: http://localhost:8000/admin/login/?next=/admin/ Django Version: 1.11.4 Python Version: 3.6.2 Installed Applications: ['ad_app.apps.AdAppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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'] Traceback: File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request) File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 215. response = response.render() File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\response.py" in render 107. self.content = self.rendered_content File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\response.py" in rendered_content 84. content = template.render(context, self._request) File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\backends\django.py" in render 66. return self.template.render(context) File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\base.py" in render 205. with context.bind_template(self): File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\contextlib.py" in __enter__ 81. return next(self.gen) File "C:\Users\James\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\context.py" in bind_template 263. updates.update(processor(self.request)) Exception Type: ValueError at /admin/login/ Exception Value: dictionary update sequence element #0 has length 0; 2 is required Here is my settings.py file: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - … -
Deploy Django-channels with Docker
I'm trying to move my application to Docker. I'm currently using fabric to deploying my Django app. I created a docker-compose file: version: '3' volumes: static-files: services: nginx: image: nginx:latest volumes: - ./deploy/conf/nginx.conf.template:/etc/nginx/conf.d/mysite.template - static-files:/app/static ports: - "80:80" environment: - NGINX_HOST='localhost' command: /bin/bash -c "envsubst '\$NGINX_HOST' < /etc/nginx/conf.d/mysite.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'" depends_on: - interface redis: image: redis:latest db: restart: always image: mdillon/postgis:9.5 environment: - POSTGRES_USER=production - POSTGRES_PASSWORD=production - POSTGRES_DB=production interface: restart: always build: . working_dir: /app/code/src command: ["../../../wait-for-db.sh", "db", "./interface-entrypoint.sh"] volumes: - static-files:/app/static environment: - DJANGO_SETTINGS_MODULE=restapi.settings.production_settings expose: - "8001" depends_on: - db - redis workerserver: restart: always build: . working_dir: /app/code/src command: ["./worker-entrypoint.sh"] environment: - DJANGO_SETTINGS_MODULE=restapi.settings.production_settings depends_on: - db - redis - interface This docker-compose works fine, I can connect to server and all. So my questions are: How can I use my existing database with Docker setup? I tried using volumes but I can't get it working.. How do you handle migrations and code changes with this setup? With fabric I only did migrate and only restarted workers with supervisor. Here every worker has it's own "code" in container. Would it make sense to somehow share code between containers and make separate container for migrations? … -
Perform subqueries for each day in range
I building a 'airbnb clone' app on Django. The app has a flexible price system. Each landlord-user can save arbitrary number of prices which differ by priority and date range. Here is how it looks like (most of the fields skipped for the sake of simplicity): class PriceBlock(models.Model): price = models.DecimalField() priority = models.CharField(choices=PRIORITY_CHOICES) start_date = models.DateField() end_date = models.DateField() class Flat(models.Model): prices = models.ManyToManyField(related_name='flats') For example User created 3 PriceBlock instances with date values in some random month. p1 - has priority 1, price 100$ and dates from 1 to 3 p2 - has priority 2, price 200$ and dates from 2 to 5 p3 - has priority 3, price 300$ and dates from 4 to 6 To calculate price for flat from 1 to 6 days on this month we need to calculate price of PriceBlock with higher priority on each day. The problem is - I need calculate price for each flat in the ListView of all flats. Here's how I do it: class FlatQueryset(models.QuerySet): ... def with_block_full_price(self, start, end): days = get_days(start, end) # function returns list of days nums prices = {} for num, day in enumerate(days): prices[f'price_{num}'] = Subquery( PriceBlock.objects.filter(flats=OuterRef('pk')) .filter(start_date__lte=day, end_date__gte=day) .order_by('-priority') .values('price')[:1], … -
templatetag: could not parse remainder
I'm greeted with the following error when attempting to follow a books example of templatetags with modification: django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '% get_list %' from '% get_list %' [17/Nov/2017 09:12:57] "GET /account/requestaccess/?report_id=88&report_id=89 HTTP/1.1" 500 180158 I'm following the instructions of adding templatetags to my app directory and included the init.py and the app_filter.py i'd like to filter on, as such: Security Accounts templatetags app_filter.py __init__.py My app_filter.py is defined as such: from django import template register = template.Library() @register.filter('accounts/requestaccess.html') def get_list(querydict, itemToGet ): return querydict.getlist(itemToGet) My settings.py includes the following: INSTALLED_APPS = [ 'django_python3_ldap', 'django_extensions', 'django_filters', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', ] TEMPLATE_LOADERS = ( 'django.template.loaders.app_directories.load_template_source', ) My view is passing the array correctly: checkedlist = request.GET.getlist('report_id') I see the array in my console, when doing a print checkedlist: ['75', '76', '77'] My template is the following: {% load app_filters %} {% for reports in retreivecheckbox %} <input type="checkbox" name="report_id" value ="{{reports.report_name_sc}}"> {{ % get_list % }} </div> {% endfor %} -
Adding data to related model (custom user model)
I have a custom User Model. I can successfully add user to it and want to add the relationship to a related model. It gives me no errors but does not link the user to the related field compusers in the company model. Basically I need it to after creating a user, also add the user to the related compusers field. This is the code I am trying in the view: self.object.compusers.add(self.object.id) The Model class Company(models.Model): user = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='compusers') name = models.CharField(max_length=265, blank=True) tel = models.IntegerField(blank=True, null=True) email = models.EmailField(max_length=265,blank=True) address = models.TextField(blank=True) postal = models.TextField(blank=True) regno = models.CharField(max_length=265,blank=True) vatno = models.CharField(max_length=265,blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('nodisoapp:home') The View class AddStaffView(CreateView): form_class = forms.AddStaffMember success_url = reverse_lazy('nodisoapp:home') template_name = "scrty/addstaff.html" def form_valid(self, form): self.object = form.save(commit=False) self.object.password = get_random_string(length=8) self.object.save() self.object.compusers.add(self.object.id) return super(AddStaffView, self).form_valid(form) The form Class AddStaffMember(forms.ModelForm): usrtype = forms.ChoiceField(choices=[('Admin','Admin'),('Manager','Manager'),('Employee','Employee')],label="User Type: See below for descriptions" ) class Meta: model = get_user_model() fields = ("firstname","lastname","email","usrtype") labels = { "firstname": _("First Name"), "lastname": _("Last Name"), "email": _("E-mail"), } -
Django urls.reverse with argument
Stuck on this for a while: in Django pytest I am trying to do req = RequestFactory().get(reverse('app_name:app_view_name')) But I require the url to have '/[number]' at the end so that UpdateView will recognise the number and display appropriate form from model. In the browser the links and form submission all work fine, but I am unable to use reverse() in testing. I have tried: req = RequestFactory().get(reverse('app_name:app_view_name', args=[1])) and req = RequestFactory().get(reverse('app_name:app_view_name'), kwargs=['pk'=1]) but none of these work. I am simply trying to build the url with '/1' added at the end. Any help much appreciated. -
return a output linux log file in formatted way
Hi I am using djanog and following the below method in views.py to return a output file, response = HttpResponse(content=log_file) response['Content-Type'] = 'application/txt:html' return HttpResponse(response) Now the issue is when I return the file in browser is displayed without /n (next line) my actual file content is, ../xyz/value.txt ../abc/cls.txt ../opt/value.txt ../zz.txt But it is display as, ../xyz/value.txt ../abc/cls.txt ../opt/value.txt ../zz.txt when I open the same file with vim editor in linux machine it displays properly but here when I return from views and read it in browser it shows without /n How can I fix this issue? -
disable ordering by default for django_tables2 Tables
I use django_tables2 to render my tables. For one table, I only want to see the most recent 5 entries. Therefore, I need to order my queryset before passing it to the table object: qset = myObject.objects.order_by('-start_time').all()[:5] table = MyTableClass(qset, template='path/to/template.html') This yields the following error message: AssertionError: Cannot reorder a query once a slice has been taken. I could set orderable=False for every django_tables.Column, but since MyTableClass inherits from another table class, I would like to avoid this. Thanks in advance -
Daphne in Docker file
I have my docker file configuration for my django project, I am trying to set up daphne server for my project in the Docker file, I do not want to have the daphne command in the compose file.But when I add the following command to the Dockerfile I get an error of no app specified. CMD daphne -b 0.0.0.0 -p 8080 <app>.asgi:channel_layer How do I correctly configure this? -
Adding extra content to Class Based View and filtering it
I've built a for-loop in my HTML template and its nearly working. The issue I'm having is its listing Matches that are apart of a different tour. I think the way to fix this is adding a filter to the view that basically says "only pull in the matches to do with this tour" which is what I've tried to do below in the Match.objects.filter() but it isnt working and I'm not sure why. class CricketCalendar(generic.ListView): template_name="monthly_view/cricket-monthly-view.html" context_object_name='cricket_monthly_view' queryset = CricketMonthlyView.objects.all() def get_context_data(self, **kwargs): context = super(CricketCalendar, self).get_context_data(**kwargs) context['Tour'] = Tour.objects.all() context['Match'] = Match.objects.filter(tour=self.request.Tour) return context I have also tried the following and neither worked: self.kwargs['pk'] self.kwargs['Tour'] -
Django Admin conditional display inlines based on models property
I've got marketplace models with fields: class VacationEvent(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) process_fba = models.BooleanField(default=True) @property def has_amazon_fba_vacation(self): return hasattr(self, 'amazon_fba_vacation') And in admin.py: class FBAInline(admin.StackedInline): model = AmazonFBAVacation can_delete = False verbose_name_plural = 'amazon fba vacation' fk_name = 'event' I need to display conditionally FBAInline class when creating\updating VacationEventAdmin. list_filter shows true\false values of "process_fba" field, so if it is true - FBAInline should be displayed: @admin.register(VacationEvent) class VacationEventAdmin(admin.ModelAdmin): inlines = [] list_display = ('id', 'user', 'holiday_name', 'start_date', 'end_date', 'process_fba', 'process_fbm', 'process_walmart', 'process_ebay') list_filter = ['process_fba', 'process_fbm', 'process_walmart', 'process_ebay', 'status',] search_fields = ['holiday_name', 'user__username'] # if VacationEvent.process_fba and VacationEvent.has_amazon_fba_vacation: # inlines.append(FBAInline) # try: # getattr(VacationEvent, 'process_fba') # except AttributeError: # print "doesn't" # else: # inlines.append(FBAInline) I tried getting attr but don't understant how to compare field values for admin. Thanks for any help. -
Django ignore method for ALLOWED_HOSTS and django-cors-headers
In my app, I defined ALLOWED_HOSTS and CORS_ORIGIN_WHITELIST, but I have some methods which I want to be ignored from ALLOWED_HOSTS and CORS_ORIGIN_WHITELIST, in other words I want to access those methods from from everywhere. Is there a way to achieve this? -
Make autocomplete on text Input field using django-autocomplete-light 3.2.10
I have integrate django-autocomplete-light 3.2.10 successfully and it is working fine the issue is with its UI In template it renders with <select> <option> html, after clicking on it a span get attached to it with input text field inside. In form i am using ModelSelect2 as widget. widget=autocomplete.ModelSelect2(url='discovery:city-autocomplete') TextWidget is not supported in latest version 3.2.10 I just want the input text field directly visible to user. is there any possible way to achieve it with same library. May be i can create my own CustomTextWidget, or use some javascript to customize its UI -
Django + CMS: filer failing to upload
I am using django-cms==3.4.4 with django-filer==1.2.8, which has been working perfectly until now. When attempting to upload new images/files using the bootstrap3 image plugin, I am shown 'upload successful' but get an error 500: "POST /en/admin/filer/clipboard/operations/upload/2/?qqfile=test.jpeg HTTP/1.1" 500 102 This has been working previously. Recent changes to settings.py have included modifying MEDIA_ROOT and STATIC_ROOT, however, reversing these changes does not resolve the issue. I have seen on questions with similar problems that installing Pillow with easy_install instead of pip can solve the problem. I tried this, to no avail. Any help would be great. -
Django, S3 secure files - blue question mark instead of image
I host my static and media within AWS S3, I believe this is setup correct and is working. the files are currently public but I would like to make them all private, so that django acts as proxy for them. thus far I can get the image url correctly I get the type and the file and then I output it to a http response, I think im pretty close, however it returns a blue question mark instead of the image at the moment def get_file(request, file_id): import requests from django.http import HttpResponse from PIL import Image from io import BytesIO file_object = SiteFiles.objects.get(pk=file_id) if file_object.site_image: image_data = requests.get(file_object.site_image.url) image = Image.open(BytesIO(image_data.content)) return HttpResponse(image, content_type='image/{}'.format(image.format)) elif file_object.site_file: file_data = requests.get(file_object.site_image.url) return HttpResponse(pdf_data, content_type='application/{}'.format('type')) else: return redirect('sites:file_not_found') I have PIL confirmed as getting the image when I run some testing: >>> image_data = requests.get(file_object.site_image.url) >>> img = Image.open(BytesIO(image_data.content)) >>> img <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=640x480 at 0x7F55F2E29780> -
How to pass url value in django to views
My url.py is as below, from myapp import views urlpatterns = [ url(r'^myapp/get_requests/$', views.get_requests), ] Now my views.py is as below, @api_view(['GET']) def get_request(request): #How can I get request ID (base url here)? return HttpResponse('test') In the above if I do request in my browser with url as below it reaches my get_request method, http://localhost:8080/myapp/get_requests/ But the same gives error 404 when I try with some ID in the end as below, http://localhost:8080/myapp/get_requests/40 Now How can I get this ID number 40 in my views.py method? -
Using signals pre-delete, how to turn it off on some occasions?
Using Django: 1.10 Issue: Turn off pre_delete signal and receiver sometimes I want to use pre_delete to delete other related records for a model. And not call it at certain times even when I do want to delete the main model What did I try? I tried overriding the delete function in the main model PalletContent like this: def delete(self, *args, **kwargs): self.auto_delete_line_item = False if 'auto_delete_line_item' in kwargs: self.auto_delete_line_item = kwargs['auto_delete_line_item'] del kwargs['auto_delete_line_item'] return super(PalletContent, self).delete(*args, **kwargs) And then in the pre_delete @receiver(pre_delete, sender=PalletContent) def auto_delete_line_item(sender, instance, **kwargs): if instance.auto_delete_line_item: EntryFormHelper.remove_entry_form_line_item_from_pallet_content( pallet_content=instance) ExitFormHelper.remove_exit_form_line_item_from_pallet_content_if_any( pallet_content=instance) And then in the appropriate calls: I expect this to activate the pre_delete: pallet_content.delete(auto_delete_line_item=True) I expect this not to activate the pre_delete: pallet.pallet_contents.all().delete() What I got back was: File "/usr/../signals.py", line 31, in auto_delete_line_item if instance.auto_delete_line_item: AttributeError: 'PalletContent' object has no attribute 'auto_delete_line_item' -
How can I get the foreign field's name in queryset?
I have a Disk model, which has three ForeignKey: class Disk(models.Model): diskEssenceType = models.ForeignKey(to=DiskEssenceType, related_name='disks') # "SAS", "SSD" 等 diskOsType = models.ForeignKey(to=DiskOSType, related_name='disks') # "系统盘" "数据盘" 两种选择 hostType = models.ForeignKey(to=HostType, related_name='disks', on_delete=models.CASCADE) price = models.DecimalField(max_digits=8, decimal_places=2, default=0.00) # 单价 def __str__(self): return self.diskEssenceType.name + "-" + self.hostType.name def __unicode__(self): return self.diskEssenceType.name + "-" + self.hostType.name I use queryset : qs = Disk.objects.filter(hostType=obj) Its queryset data is like bellow, after use model_to_dict convert: { "price": 5.0, "diskOsType": 1, "hostType": 6, "diskEssenceType": 1, "id": 4 }, But I want to get the diskEssenceType's name, and the diskOsType's name, not its id, how to do with that? -
How to force function to evaluate queryset every time it is called
I'm creating a social media site in django, in which each user can have multiple accounts, each with their own posts, friends etc. In order to determine which account to use when loading templates, I have defined this function: def get_active_account(request): for account in Account.objects.filter(user=request.user): if account.active: return account Most views will then call get_active_account when they need to evaluate the currently active account. Now, the problem arises when changing the active account. In the view: def set_active(request, pk): account = get_object_or_404(Account, pk=pk) account.set_active() return redirect('/') In the Account model: def set_active(self): for account in Account.objects.filter(user=self.user): account.active = False account.save() self.active = True self.save() This appears to do nothing; anything referencing the active account will still show the previously active account, and trying to create a post etc. will do it under the old account. After refreshing, however, everything is as it should be. From what I've read, this is a problem with the get_active_account function evaluating the queryset once and then returning a cached version when it is called later (although this may be a totally incorrect assumption). How do I fix the problem, and have everything work without needing a browser refresh? -
<Disk: > is not JSON serializable
In my serializer, I have a SerializerMethodField field: class CloudHostParamsSerializer(ModelSerializer): """ 根据hosttype id返回云服务器购买需要的参数 """ cputypes = CPUTypeSerializer(many=True, read_only=True) memtypes = MEMTypeSerializer(many=True, read_only=True) bandwidths = BandWidthTypeSerializer(many=True, read_only=True) #disks = HostTypeDiskSerializer(many=True, read_only=True) disks = serializers.SerializerMethodField() class Meta: model = HostType exclude = [ "availablearea", ] def get_disks(self, obj): qs = Disk.objects.filter(hostType=obj) dict = {"系统盘": [], "数据盘": []} for item in qs: if item.diskOsType.name == "系统盘": dict["系统盘"].append(item) elif item.diskOsType.name == "数据盘": dict["数据盘"].append(item) return dict in it I return a dictionary, but when I access the API, there comes a issue: TypeError at /api/userfront_product/cloudserver/cloudparams/hosttype/6/ is not JSON serializable My views.py is bellow: class CloudParamsAPIView(RetrieveAPIView): """ 根据hosttype id得到的 """ serializer_class = CloudHostParamsSerializer permission_classes = [] queryset = HostType.objects.all()