Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rendering fields from separate apps in django
I have my main app, and a tags app, I have added the tags to my blogpost model and have made sure I have added them in the back end. My problem is getting them to render. My current code: MODEL class BlogPost(models.Model): tags = models.ManyToManyField(Tag, related_name='blog_posts', blank=True) class Tag(models.Model): label = models.CharField(max_length=255) def __str__(self) -> str: return self.label class TaggedItem(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveBigIntegerField() content_object = GenericForeignKey() VIEW def Blog(request): posts = BlogPost.objects.filter(date__lte=timezone.now()).order_by('-date') blog_paginator = Paginator(posts, per_page=4) page_number = request.GET.get('page') page = blog_paginator.get_page(page_number) tags = [] for post in posts: post_tags = post.tags.all() tags.extend(post_tags) context = { 'posts': posts, 'tags': tags, 'page': page, } return render(request, 'mhpapp/blog.html', context) HTML {% for post in page.object_list %} {% if post.published %} <span> {% for tag in tags %} {% if tag in post.tags.all %} {{ tag.label }} {% endif %} {% endfor %} </span> {% endif %} {% endfor %} -
How to create a discord bot that changes user role with django rest framework?
Im using React in the frontend to make a post request to my REST API in drf. The body of the post request sends the discord_userId. I have this code that runs perfeclty outside my drf application. @bot.slash_command(name="changerole", guild_ids=[DISCORD_CHANNEL], pass_context=True) async def changerole(ctx): member = ctx.author role = get(member.guild.roles, name="Human") await member.add_roles(role) await ctx.send(f"{member.name} has been giving a role called: {role.name}") bot.run(DISCORD_TOKEN) However I want to receive discord_userId in my request and execute the code above inside my drf application I tried this in my views.py from .utils.discord_utils import changerole class VerifyMembershipDiscord(generics.GenericAPIView): def post(self, request): changerole(request.data["discordId"]) return Response({"error": "false", "message": "ok"}, status=status.HTTP_200_OK) my change role function is import discord from discord.utils import get bot = discord.Bot() # Create a new role and assign it to the specified user ID @bot.slash_command(name="changerole", pass_context=True) async def changerole(ctx, user_id: int): guild = bot.get_guild('my_guild_id') member = guild.get_member(user_id) role = get(member.guild.roles, name="Human") await member.add_roles(role) await ctx.send(f"{member.name} has been giving a role called: {role.name}") bot.run(TOKEN) But this raises an error saying: File "/Users/.pyenv/versions/3.10.9/lib/python3.10/asyncio/events.py", line 671, in get_event_loop raise RuntimeError('There is no current event loop in thread %r.' RuntimeError: There is no current event loop in thread 'django-main-thread'. What can I do? -
Django Button Behavior within View that Handles POST and GET Requests
I've implemented the code on the site at the link below. I'm trying to understand what is happening with the log_message view. I understand that the view below handles both POST and GET requests. Note, in the template that this log_message calls (log_message.html), there is a form string/char field called message and a button to log the message. Django and VSCode So, on the first call to this view (view.log_message), the first if is passed and the render function is called where it passes the form to the template. The template contains a message field and log button. I insert some text into the message form, and then press the log button. While doing this in VSCode debugger, i notice that when i press the log button, the control is sent back to the start of the log_message function, but this time request.method=='POST'. There seems to be some underlying behavior that when the button is pressed it reloads the page and thus calls the log_message view again? But that doesn't seem very transparent in the code. Can someone explain what's going on here? def log_message(request): form = LogMessageForm(request.POST or None) if request.method == "POST": if form.is_valid(): message = form.save(commit=False) message.log_date … -
Get FK of previous formset and pass into the Next one
I'm Working on a project and i'm trying to make a product variation, I have a Product, a Color Variation (FK=Product) and a Size Variation (FK=Color Variation) I'm using inline formsets to acomplished that, but when i save more then one Color Variation, i get error saying that get() returned 2 objects. On my CreateView form_valid, first i save the product, then i loop into the variants and inside this loop i made another loop to save the sizes. So for example, if i have Color Red, it will save, then loop to all the sizes that belong to color red and save, and after will check for another Color variation.But this only works when i have only 1 color variation How can i get the fk of the variation that is beeing looped and pass to the size ? Here are my CreateView: def get_context_data(self, **kwargs): ctx = super(ProductCreate, self).get_context_data(**kwargs) if self.request.POST: ctx['variants'] = VariantFormSet(self.request.POST or None, self.request.FILES or None, prefix='variants') ctx['sizes'] = SizeFormSet(self.request.POST or None, self.request.FILES or None, prefix='sizes') else: ctx['variants'] = VariantFormSet(prefix='variants') ctx['sizes'] = SizeFormSet(prefix='sizes') return ctx def form_valid(self, form): form.instance.vendor = get_vendor(self.request) form.instance.product_slug = slugify(form.instance.product_name) context = self.get_context_data() variants = context['variants'] sizes = context['sizes'] with transaction.atomic(): … -
how to add a field for choose a directory in django model?
I need a field to specify the path of my backup file and I write this model: def backup_path(): return os.path.join(settings.BASE_DIR.parent, "backups") class Backup(Authorable, Publishable, models.Model): file_path = models.FilePathField( _("مسیر فایل"), path=backup_path, recursive=True, ) file_size = models.CharField(verbose_name=_("حجم فایل"), max_length=255, null=True, blank=True) class Meta: verbose_name = _("تهیه پشتیبان") verbose_name_plural = _("تهیه پشتیبان") def __str__(self): return f"{self.id} - {self.file_path} - {self.file_size}" def save(self, **kwargs): BackupService.run(self.file_path) return super().save(**kwargs) but in admin panel I can't choose a directory for save backup file. how can i choose a directory in admin? -
Django - Use postgres unaccent with django-filters library
I have a Django app that uses postgres. I know that if i have the unaccent extension from postgres installed in the database, I can use like it's described in the docs to apply filters ignoring the accents in the words: >>> City.objects.filter(name__unaccent="México") ['<City: Mexico>'] >>> User.objects.filter(first_name__unaccent__startswith="Jerem") ['<User: Jeremy>', '<User: Jérémy>', '<User: Jérémie>', '<User: Jeremie>'] In this app I'm also using the django-filter library. I was wondering if there is a way to use the unaccent extension in conjunction with django-filter to avoid rewriting all my search functions. Here is an example of the code used to filter: class BranchsFilter(django_filters.FilterSet): name = CharFilter( label='Filial', label_suffix='', field_name='name', lookup_expr='icontains', ) class Meta: model = Branchs fields = '__all__' Appreciate the help. -
how can i display data from a model that has a foreinkey relationship
I have a django shop model and a command model who has a foreinkey relationship to the model shop class Shop(models.Model): name= models.CharField(max_length=60, verbose_name='nom') adress= models.CharField(max_length=250, verbose_name='adresse') description=models.TextField(max_length=1000) logo=models.ImageField( blank= True ,null=True ) horaire=models.CharField(max_length=100) user= models.ForeignKey(User, blank= True , null=True ,verbose_name="utilisateur", on_delete=models.CASCADE) date= models.DateTimeField(auto_now_add=True, verbose_name='date de création') data=models.JSONField(null=True,blank=True) def __str__(self) -> str: return str(self.name) class Command(models.Model): class Status(models.TextChoices): PENDING = "PENDING" REJECTED = "REJECTED" CANCELED = "CANCELED" PROCESSING = "PROCESSING" READY = "READY" DELIVERED = "DELIVERED" user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) cart = models.ForeignKey( Cart, verbose_name="panier", on_delete=models.CASCADE) type = models.CharField(max_length=50) data = models.JSONField(null=True, blank=True) date = models.DateTimeField(auto_now_add=True) status = models.CharField( max_length=20, choices=Status.choices, default="PENDING") shop= models.ForeignKey(Shop, null=True , blank=True, verbose_name="boutique", on_delete=models.CASCADE) email = models.EmailField(max_length=50, null=True) phone = models.CharField(max_length=60) name = models.CharField(max_length=30) company = models.CharField(max_length=50, default='') address = models.CharField(max_length=100, default='') appartement = models.CharField(max_length=100, default='', null=True, blank=True) city = models.CharField(max_length=50, default='') country = models.CharField(max_length=50, default='') # payment = models.ForeignKey(Payment, verbose_name="Payment", on_delete=models.CASCADE) note = models.TextField(default='', null=True) home_delivery = models.BooleanField(default=False) def __str__(self): return str(self.user) or 'Anomyne' I want to display the order data and save when placing an order ,all give show except foreignkey part for model shop. how to manage to display this so that each order can then have a specific shop because … -
How to specify Django UniqueConstraint for GeoDjango PointField to prevent duplicate points within some tolerance
I'd like to ensure that users cannot enter duplicate coordinates in my database (stored as a geodjango PointField). Django's UniqueConstraint feature permits this, but to my knowledge only excludes exact matches. It would be more useful to prevent coordinates being within some tolerance (e.g. 1m) of one another. Is there an easy way of achieving this with UniqueConstraint? Or if not, what is the best approach? E.g. perhaps writing some custom SQL for BaseConstraint? -
Django queryset for near by vendors by their delivery_target using geolocation
Good afternoon. I don't have much experience with querysets and I'm writing a Django app and I'm having trouble resolving an impasse. In this app, I wanted users to determine the distance of the stores to be shown based on a given radius: top_vendors = Vendor.objects.filter(user_profile__location__distance_lte=(pnt, D(km=RADIUS))).annotate(distance=Distance("user_profile__location", pnt)).order_by("distance") I then created a vendor field to give the vendor a RADIUS delivery so they can limit the distance they can deliver. vendor_max_delivery_distance = models.PositiveIntegerField(default=0) I would like some help to add one more condition to the queryset which would be to limit the list of vendors to the distance established by the user matched with the distance that the vendor can deliver. It's inside RADIUS (already done in top_vendors code) In addition to being within the RADIUS defined by the user, the vendor_max_delivery_distance also meets within this RADIUS. Item number two is driving me crazy from trying to find a solution. If anyone has experience and can help me I would be very grateful! Thank you very much. -
Create Django admin action to save a list of selected objects to another table
I am working on a bjj tournament app. It would take competitors' registration: Name, weight, and rank. I was able to set up the form and save the information into the admin panel. How to create an "action" in the admin panel to allow the admin to choose and create separate groups from the existing table? For example: Eric C - 180 - W Donny W - 160 - B Banaa O - 150 - B Claudi B - 145 - P Nikki R - 160 - B Jordan M - 175 - B How to create an action that let me choose 1,2,4 into a Group 1 (another table in the database) and 3,5 into group 2, and 6 into group 3. Thanks, ChatGPT suggested this but it didn't work """def create_group(modeladmin, request, queryset): # Get the name of the current table table_name = queryset.model._meta.db_table # Create other tables based on the current table with connection.cursor() as cursor: cursor.execute(f"CREATE TABLE {table_name}_other (id INT PRIMARY KEY);") cursor.execute(f"CREATE TABLE {table_name}_more (id INT PRIMARY KEY);") # Display a success message modeladmin.message_user(request, f"Created other tables based on {table_name}.") class MyModelAdmin(admin.ModelAdmin): actions = [create_group] admin.site.unregister(Competitors) admin.site.register(Competitors, MyModelAdmin) """ -
Create custom user model using django with customized fields with authentication
I want to create a user model with two fields (username, code) both are cahrfield with no more other fields just these two and I want to Authenticate this model everytime I create one that is all I would be thankful if you help me🙏🏻 -
Django form error "this field is required" after HTMX request
I'm using HTMX lib to send the requests with Django. The issue is that after succeed htmx request with project_form swapped project_detail_form comes with "this field is required". What am I doing wrong? This is my views.py: def index(request): """Index view.""" project_form = ProjectForm(data=request.POST or None) project_detail_form = ProjectDetailForm(data=request.POST or None) if request.method == "POST": try: if project_form.is_valid(): project_form.save() return render( request, "monitor/_project_detail_form.html", context={"project_detail_form": project_detail_form}, ) except Exception as e: return HttpResponse(f"Error: {e}") return render(request, "monitor/index.html", context={"project_form": project_form}) A part of index.html <form class="pt-4" hx-post="/" hx-target="this" hx-swap="innerHTML" enctype="multipart/form-data"> {% csrf_token %} {{ project_form.as_div }} <button class="btn btn-primary" type="submit">Save</button> </form> _project_detail_form.html {% csrf_token %} {{ project_detail_form.as_div }} <button class="btn btn-primary" type="submit">Save</button> forms.py class ProjectForm(forms.ModelForm): """Project form.""" name = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control"})) check_interval = forms.IntegerField( widget=forms.NumberInput(attrs={"class": "form-control"}) ) is_active = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={"class": "form-check"}) ) class Meta: """Meta.""" model = Project fields = "__all__" class ProjectDetailForm(forms.ModelForm): """Project Detail form.""" project = forms.ModelChoiceField( queryset=Project.objects.all(), widget=forms.Select(attrs={"class": "form-select"}), ) url = forms.URLField(widget=forms.URLInput(attrs={"class": "form-control"})) pagination = forms.IntegerField( required=False, widget=forms.NumberInput(attrs={"class": "form-control"}) ) is_active = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={"class": "form-check"}) ) class Meta: """Meta.""" model = ProjectDetail fields = ["project", "url", "pagination", "is_active"] -
duplicate key value violates unique constraint error in django in a many-to-one relationship
I'm trying to set-up a database in django, given the following relationships: class Team(BaseModel): class Meta: db_table = '"teams"' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(unique=True, null=False, blank=False, max_length=100) members = models.ManyToManyField(User, through='TeamMember', related_name='members', related_query_name='members') creator = models.ForeignKey(User, unique=False, null=True, on_delete=models.SET_NULL, related_name='created_teams', related_query_name='created_teams') team_admins = models.ManyToManyField(User, through='TeamAdmin', related_name='admin_teams', related_query_name='admin_teams') class User(AbstractUser): class Meta: db_table = '"users"' username = None email = models.EmailField(blank=False, unique=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] In essence, I want to set-up a many-to-one relationship between the class User and the class Team via "Creator". A Team can only have one Creator user, but a single user can be the Creator for multiple Teams. To do that, I'm using models.ForeignKey. However, whenever I try to create an additional team using the same user, I get the error: "duplicate key value violates unique constraint "teams_creator_id_key"". Is there something wrong with how I set up this many-to-one relationship? I've tried setting the ForeignKey definition with unique=False, removing that flag altogether, and nothing seems to work. As a sidenote, to create a new Team im using a serializer with the following code: def create(self, validated_data): user = User.objects.get(id=self.context['user_id']) team: Team = Team.objects.create( name = validated_data.get('name'), creator … -
How can you create a custom InlineEntityElementHandler in Wagtail CMS?
I'm trying to create a custom rich text feature which mimics the behaviour of richtext's link feature. The only differences are another name, and adding a class to it. Because we need two different types of links in the frontend (Headless setup). And it's essential that we have the Link Chooser interface (Page, external, email etc.). I tried the following, but now both Link handlers (built-in and custom) have the "arrow" class: @hooks.register('register_rich_text_features') def register_arrow_link(features): feature_name = 'arrow' type_ = 'LINK' tag = 'a class="arrow"' control = { 'type': type_, 'label': '->', 'description': 'Arrow Link', } features.register_editor_plugin( 'draftail', feature_name, draftail_features.EntityFeature(control) ) db_conversion = { 'from_database_format': {tag: InlineEntityElementHandler(type_)}, 'to_database_format': {'entity_decorators': {type_: tag}} } features.register_converter_rule('contentstate', feature_name, db_conversion) features.default_features.append(feature_name) -
.gitignore file in django
i should do a push of my small project in django/redis and python on github but i noticed that after creating some users and doing the push, they are also saved on github. Reading on the internet I should create a gitignore file but I don't know what to write in it. I should obviously save the migrations but not the data that has been entered in the database. i found a file on gitignore.io but i am not sure if everything in it fits my case. do you have any tips or sites where i can check this? -
How can the carriage return \r\n in a text which is put in an HTML cell with Django be interpret as carriage return and not present the \r\n?
I have as input a text block with several lines separated by \r\n. I'm extracting the information with Django and putting into a model as TextField, e.g. info = models.TextField() b'Hey\r\n\r\nIn regards to your letter sent ...' Inside a Django template I put the text into an HTML cell {{ letter.info }} When the HTML table is presented, the text is shown as one line with the \r\n visible as part of text. Is there a way to make that the text is presented in different lines? i.e. that the \r\n are interpreted as the carriage return and not presented raw? I've tried some suggestions I found for similar questions, as using style="white-space: break-space" pre-line; pre-wrap but that did not work. I've also tried to replace the \r\n with <br/>, but the raw is presented instead and the line is not broken. -
Send StreamingHttpResponse in django channels
Exception inside application: 'StreamingHttpResponse' object has no attribute 'encode' Traceback (most recent call last): File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\django\contrib\staticfiles\handlers.py", line 101, in __call__ return await self.application(scope, receive, send) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\routing.py", line 62, in __call__ return await application(scope, receive, send) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\middleware.py", line 24, in __call__ return await self.inner(scope, receive, send) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\routing.py", line 116, in __call__ return await application( File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\consumer.py", line 94, in app return await consumer(scope, receive, send) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\consumer.py", line 58, in __call__ await await_many_dispatch( File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\utils.py", line 50, in await_many_dispatch await dispatch(result) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\consumer.py", line 73, in dispatch await handler(message) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\generic\websocket.py", line 194, in websocket_receive await self.receive(text_data=message["text"]) File "C:\Users\Tamerlan\Desktop\chatbot_project\chatbot_app\consumers.py", line 28, in receive await self.send(text_data=response) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\generic\websocket.py", line 209, in send await super().send({"type": "websocket.send", "text": text_data}) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\consumer.py", line 81, in send await self.base_send(message) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\sessions.py", line 226, in send return await self.real_send(message) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\daphne\server.py", line 240, in handle_reply protocol.handle_reply(message) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\daphne\ws_protocol.py", line 202, in handle_reply self.serverSend(message["text"], False) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\daphne\ws_protocol.py", line 256, in serverSend self.sendMessage(content.encode("utf8"), binary) AttributeError: 'StreamingHttpResponse' object has no attribute 'encode' I … -
Creating a Django project on an existing empty git repository
I'm pretty much new at programming using Mac, Django, Python and PyCharm. I wanted to create my first project and ran into the following problem: For this project I want to use Python 3.7, so I installed it into my Mac using pyenv install 3.7 And set a virtual environment with this line: pyenv virtualenv 3.7.16 python-3.7 Then, for the project I got an empty git repository and cloned it into my /opt/ folder. I opened it with Pycharm and it appears to be empty, just as expected. Then, I went to Files >> New Project, selected Django project and set the location of the project to the folder created during the clone, so the path is /opt/my-first-project. Then, I set the interpreter to be the environment previously created. I get this warning on screen that says Project name should only contain letters, numbers and underscores. For the tests I've done, I guessed this refers to the name of the folder, my-first-project in this case. This is the name of the git repository, and since I'm not the owner of the repository I cannot change that name. How should I create a new Django project inside this repository? -
Exception in logging module itself is not sent to sentry
Django app on python 2 (yeah I know). The sentry integration is working well otherwise, but looks like it doesn't record crashes in logging itself, for instance when passing insufficient arguments to logger.info(). In this case the incriminating line was something like: logger.info('some info about %s and %s', my_thing) i.e. missing an argument. This traceback showed up in heroku logs but nothing in sentry: Apr 27 23:35:32 xxx app/web.9 Traceback (most recent call last): Apr 27 23:35:32 xxx app/web.9 File "/usr/local/lib/python2.7/logging/__init__.py", line 868, in emit Apr 27 23:35:32 xxx app/web.9 msg = self.format(record) Apr 27 23:35:32 xxx app/web.9 File "/usr/local/lib/python2.7/logging/__init__.py", line 741, in format Apr 27 23:35:32 xxx app/web.9 return fmt.format(record) Apr 27 23:35:32 xxx app/web.9 File "/usr/local/lib/python2.7/logging/__init__.py", line 465, in format Apr 27 23:35:32 xxx app/web.9 record.message = record.getMessage() Apr 27 23:35:32 xxx app/web.9 File "/usr/local/lib/python2.7/logging/__init__.py", line 329, in getMessage Apr 27 23:35:32 xxx app/web.9 msg = msg % self.args Apr 27 23:35:32 xxx app/web.9 TypeError: not enough arguments for format string Apr 27 23:35:32 xxx app/web.9 Logged from file models.py, line 18407 Do I need to do something for sentry_sdk to include whatever context the logging module is running in as well? -
Using django-tinymce with django-filebrowser to upload images to a blog post
I am implementing django-tinymce together with django-filebrowser to be able to include media files in the text editor of a blog. Everything seems to be working fine, but when I click on the image button in the text editor, the dialog box doesn't include a button to upload a file. I have gone through the threads on this topic in the forum but cannot find a solution to solve it. These are the settings: INSTALLED_APPS = [ # file-browser 'grappelli', 'filebrowser', ... 'tinymce', ...] STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / 'static'] STATIC_ROOT = BASE_DIR / 'staticfiles' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' #django-filebrowser: # Path to filebrowser static files FILEBROWSER_DIRECTORY = 'filebrowser/' FILEBROWSER_STATIC_URL = STATIC_URL + 'filebrowser/' FILEBROWSER_MEDIA_ROOT = BASE_DIR / 'media/uploads/' FILEBROWSER_MEDIA_URL = '/filebrowser/media/' FILEBROWSER_SORT_BY = 'date' FILEBROWSER_MAX_UPLOAD_SIZE = 10485760 # 10 MB EXTENSIONS = { 'Image': ['.jpg','.jpeg','.gif','.png','.tif','.tiff'], 'Video': ['.mov','.wmv','.mpeg','.mpg','.avi','.rm'], 'Audio': ['.mp3','.mp4','.wav','.aiff','.midi','.m4p'], 'Document': ['.pdf','.doc','.rtf','.txt','.xls','.csv','.docx','.xlsx'] } SELECT_FORMATS = { 'File': ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'zip', 'rar', 'tar', 'gz', 'bz2', 'csv'], 'Image': ['jpg', 'jpeg', 'png', 'gif', 'tif', 'tiff'], 'Video': ['swf', 'flv', 'mpg', 'mpeg', 'mp4', 'mov', 'avi', 'wmv'], } #django-tinymce TINYMCE_JS_URL = 'https://cdn.tiny.cloud/1/{api-key}/tinymce/5/tinymce.min.js?referrerpolicy=origin' TINYMCE_DEFAULT_CONFIG = { "theme": "silver", "height": 500, "menubar": True, "plugins": "advlist,autolink,lists,link,image,charmap,print,preview,anchor,searchreplace,visualblocks,code,fullscreen,insertdatetime,media,table,paste,code,help,wordcount," "searchreplace,visualblocks,code,fullscreen,insertdatetime,media,table,paste," … -
Django not showing messages after redirect
I'm using Django 4.0.9, and I'm trying to show a message using django-messages after a user has been created and after it has been deleted. Using prints I can see that the messages get created when the create/delete form executes, but when the messages are printed after the redirect to the homepage they don't exist in the Django system anymore. The interesting part is that if I set the setting DEBUG = True to my 'settings.py' everything works as intended, if DEBUG = False I get the error mentioned above. I'm not sure if the DEBUG setting deletes the cache, doesn't take the messages after the redirect or anything of that kind. This is my view when the user is deleted: from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib.auth import logout from django.contrib import messages from .models import User from .forms import DeleteUser def delete_user_view(request): if request.user.is_authenticated: if request.method == 'POST': form = DeleteUser(request.POST) if form.is_valid(): if request.POST["delete_checkbox"]: rem = User.objects.get(username=request.user) if rem is not None: rem.delete() logout(request) messages.info(request, "Il tuo account è stato cancellato.") # This is the print that let's me see the messages BEFORE the redirect allMsg = messages.get_messages(request) print('---------------- START MSG DELETE USER … -
Python djnago coverage : The name "coverage" is not recognized as the name of the cmdlet
I'm using python 3.10, django 4, windows 10, when I type into the console, coverage report outputs an error coverage : The name "coverage" is not recognized as the name of a cmdlet, function, script file, or executable program. Check the spelling of the name, as well as the presence and correctness of the path, and then try again. line:1 sign:1 coverage CategoryInfo : ObjectNotFound: (coverage:String) [], CommandNotFoundException FullyQualifiedErrorId : CommandNotFoundException coverage I have installed I tried to install coverage via pip and through the pychrm interface I tried to enter python coverage but nothing helped -
Website can not fetch from the Django API when secured with HTTPS [closed]
My React.js website is hosted by IONOS company, together with a domain name. It fetches data from a Django REST Framework API, hosted on a virtual server at another address (it fetches through an IP address, the virtual server is not associated with a domain name). The API is run with Gunicorn and Supervisor. Everything works perfectly when the website is not secured. But as soon as I configure the web server of the website to use HTTPS, the website can not fetch from the API anymore : it gets “Connection refused” responses. What should I do to enable the HTTPS website to fetch my Django API ? I’ve been searching for a while, found suggestions to enable connections from a front-end to a back-end, but nothing to deal with requests from web browsers using HTTPS. Help required, thanks ! -
How should we do order_by in Django ORM for self-referred sub objects?
Have an issue with a somewhat problematic ordering/sorting in Django ORM. What I have is a Venue with a FK to self, thus the potential for sub-venues: # models.py class Venue(models.Model): company = models.ForeignKey(to="Company", related_name="venues", on_delete=models.CASCADE) parent = models.ForeignKey( to="self", related_name="children", on_delete=models.CASCADE, null=True, blank=True ) ordering = models.PositiveSmallIntegerField(default=0) # ... This is how it looks like in the custom dashboard we've built. We're doing something akin to: Venue.objects.filter(parent__isnull=True) and then, for each venue, we're doing obj.children.all(), thus creating this layout: # find all parent=None, then loop over all obj.children.all() Spain (ordering=0, parent=None) - Barcelona (ordering=0, parent="Spain") - Castelldefels (ordering=1, parent="Spain") - Girona (ordering=2, parent="Spain") Singapore (ordering=1, parent=None) This is what we want to see when requesting our API endpoint: // json response [ {"venue": "Spain", "ordering": 0}, {"venue": "Barcelona", "ordering": 0}, {"venue": "Castelldefels", "ordering": 1}, {"venue": "Girona", "ordering": 2}, {"venue": "Singapore", "ordering": 1} ] Problem is when we're calling the API, is that we're also using django-filters in our ModelViewSet thus we can't filter on parent__isnull=True or we won't see the children in the API response. We still have access to the queryset in the def list-method before returning it to the serializer. Question is: how do we set the … -
encoding password in django
Why isn't the password received from the user during registration coded and encrypted in the database in the Django framework? Why isn't the password received from the user during registration coded and encrypted in the database in the Django framework