Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I create a complete video tube site using Django?
I would like to create a video tube site like YouTube using the Django framework. I read about the VideoJS plugin. It works fine. But, I'm not able to add an option to select the video quality. Can you give me some references where I can find more information about creating a complete video site using Django? -
How to use logging for print statements inside a python package?
I am working on a Django project which uses some packages that print statements out to the console (some of these packages are by made me). These print statements represent important info and cannot be removed just by commenting out the prints. Can someone guide me as to how to redirect such print statements to a logger? Also what would be the best practice for printing stuff to console while developing a package? -
How can i get list of Django ManyToManyField like this?
msgs <QuerySet [<Msg: home : Dusra msg from admin>, <Msg: home : good>, <Msg: home : k>, <Msg: home : k>, <Msg: home : hi>, <Msg: home : Yello>, <Msg: home : Good>, <Msg: home : lets se>]> msgs.values('content','likes') # likes is a ManyToManyField <QuerySet [{'content': 'Dusra msg from admin', 'likes': UUID('472ab5e5-ddda-4d18-b229-67f7d0f3d7fb')}, {'content': 'Dusra msg from admin', 'likes': UUID('8bbb16f2-11a7-4d52-818b-acbdcf518810')}, {'content': 'Dusra msg from admin', 'likes': UUID('d1499fb6-4fd6-4ec1-abda-a507c1339d93')}, {'content': 'good', 'likes': None}, {'content': 'k', 'likes': None}, {'content': 'k', 'likes': UUID('36d0c720-9169-4d66-8afa-2ff2ffb30166')}, {'content': 'hi', 'likes': None}, {'content': 'Yello', 'likes': None}, {'content': 'Good', 'likes': None}, {'content': 'lets se', 'likes': UUID('36d0c720-9169-4d66-8afa-2ff2ffb30166')}, {'content': 'lets se', 'likes': UUID('68f85e0c-fda1-4856-894c-b9c52fda5669')}, {'content': 'lets se', 'likes': UUID('d1499fb6-4fd6-4ec1-abda-a507c1339d93')}]> I want to convert above output to like below one <QuerySet [{'content': 'Dusra msg from admin', 'likes': ['472ab5e5-ddda-4d18-b229-67f7d0f3d7fb', '8bbb16f2-11a7-4d52-818b-acbdcf518810', 'd1499fb6-4fd6-4ec1-abda-a507c1339d93')}, {'content': 'good', 'likes': None}]} -
Invalid block tag 'endwith' Django
I have a Django template which is quite minimal but still throws an error at me, here it is : {% load static %} {% with somevar="somethingcool" %} {% extends 'myapp/ElementBase.html' %} # some html {% endwith %} I get the error "Invalid block tag on line 5: 'endwith'. Did you forget to register or load this tag? " which makes no sense to me. Any idea what i'm missing here ? -
How to improve unit test migration setup with Django?
I have created a Django project, which has more than 150 migration files. While running the unit tests, the setup itself is very much time consuming because Django first drops the database and creates a new test database and runs all migrations. I have tried using --keepdb flag, but with this approach the problem is that ensuring the base setup is clean is not guaranteed. One approach I can think of is using the --keepdb flag along with 2 additional steps- Before starting test, drop database, re-create from a database dump. Which will be way faster than running the migrations Run tests with --keepdb flag Is there any other approach we can take to reduce the total setup time? -
django migrate error raise CircularDependencyError(", ".join("%s.%s" % n for n in cycle)) django.db.migrations.exceptions.CircularDependencyError
I am a bit new to python and django Please adice me on how to resolve this issue in django after running python manage.py migrate /lib/python3.7/site-packages/django/db/migrations/graph.py", line 274, in ensure_not_cyclic raise CircularDependencyError(", ".join("%s.%s" % n for n in cycle)) django.db.migrations.exceptions.CircularDependencyError: app_features.0001_initial, authtoken.0001_initial, authtoken.0002_auto_20160226_1747, authtoken.0003_tokenproxy my requirements.txt below Django==3.1.3 pytz==2021.1 sqlparse==0.4.1 dj-database-url==0.5.0 django-cors-headers==3.6.0 django-rest-swagger==2.2.0 djangorestframework==3.12.2 drf-yasg==1.20.0 gunicorn==19.9.0 ruamel.yaml==0.16.13 ruamel.yaml.clib==0.2.2 whitenoise==5.0.1 psycopg2-binary==2.8.6 django-hashid-field==3.2.1 requests even runserver is not working anymore Is there a conflicting field value in my models? Can someone please tell me what I have to do to fix this Thanks in advance -
Django postgres django.db.utils.OperationalError by running from Git Repo
I have pushed my Django Projekt with Postgres DB in GitHub and want to run it on a Windows Server. On the server Postgres was installed, in cloned Git Repo DB connection settings were adjusted. However, by running the django server it crashes with an error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError Postgres is running at the time, all libs are installed. My settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'Name', 'USER': 'User', 'PASSWORD': 'PW', 'HOST': 'localhost', 'PORT': '5432', } } On the server there is another Django Project connected to the same DB, but i have read that it should not be a problem to share the same User and DB between 2 projects. Maybe someone encountered the same problem? -
sorting of store goods
I'm using ListView in my Class Based Views and I want to sort the goods by the selected field by the user, but I couldn't find the information I needed view class Shop(ListView): template_name = 'essense/shop.html' context_object_name = 'items' paginate_by = 9 allow_empty = False def get_queryset(self): return Item.objects.all() def get_context_data(self, *, object_list=None, **kwargs): ***context*** return context def get_ordering(self): ordering = self.request.GET.get('orderby',) print(ordering) return ordering template <form action="{% url 'shop' %}" method="get" id="sortProduct"> <div class="product-sorting d-flex"> <p>Sort by:</p> <select type="submit" name="select"> <option type="submit" name="orderby" value="price">Price: $$ - $</option> <option type="submit" name="orderby" value="-price">Price: $ - $$</option> </select> <input type="submit" class="d-none" value=""> </div> </form> -
Django throwing error 404 while connecting with stripe webhook
Hey guys I am keep getting 404 error on while using Stripe webhook in my Django app. Really appreciate your help my urls.py urlpatterns = [path('my_webhook/', views.my_webhook, name='my_webhook')] views.py @csrf_exempt def my_webhook(request): payload = request.body event = None try: event = stripe.Event.construct_from( json.loads(payload), stripe.api_key ) except: return HttpResponse(status=400) if event.type == 'payment_intent.succeeded': payment_intent = event.data.object elif event.type == 'payment_method.attached': payment_method = event.data.object else: print('Unhandled event type {}'.format(event.type)) return HttpResponse(status=200) Error: [20/Jul/2021 14:28:36] "POST /my_webhook HTTP/1.1" 404 3816 Not Found: /my_webhook -
Django-Elasticsearch-Dsl does not create an index
I am working on a project and want to index an existing models.Model class to search for it. Here is my code of the corresponding Document class: @registry.register_document class LiteratureDocument(Document): class Index: # Name of the Elasticsearch index name = 'literature' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Paper # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ 'title', ] I then rebuilt the search index and started the elasticsearch server properly but it does not recognize my index. When searching for something, I get an index_not_found_exception. Thanks -
Dajngo Rest Framework how to set field to no required
I have this code and i want to set content field to be not required. type = serializers.ReadOnlyField(default=ComponentType.MediaComponent.value) content = ContentSerializer() class Meta: model = MediaComponent fields = ['id'] + ComponentSerializer.Meta.fields + ['type', 'content'] -
Django model form field initials not updating
Here my intention is to show pass the analysis_start_date value as year and month only(%Y-%m), below in my form class allowed_date_formats = [ '%m-%Y', '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%Y-%m' ] class PropertyForm(forms.ModelForm): analysis_start_date = forms.DateField( input_formats=allowed_date_formats, help_text="Choose the starting month", ) def __init__(self, *args, **kwargs): if self.instance: date = self.instance.analysis_start_date kwargs.update(initial={ 'analysis_start_date': date.strftime('%Y-%m') }) but in the but in the output form it shows date including the day, thanks in advance for any solutions :) -
How to make Django modifiy JSONField value effictively
With MySQL as database backend, I make Django ORM to update the following JSONField value { "01-task1": {"data":"huge data here"} } just add a new element , "02-testing": {} but I got the following sql log (0.000) UPDATE `by_jsontree_store1` SET `store_type` = 1, `user_id` = 2, `data` = '{\"01-task1\": {\"data\": \"huge data here\"}, \"02-testing\": {}}' WHERE `by_jsontree_store1`.`id` = 1; args=(1, 2, '{"01-task1": {"data": "huge data here"}, "02-testing": {}}', 1) It looks like Django rewrite the whole content of that JSONField. Imaging if the original content is huge, like 100MB, what could happen. Is there any trick could handle that effectively? -
KeyError at /admin/quiz/client/2/change/
I m getting this error when i m trying to change the model using Django Admin: "Key 'id' not found in 'ClientForm'. Choices are: denumire, email, is_active, is_client, is_staff, password, quizCompleted." ----- models.py ------ class CustomAccountManager(BaseUserManager): def create_superuser(self, email, denumire, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, denumire, password, **other_fields) def create_user(self, email, denumire, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, denumire=denumire, **other_fields) user.set_password(password) user.save() return user class Client(AbstractBaseUser, PermissionsMixin): denumire = models.CharField(max_length=300, default=' ', verbose_name='denumire') email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_client = models.BooleanField(default=False) quizCompleted = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['denumire'] def __str__(self): return self.denumire ----- admin.py ------ class UserAdminConfig(UserAdmin): model = Client search_fields = ('id','email', 'denumire', ) list_filter = ('id','email', 'denumire', 'is_active', 'is_staff', 'is_client', 'quizCompleted') ordering = ('-denumire',) list_display = ('email', 'denumire', 'is_active', 'is_staff', 'is_client', 'quizCompleted') fieldsets = ( (None, {'fields': ('id', 'email', 'denumire',)}), ('Permissions', {'fields': ('is_staff', 'is_active', 'is_client')}), ('Personal', {'fields': ('quizCompleted',)}), ) formfield_overrides = { models.TextField: {'widget': … -
What do I put in the success_url in my django view. Right now, this isn't saving the edited form nor redirecting the page
I don't know what to use or how to use the success_url in the django views. I tried reading online but did not understand, also tried doing a few things told by others but that is not working. I am pretty sure I am doing something wrong but I don't know what and how to solve it. views.py: class EditComplaint(UserPassesTestMixin, UpdateView): model = Complaint form_class = ComplaintForm template_name = 'newcomplaint.html' success_url = reverse_lazy('Complaint') def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter( user=self.request.user ) def test_func(self): complain = self.get_object() if self.request.user == complain.user: return True raise Http404(_('This complain does not exist')) urls.py: urlpatterns = [... path('Complaint/<int:pk>/edit/', accounts.views.EditComplaint.as_view(), name='Complaint') ] -
Format Column with Django-Tables2 based on another boolean column
I have a table whith a few columns amongst them one is called commune and has a string type and another is confiance_commune which is a boolean value. I would like commune to be rendered bold and green if confiance_commune is true. Here is my code : models.py class Mrae(models.Model): titre = models.TextField(blank=True, null=True) lien = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) type_projet = models.TextField(blank=True, null=True) pv_mentionne = models.BooleanField(blank=True, null=True) commune = models.TextField(blank=True, null=True) commune_m = models.TextField(blank=True, null=True) departement = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True) confiance_commune = models.BooleanField(blank=True, null=True) index = models.AutoField(primary_key=True) class Meta: managed = False db_table = 'mrae' tables.py from django_tables2 import tables from django_tables2.columns import URLColumn from .models import Mrae class MraeTable(tables.Table): lien = URLColumn("Lien") class Meta: model = Mrae attrs = {"class": "table table-responsive"} fields = ['titre', 'lien', 'pv_mentionne', 'date', 'commune', 'departement'] tamplate_name = "django_tables2/bootstrap-responsive.html" -
Update the same template without refreshing from different views in Django
I am implementing a geospatial web app where everything is contained within one template in Django. At the moment I want to update a div in the template to display a Plotly graph, which is most easily created with Python and then passed to the template as a template variable. Is there a way I can update the variables returned, and then update the displayed template without refreshing, from a different view which renders the template initially? -
Style Form with django-filters
How can I modify the render of my form ? I followed the tutorial from django-tables2 considering table filtering. My actual code : filters.py import django_filters from .models import Mrae class MraeFilter(django_filters.FilterSet): titre = django_filters.CharFilter(lookup_expr='icontains', field_name='titre', label='Titre') annee = django_filters.NumberFilter(lookup_expr='year', field_name='date', label='Année') class Meta: model = Mrae fields = ['titre', 'pv_mentionne', 'date', 'date', 'commune', 'departement'] index.html <section class="container-fluid"> {% load render_table from django_tables2 %} {% load bootstrap4 %} {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='sr-only' %} {% bootstrap_button 'Filtrer' %} </form> {% endif %} {% render_table table 'django_tables2/bootstrap.html' %} </section> models.py class Mrae(models.Model): titre = models.TextField(blank=True, null=True) lien = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) type_projet = models.TextField(blank=True, null=True) pv_mentionne = models.BooleanField(blank=True, null=True) commune = models.TextField(blank=True, null=True) commune_m = models.TextField(blank=True, null=True) departement = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True) confiance_commune = models.BooleanField(blank=True, null=True) index = models.AutoField(primary_key=True) class Meta: managed = False db_table = 'mrae' The Result : If I look at the resulting html, here is the code : <form class="form form-inline" action="" method="get"> <div class="form-group"> <label for="id_titre"> Titre </label> <input type="text" name="titre" class="form-control" placeholder="Titre" title="" id="id_titre"> </div> <div class="form-group"> <label for="id_pv_mentionne"> Pv mentionne </label> <select name="pv_mentionne" class="form-control" title="" id="id_pv_mentionne"> <option value="unknown" selected="">Inconnu</option> <option … -
Add links to non-model items in Django admin
I have a few utility tools within my existing Django app, eg. a view which allows Django admin users to send an email to users, or generate embed codes for external websites, etc. I want to add links to these tools to the Django admin index – what's the best way to go about this? I know I can override the admin index template and (presumably) manually add a list of URLs, but this doesn't feel very "Django". The URLs for these utilities live in my app's urls.py – should I try extracting them out into their own app somehow? I really just want to add a box like the one shown here, which links to three or four URLs – there must be a way! -
Django makemigration breaks when model query is run in form - Why?
I am using Django 3.2 I want to populate a form select field as follows: from .models import Post, BlogPostSubscriber, PostCategory # This causes makemigrations to break !!! # categories = [x for x in PostCategory.objects.all().order_by('slug').values_list('name', 'name')] categories = [('',''),] class PostForm(forms.ModelForm): class Meta: model = Post fields = ['category', 'title', 'content','tags'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-control input'}), 'category': forms.Select(choices=categories, attrs={'class': 'form-control input'}), 'content': forms.Textarea(attrs={'class': 'form-control editable medium-editor-textarea'}), 'tags': forms.TextInput(attrs={'class': 'form-control input'}), } When I run python manage.py makemigrations, I get the following error: Relation blog_postcategory does not exist Why? and how do I fix this error? -
How to query a char field with regular expression?
I have a charField called 'blood_pressure' and it has values like 120/80, 110/70 and so on. I need to query the values by only the denominator value and regardless of the Numerator. I tried: Muserments.objects.filter(blood_pressure=r'/d+\/20') My goal I need to get the object with a denominator greater than \d+>=80 Muserments.objects.filter(blood_pressure=r'\d+\/\d+>=80') -
How to correctly display multi level data
I have a model MyModel which contains data with various levels. The goal is to display the data in a treegrid /treetable. Model: class MyModel(models.Model): title = models.CharField(max_length=100) level = models.IntegerField() price = models.FloatField(null=True, blank=True) parent = models.ForeignKey("self", on_delete=models.PROTECT, blank=True, null=True) Serializer: class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('title', 'level', 'price', 'parent') depth = 5 Viewset: class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer The data: [ { "title": "First A", "level": 0, "price": 111.1, "parent": null }, { "title": "Second A", "level": 1, "price": 222.2, "parent": 1 }, { "title": "Third A", "level": 2, "price": 333.42, "parent": 2 }, { "title": "Fourth A", "level": 3, "price": 444.1, "parent": 3 }, { "title": "Fifth A", "level": 4, "price": 33.442, "parent": 4 }, { "title": "First B", "level": 0, "price": 321.0, "parent": null }, { "title": "Second B", "level": 1, "price": 1234.0, "parent": 6 }, { "title": "Third B", "level": 2, "price": 4335.0, "parent": 7 } ] I have followed [this][1] post, but I don't received the data that I want. The following output is received after calling the current viewset: [ { "title": "First A", "level": 0, "price": 111.1, "parent": null }, { "title": "Second A", "level": … -
How to create tasks correctly in Celery with Django?
I ask for help with the task. There is a notification model. I want to create an asynchronous task for creating notifications. But I get an error Object of type MPTTModelBase is not JSON serializable. models.py class Comment(MPTTModel): """Модель комментариев""" content_type = models.ForeignKey(ContentType, verbose_name=_('Тип контента'), related_name='content_ct_%(class)s', on_delete=models.CASCADE) object_id = models.PositiveIntegerField(verbose_name=_('ID контента'), db_index=True) content_object = GenericForeignKey('content_type', 'object_id') """Род.коммент""" parent = TreeForeignKey('self', on_delete=models.CASCADE, verbose_name=_('Родительский комментарий'), blank=True, null=True, related_name='children') """Инфо, привязка, модерация""" content = models.TextField(verbose_name=_('Комментарий')) created_by = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='comment_created_by', verbose_name=_('Автор комментария')) is_published = models.BooleanField(verbose_name=_('Опубликовать'), default=True) time_create = models.DateTimeField(auto_now_add=True, verbose_name=_('Дата добавления')) """Generic FK""" rating = GenericRelation('Rating', related_query_name='%(class)s') notification = GenericRelation('Notification', related_query_name='%(class)s') def save(self, *args, **kwargs): send_create_notification.delay(self, 3) super().save(*args, **kwargs) services.py def create_notification(instance, type): """Notification create""" from modules.core.models import Notification model_object = instance obj = model_object.content_object try: text = model_object.content[0:120] except: text = None try: to_user = obj.created_by except: to_user = obj from_user = model_object.created_by now = timezone.now() last_minute = now - datetime.timedelta(seconds=60) similar_actions = Notification.objects.filter(from_user=from_user, to_user=from_user, type=type, time_create__gte=last_minute) if obj: from django.contrib.contenttypes.models import ContentType content_type = ContentType.objects.get_for_model(obj) similar_actions = similar_actions.filter(content_type=content_type, object_id=obj.id) if not similar_actions: if text: notification = Notification(from_user=from_user, to_user=to_user, type=type, content_object=obj, text=text) else: notification = Notification(from_user=from_user, to_user=to_user, type=type, content_object=obj) notification.save() return True return False tasks.py @shared_task() def send_create_notification(self, type): return create_notification(self, type) -
why changing my language is not working on django
I'm trying to change my language from french (the default langauge of my web navigator and my app) to the english language. LANGUAGES= [ ('fr', 'French'), ('en', 'English'), ] Here is my form to change the language, I found it on the documentation <form action="{% url 'set_language' %}" method ="post"> {% csrf_token %} <input type="hidden" name="next" value ="{{ redirect_to }}"> <select name="language" id=""> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages%} <option value="{{ langauge.code }}" {% if language.code == LANGUAGE_CODE %} selected {% endif %}> {{language.name_local}} ({{language.code}}) </option> {% endfor %} </select> <input type = "submit" value="Go"> </form> Here is my urls pattern urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), path('mission/',include('mission.urls')), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), url(r'^favicon\.ico$', RedirectView.as_view(url='/static/images/favicon.ico')) ] at my views.py code I add this def index(request): from django.utils import translation #user_language = 'en' #translation.activate(user_language) #request.session[translation.LANGUAGE_SESSION_KEY] = user_language if translation.LANGUAGE_SESSION_KEY in request.session: del request.session[translation.LANGUAGE_SESSION_KEY] return render(request, 'mission/index.html', {}) But whene I try this in my views.py code to change the language manually it works user_language = 'en' translation.activate(user_language) request.session[translation.LANGUAGE_SESSION_KEY] = user_language I think the problem is on the fucntion set_langauge It is predifned on a file named i18n.py but i'm not sure -
Pass values from views.py for-loop to template in Django
I have a "Meeting room booking" system in my project,and here is my html: Here is the "views.py" I have written: def meeting(request): today = datetime.now().date() today2 = today + timedelta(days=1) today3 = today + timedelta(days=2) today4 = today + timedelta(days=3) today5 = today + timedelta(days=4) today6 = today + timedelta(days=5) today7 = today + timedelta(days=6) date_dict = {str(today): "today", str(today2): "today2", str(today3): "today3", str(today4): "today4", str(today5): "today5", str(today6): "today6", str(today7): "today7"} book_list = Booking.objects.filter(booking_date__gte=today).filter(is_deleted='0') booking = [] htmls = "" for day in date_dict: htmls += '<tr><td><a id="{}"></a></td>'.format(date_dict[day]) for time_choice in ["10:00~12:00", "12:00~14:00", "14:00~16:00", "16:00~18:00", "18:00~20:00", "20:00~22:00"]: book = None flag = False for book in book_list: if book.time_id == time_choice and book.booking_date == day: flag = True break if flag: if book.user == request.user.username: htmls += '<td><button type="button" class="btn btn-warning" data-toggle="modal" data-target="#modal-warning" onclick="RunAlg(this)" user-id="{}" theme-id="{}">You Booked</button></td>'.format(book.user, book.theme) booking.append(book.theme) print(booking) else: htmls += "<td bgcolor='#0088ff' class='info item'>Booker:{}<br>Meeting theme:{}</td>".format(book.user, book.theme) else: htmls += '<td><button type="button" class="btn btn-success" data-toggle="modal" data-target="#booking-success" onclick="RunAlg(this)">Bookable</button></td>' htmls += "</tr>" return render_to_response('meeting.html', {'htmls': htmls, 'booking': booking}) And here is my template part about modal: <div class="modal fade" id="modal-warning"> <div class="modal-dialog"> <div class="modal-content bg-warning"> <div class="modal-header"> <h4 class="modal-title">You booked this meeting room</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span …