Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to let users upload files to a website on Azure?
I want to add a feature to my website that enables users to upload files. I want to store the uploaded files as blobs (my site is hosted on Azure. Im planning to use python (django) for the server side, however, I can also work with node.js instead (I'm new to both technologies. How can I implement it? Do I need to store these files temporarily on the virtual server, then store them as blobs and then delete them or there is a better, more efficient way to store them directly to the blob storage? Ill just clarify that I do not want to expose the account credentials so I can't use Azure storage REST interface from the browser. Thanks! -
Django Field Instances overriding each others arguments
I am testing and preparing a new Django package for using bleach with Text and Char fields in the Django ORM and with DRF. I've hit a bit of a roadblock with it however and it has made me take pause and wonder if I truly understand how a models fields are instantiated. Hopefully someone can clear this up. I am initialising the arguments for bleach by loading a default settings dict from django.conf.settings, and then checking a field_args parameter to see if any have been overridden for a specific field definition, like below. This is then used in the pre_save function to call bleach: class BleachedCharField(CharField): """ An enhanced CharField for sanitising input with the Python library, bleach. """ def __init__(self, *args, field_args=None, **kwargs): """ Initialize the BleachedCharField with default arguments, and update with called parameters. :param tags: (dict) optional bleach argument overrides, format matches BLEACHFIELDS defaults. :param args: extra args to pass to CharField __init__ :param kwargs: undefined args """ super(BleachedCharField, self).__init__(*args, **kwargs) self.args = settings.BLEACHFIELDS or None if field_args: if 'tags' in field_args: self.args['tags'] = field_args['tags'] if 'attributes' in field_args: self.args['attributes'] = field_args['attributes'] if 'styles' in field_args: self.args['styles'] = field_args['styles'] if 'protocols' in field_args: self.args['protocols'] = field_args['protocols'] … -
How to get a list of tags from the logged-in user in views.py?
Hei, i need a list (array) of all tags of the logged-in user in one of my views. My model.py looks like this: from taggit.managers import TaggableManager class CustomUser(models.Model): user = models.OneToOneField('auth.User', null=True, on_delete=models.CASCADE) tags = TaggableManager() And the view, where I need the list, looks like this: @login_required def tag_list(request): u = CustomUser.objects.get(user=request.user) tags= Tag.objects.filter(name=u) arr = [] for tag in tags: arr.append(str(tag)) return render(request, 'tag_list.html', locals()) I already get the specific user but the the array is empty even in the admin-backend I can see tags in the field. -
TypeError: Object of type 'CatalogObject' is not JSON serializable without views
this is my item model. class Item(models.Model): id = SmallUUIDField(default=uuid_default(), primary_key=True, db_index=True, editable=False, verbose_name='ID') name = models.CharField(max_length=100) data = JSONField() in the save_items function im passing a parameter square_items which is json that we get back from a third party api. im tring to save that raw data to a property data in the item field. but im getting this error E TypeError: Object of type 'CatalogObject' is not JSON serializable not quite sure why its saying that square_item is not json since its a json response from a third party api. def save_items(self, square_item): try: record = Item.objects.get_or_create( name=square_item['name], data=json.dumps(square_item) ) except POSRecord.DoesNotExist: record = Item(name=square_item['name']) record.save() -
AttributeError: type object 'ListViewSet' has no attribute 'get_extra_actions'
I'm trying to build a scrumboard django app which basically has cards and lists in it. I'm unable to solve the following issue. Unhandled exception in thread started by <function check_errors <locals>.wrapper at 0x0000000003DF7C80> Traceback (most recent call last): File "C:\Users\...\lib\site- packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) ... urlpatterns = router.urls File "C:\Users\...\lib\site- packages\rest_framework\routers.py", line 101, in urls self._urls = self.get_urls() File "C:\Users\...\lib\site- packages\rest_framework\routers.py", line 363, in get_urls urls = super(DefaultRouter, self).get_urls() File "C:\Users\...\lib\site- packages\rest_framework\routers.py", line 261, in get_urls routes = self.get_routes(viewset) File "C:\Users\...lib\site-packages\rest_framework\routers.py", line 176, in get_routes extra_actions = viewset.get_extra_actions() AttributeError: type object 'ListViewSet' has no attribute 'get_extra_actions' Following is my models.py from django.db import models class List(models.Model): name = models.CharField(max_length=50) def __str__(self): return "List : {}".format(self.name) # returns list values class Card(models.Model): title = models.CharField(max_length=100) description = models.TextField(blank=True) list = models.ForeignKey(List, related_name = "card" ,on_delete=models.PROTECT) story_points = models.IntegerField(null=True, blank = True) business_value = models.IntegerField(null=True, blank = True) def __str__(self): return "Card : {}".format(self.title) My api.py where my viewset is defined from rest_framework.viewsets import ModelViewSet from drf_multiple_model.views import ObjectMultipleModelAPIView from .serializers import ListSerializer, CardSerializer from .models import List, Card class ListViewSet(ModelViewSet): queryset = List.objects.all() serializer_class = ListSerializer class CardViewSet(ModelViewSet): queryset = Card.objects.all() serializer_class = CardSerializer class ListViewSet(ObjectMultipleModelAPIView): querylist … -
Setting headers in Django tests (API versioning)
I'm using AcceptHeaderVersioning with the Django rest framework as described here: https://www.django-rest-framework.org/api-guide/versioning/#versioning-with-rest-framework I'd like to test that the API returns the default version if no version is specified but the correct version when it is. But, it seems impossible to pass the version parameter to the test. Here's an example: def testCheckVersion(self): versions = [u'v0.1', u'v0.2'] self.key = APIKey(name='Example Key') self.key.save() for version in versions: response = self.client.get('/api/data/', VERSION="{0}".format(version), **{'Api-Key': self.key.key}) self.assertEqual(response.status_code, 200) content = json.loads(response.content) self.assertEqual(content['api_version'], version) This always gives the default api version (v0.2 in this case). I've tried various means of re-working the response = line with no luck. This could perhaps be fixed by using QueryParameterVersioning instead but I'd rather not, so please let me know if you have any suggestions. -
Did not work django-filters in Django app. Python
I am trying to use django filters for my application, but it always returns the same error. from django.contrib.auth.models import Promoters ImportError: cannot import name 'Promoters' from 'django.contrib.auth.models' (C:\Users\tymot\Desktop\my_app\env\lib\site-packages\django\contrib\auth\models.py) Has anyone had a similar problem? How best to solve it? change of django versia? or maybe there are any alternatives? My django version (2, 1, 2, 'final', 0), Python 3.6. -
Running the django migrations one by one
I have django migrations on production server until 0102_auto. Now in my development server i have 13 more and number is 0115_auto in dev server. Tomorrow i will carry all files to production server. Also i will carry models.py , views.py and templates to production server. Normally i run migrate on production server and it migrates all new 13 migrations. But this time i want to run migrations one by one to have more control. Because i had some issues on test server. Is it possible to run these 13 new migrations one by one, one after another ? -
Weird error in Django while adding record through admin panel
expected str, bytes or os.PathLike object, not list Traceback (most recent call last): File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\options.py", line 604, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\sites.py", line 223, in inner return view(request, *args, **kwargs) File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\options.py", line 1636, in add_view return self.changeform_view(request, None, form_url, extra_context) File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\options.py", line 1525, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\options.py", line 1564, in _changeform_view self.save_model(request, new_object, form, not add) File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\options.py", line 1091, in save_model obj.save() File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 718, in save force_update=force_update, update_fields=update_fields) File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 748, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 831, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 869, in _do_insert using=using, raw=raw) File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Kamil\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line … -
Django admin - edit multiple values simultaneously in list display
I have a large number of items and would like to be able to edit a selection of those simultaneously, while in the admin list view. Here is screen shot of how the action checkbox could be used for this purpose. So, if I edit the importance of one selected item, the importance of all selected items should change simultaneously. By also applying list_filter and search_field, this should speed up edits when dealing with a large number of items. -
Storing a .html report with a data model
I am new to Django, and I am looking for the best approach to the following problem. I have an application that is producing two reports. One is a JSON blob so I store it in psql with data model that uses JSONField. The second report is a .html file. The .html file will be generated multiple times a day so the first thing that came to mind was storing it in the db. I need to be able to pull the report as well so it can be displayed to the user in the UI. I created a test data model using TextField: class TestResultsHTML(models.Model): name = models.CharField(max_length=200) report = models.TextField() It makes it into the Db no problem, however when I attempt to retrieve it I can't seem to get the actual report: In [3]: html_results = TestResultsHTML.objects.get(id=4) In [4]: html_results.name Out[4]: 'b0f5c336-867a-44a3-a5ef-6297bf6042cf' In [5]: html_results.report Out[5]: "<_io.TextIOWrapper name='report.html' mode='r' encoding='UTF-8'>" I was expected that .report would return the actual contents of the file. The file itself is 1800+ lines. Is this a good approach or is this not the intended use of TextField? -
Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH
I'm creating a startproject and I'm trying to migrate default django schema using the command line: manage.py migrate The result is : "Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?" I'm using a virtual environment and I have the next dependencies installed: Django==2.1.2 psycopg2==2.7.5 pytz==2018.5 Of course I'm trying to migrate with the virtual environment activated. Somebody knows if I've got a problem with the compatibilitie of the versions? My PostgreSQL is 10. -
How to delete / edit posts as staff or superuser?
I am fairly new to Django and right now not very familiar with the concept of Django. I created a user board (from simpleisbetterthancomplex.com) and would like to implement a Moderation with a "is_staff" user. For now, only the user which created a post / comment is able to edit the post. As a is_staff user, I also want be able to edit ALL posts / comments. This is the edit button: {{ post.message }} {% if post.created_by == user %} <div class="mt-3"> <a href="{% url 'edit_post' post.topic.board.pk post.topic.pk post.pk %}" class="btn btn-primary btn-sm" role="button">Edit</a> </div> {% endif %} I thought I could so something like: {{ post.message }} {% if user.is_staff %} <div class="mt-3"> <a href="{% url 'edit_post' post.topic.board.pk post.topic.pk post.pk %}" class="btn btn-primary btn-sm" role="button">Edit</a> </div> {% endif %} Although I reach the correct hyperlink to edit the post, I receive a "Page not found" error. What could be an approach to implement some Moderation to my forum? -
Django : Trying to import quantity data in cart app when the customer persist the order form
I am currently trying to make a ordering system with django. Now I am at the stage of letting customers to proceed their orders, and I am now facing the problem that I cannot import a quantity data of the products in the cart. I have two apps under my whole system which is Cart and Foodordering. Cart app does the cart system in the website, storing session data and get quantity data. The cart app works fine, no errors. In Foodordering app, It has all the database stuff behind, so that proceeding order will be dealt within this app. I tried to import Cart in my foodordering/views.py but for some reason Cart(request) doesn't work even though I did import it. The exact error it is saying is -> NameError: name 'request' is not defined. foodordering/views.py : from foodordering.models import Order_dish from django.views.generic.edit import CreateView from django.urls import reverse_lazy from cart.cart import Cart from cart.forms import CartAdd #---- Creating Order_dish record class create_orderdish(CreateView): cart = Cart(request) model = Order_dish fields = ['quantity'] success_url = reverse_lazy('foodordering:created') initial = {'quantity': item['quantity']} def form_valid(self, form): return super(create_orderdish, self).form_valid(form) cart/cart.py: from decimal import Decimal from django.conf import settings class Cart(object): def __init__(self, request): self.session … -
Change date format in Django admin page
When i export the data from my admin page to excel it is giving default date format.But I need to change the default date format(2018-10-18) to (10/18/2018) in admin page.Where should i change this? models.py class Track(models.Model): Date = models.DateField() -
meta update need two request to update
I update some model field choices at object construction but admin interface requires to be called two times to show the field as a combobox. class Widget(Subclassed): entity_type = models.CharField(max_length=1024) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._meta.get_field("entity_type").choices = ["fun","happiness", "joy"] I use Django 2.1 -
UNIQUE constraint failed(django modelform)
im trying to UPDATE specific fields of a model instance (non PK fields) , for instance a blog model , using a ModelForm input from a user class Post(models.Model): STATUS_CHOICES = [ ('draft','Draft'), ('published','Published') ] postId = models.AutoField(primary_key=True) title = models.CharField(max_length=50,unique=True) slug = models.SlugField(max_length=50) body = models.TextField() status = models.CharField(max_length=20,choices=STATUS_CHOICES,default='draft') date = models.DateField(auto_now_add=True) ----------------------------------------------------------------------- class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title','body','status'] ----------------------------------------------------------------------- def edit(request,slug): template = 'blog/post_edit.html' post = get_object_or_404(Post,slug=slug) form = PostForm(request.POST or None,instance=post) if request.method == 'POST': if form.is_valid(): form.save() return render(request,template,{'form':form}) the problem im seeing is that the db is trying to insert a new value with the same postId PK! I also tried using cleaned_data in the same post instance and always get the same error -
Django : Get queryset with filters over list (filled and/or empty)
I'm working on a module which let to display objects thanks to filters defined by users. View.py file : checkbox_category = self.request.GET.getlist('CategoryChoice') checkbox_format = self.request.GET.getlist('FormatChoice') checkbox_language = self.request.GET.getlist('LanguageChoice') choice_title = self.request.GET.get('TitleChoice') test_research = Document.objects\ .filter(Q(publication__category__name__isnull=True) | Q(publication__category__name__in=checkbox_category))\ .filter(Q(format__isnull=True) | Q(format__in=checkbox_format))\ .filter(Q(language__isnull=True) | Q(language__in=checkbox_language))\ .filter(Q(title__isnull=True) | Q(title__in=choice_title)) My template file for one filter (language) : <button class="btn btn-default btn-choice" type="button" data-toggle="collapse" data-target="#language" aria-expanded="false" aria-controls="language"><span class="glyphicon glyphicon-chevron-down"></span> {% trans 'Language' %}</button> <div class="row"> <div class="col"> <div class="collapse multi-collapse" id="language"> <div class="card card-body card-choice"> {% for language in search_language %} <input type="checkbox" class="fakeRadio" name="LanguageChoice" value="{{ language }}"> {{ language }}<br> {% endfor %} </div> </div> </div> </div> It looks like this in my web application : I can check one or multiple checkboxes, but also none checkbox for a specific criteria. This last option makes issue, because, for example, if I don't check language, the resulting queryset is empty and shouldn't be because it should take account the others filters. Example from my terminal with print: Category filter : ['FOOD CONTACT'] Format filter : ['pdf'] Language filter : ['EN'] Title filter : <QuerySet []> It should return 1 object with these parameters. I think there is an issue with my queryset and Q -
2 slugs related by ForeignKey
I am looking for a minimalist example of having 2 slugs related by a ForeignKey inside a Url. How to get the Categorie Slug in the DetailView(DetailView) and call it in the Url? #Model class Categorie(models.Model): name = models.CharField(max_length=50,unique=True) slug = models.SlugField(max_length=100,unique=True) def __str__(self): return self.name class Detail(models.Model): title = models.CharField(max_length=100) slug= models.SlugField(max_length=100,unique=True) categorie = models.ForeignKey('Categorie', on_delete=models.CASCADE, related_name="details") def __str__(self): return self.title #Views class CategorieView(DetailView): model = Categorie slug_field = 'slug' template_name = "app/categories.html" class DetailView(DetailView): model = Detail slug_field = 'slug' template_name = "app/details.html" #Ulrs path('<slug>', views.CategorieView.as_view(), name='categorie_name'), path('<?>/<slug>', views.DetailView.as_view(), name='detail_name'), -
Django TabularInline list objects that are connected to the parent of the parent
recently I faced a problem when I need to see all objects in django admin panel, which are related to object in second level realtionship. My models: class Payment() <...> class Verification() payment = models.ForeignKey('payments.Payment', null=True, blank=True, on_delete=models.DO_NOTHING) <...> class VerificationDocument(): verification = models.ForeignKey(Verification, on_delete=models.DO_NOTHING) <...> Payment can be connected to more that one Verification objects. Every Verification object can be connected to more than one VerificationDocument objects. What I need is to show all VerificationDocument objects that are connected to Payment via Verification. My admin.py file: class VerificationDocumentInline(admin.TabularInline): model = VerificationDocument fk_name = 'verification' @admin.register(Verification) class VerificationAdmin(admin.ModelAdmin): inlines = [ VerificationDocumentInline, ] With this configuration, when I click on Verification object, I see all VerificationDocument objects that are connected to Verification. So, when I click on Verification object in django admin panel, I need to see all VerificationDocument objects by this logic: verification_document.verification.payment_preference.all_verification_documents() -
return to specific page in Django
I would like to return to a specific page after I edit a record using Django "UpdateView", however this page url needs an argument passed to it as well (see urls.py below). I am pretty sure I need to use "get_absolute_url", which works when I am just redirecting to an unfiltered page, but can't seem to get the syntax to redirect to a filtered page. Models.py class DefaultDMLSProcessParams(models.Model): device = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,) customerTag = models.CharField(max_length=50,) processNotes = models.TextField(max_length=300,blank=True,default = "") def __str__(self): return str(self.defaultParamDescrip) def get_absolute_url(self): #self.object.pk? pass this below somehow? return reverse('Default_Listview',) views.py class defaultUpdateView(LoginRequiredMixin,UpdateView): model = models.DefaultDMLSProcessParams fields = ['processNotes','customerTag'] template_name = 'default_edit.html' login_url = 'login' urls.py path('<int:device>', DefaultsListView.as_view(), name='Default_Listview'), -
ModuleNotFoundError: No module named 'myapp' building django 1.11 app with pyinstaller 3.4
My Django app is under a top level company name import struture src mycomp myapp ... my apps ... settings.py manage.py unreleated_package_1 unreleated_package_2 When I try to compile to a pyinstaller app using: ./venv/bin/pyinstaller --name=foo src/mycomp/myapp/manage.py I get the following errors: File "/opt/master/venv/lib/python3.6/site-packages/PyInstaller/utils/hooks/subproc/django_import_finder.py", line 27, in <module> django.setup() File "/opt/master/venv/lib/python3.6/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/opt/master/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/opt/master/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/opt/master/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.6/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 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'myapp' And File "/opt/master/venv/lib/python3.6/site-packages/PyInstaller/compat.py", line 736, in importlib_load_source return mod_loader.load_module() File "<frozen importlib._bootstrap_external>", line 399, in _check_name_wrapper File "<frozen importlib._bootstrap_external>", line 823, in load_module File "<frozen importlib._bootstrap_external>", line 682, in load_module File "<frozen importlib._bootstrap>", line 265, in _load_module_shim File "<frozen importlib._bootstrap>", line 684, in _load File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line … -
AttributeError: 'Startup' object has no attribute 'tags'
This is my model and migration file. Its from The book Django-Unleashed - Chapter 10 . Models.py: class Tag(models.Model): def get_update_url(self): return reverse('organizer_tag_update', kwargs={'slug': self.slug}) def get_absolute_url(self): return reverse('organizer_tag_detail',kwargs={'slug':self.slug}) def get_delete_url(self): return reverse('organizer_tag_delete', kwargs={'slug': self.slug}) name = models.CharField( max_length=31, unique=True) slug = models.SlugField( max_length=31, unique=True, help_text='A label for URL config.' ) class Meta: ordering=['name'] def __str__(self): return self.name class Startup(models.Model): class Meta: ordering=['name'] get_latest_by=['founded_date'] name = models.CharField( max_length=31, db_index=True) slug = models.SlugField( max_length=31, unique=True, help_text='A label for URL config.') description = models.TextField() founded_date = models.DateField('date founded') contact = models.EmailField() website = models.URLField(max_length=255) tags = models.ManyToManyField(Tag,blank=True) def __str__(self): return self.name def get_update_url(self): return reverse('organizer_startup_update',kwargs={'slug': self.slug}) def get_delete_url(self): return reverse('organizer_startup_delete',kwargs={'slug': self.slug}) def get_absolute_url(self): return reverse('organizer_startup_detail',kwargs={'slug': self.slug}) Migrations.py : from datetime import date from django.db import migrations, models STARTUPS = [ { "name": "Arachnobots", "slug": "arachnobots", "contact": "contact@arachnobots.com", "description": "Remote-controlled internet-enabled " "Spider Robots.", "founded_date": date(2014, 10, 31), "tags": ["mobile", "augmented-reality"], "website": "http://frightenyourroommate.com/", }, { "name": "Boundless Software", "slug": "boundless-software", "contact": "hello@boundless.com", "description": "The sky was the limit.", "founded_date": date(2013, 5, 15), "tags": ["big-data"], "website": "http://boundless.com/", }, ] def add_startup_data(apps, schema_editor): Startup = apps.get_model( 'organiser', 'Startup') Tag = apps.get_model('organiser', 'Tag') for startup in STARTUPS: startup_object = Startup.objects.create( name=startup['name'], slug=startup['slug'], contact=startup['contact'], description=startup['description'], founded_date=startup['founded_date'], website=startup['website']) … -
Why HTML loads weirdly in django sometimes?
Sometimes while loading a page, a part of html ( like tags, button etc ) loads weirdly. Although it works fine most of the times and single reload can be done in most of the cases, what can be possible reason for this ? Example : -
Return value of related object with condition
As for example I've got 3 models: User, Event, Participator class Event(..): creator = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='event_creator_set') class Participator(..): status = models.CharField(..) event = models.ForeignKey('events.Event', on_delete=models.CASCADE, related_name='participators_set') user = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='participations_set') I want to get all user's and also get information about relation with specific event. If user is even't participator -> return status from Participator models, else -> null Here is my queries: e = Event.objects.first() users = User.objects.annotate(is_participationg=Case(When(id__in=e.participators_set.values_list('user__id', flat=True), then=Value(True)), default=Value(False), output_field=BooleanField())) So I can know whether user is participating in specific event. How can I get user's participating status in then and None in default?