Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I load image from Django REST API?
So as stated, I'm having trouble loading images from Django backend(fetch works fine). I've looked other similar questions, but NONE OF THEM HELPED, sadly. So here's my Django code: settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) model.py class Content(models.Model): objects = models.Manager() image = models.ImageField(upload_to='None', height_field=None, width_field=None, max_length=None, null=True, blank=True) key_line = models.CharField(max_length = 100, null=True) ### All 페이지에 보여지는 핵심 문장 body = models.TextField(blank=True, null=True) ### 발췌 내용 I've uploaded an image named 'eeee.PNG', and I can see the data serialized in JSON format like below: [ { "id": 5, "image": "/media/None/eeee.PNG", "key_line": "key.", "body": "blablabla", }, ] And my React code (fetch has been successfully worked) : <Container classname=""> <Row className=""> <Col className="text-text img-eachcake">{this.props.image}</Col> <Col className="text-text img-eachcake" src={this.porps.image}></Col> </Row> </Container> As you can see, I've tried two ways but none of them worked. What do you think is the problem? All the other props are loaded fine. It's just the image file that doesn't work. +in the inspection mode > Elements, I see the line as : <div src="/media/None/eeee.PNG" class="text-text img-eachcake col"></div> -
Pagination feature not working and paginator bar styling is off
I have two bugs in my code, First bug is a styling bug or frontend bug, Second bug is Pagination not working. The second bug is I'm trying to make the button active depending on what page it is, The button only lights up for page 1, When I go to page 2 the button is still active or lit up. The first bug for styling is the buttons were meant to look like this: but they look like this: Current code: <div class="row"> <div class="col-md-12"> {% if listings.has_other_pages %} <ul class="pagination"> {% if listings.has_previous %} <li class="page-item"> <a href="?page={{listings.previous_page_number}}" class="page-link">&laquo;</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link">&laquo;</a> </li> {% endif %} </ul> {% endif %} {% for i in listings.paginator.page_range %} {% if listings.number == i %} <li class="page-item active"> <a class="page-link page-item">{{ i }}</a> </li> {% else %} <li class="page-item"> <a href="?page{{i}}" class="page-link">{{i}}</a> </li> {% endif %} {% endfor %} </div> </div> Intended to look code <div class="row"> <div class="col-md-12"> <ul class="pagination"> <li class="page-item disabled"> <a class="page-link" href="#">&laquo;</a> </li> <li class="page-item active"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> <li class="page-item"> <a class="page-link" href="#">&raquo;</a> </li> </ul> </div> … -
How to temporary store a generated image for download
I have written some code for taking an image, and adding some text to it. Currently it just saves the file locally, but I would like it to store the new generated image temporary, so when the session is closed the file is deleted. Also, so in the future multiple users would be able to use the function at the same time, without one user owerwriting another ones image. My current code is: def Output(request): inputValue = request.GET.get('t', '') my_image = Image.open(os.path.join(BASE_DIR, 'media', 'blank.jpg')) title_font = ImageFont.truetype(os.path.join(BASE_DIR, 'homepage', 'static', 'homepage', 'Mistral.ttf'), 60) title_text = inputValue image_editable = ImageDraw.Draw(my_image) image_editable.text((45,333), title_text, (0, 0, 0), font=title_font) my_image.save(os.path.join(BASE_DIR, 'media', 'result.jpg')) return TemplateResponse(request, 'homepage/output.html', {'title': 'Output'}) so instead os saving the image locally as result.jpg, how do I save it temporary for a specific session? -
django channels redis took too long to shut down and was killed
so i was trying to do some basic stuff with channels. i wrote a script in my html to return a message script <script> const chatsocket = new WebSocket( 'ws://'+window.location.host+'/ws/test/' ) chatsocket.onmessage = function (e) { const data = JSON.parse(e.data) console.log(data) chatsocket.close() } </script> my consumers.py from channels.exceptions import StopConsumer from channels.generic.websocket import AsyncWebsocketConsumer import json class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): self.group_name = 'notificationgroup' await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() await self.channel_layer.group_send( self.group_name, { 'type': 'tester_message', 'tester': 'hello world' } ) async def tester_message(self, event): tester = event['tester'] await self.send(text_data=json.dumps({ 'tester': tester })) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.group_name, self.channel_name ) raise StopConsumer() so basically i get my desired output in the console... when i have CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer' } } but when i use an aws redis cluster (after installing channels-redis obviously) CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('aws redis endpoint', 6379)], }, }, } i get this error WebSocket HANDSHAKING /ws/test/ [127.0.0.1:51551] WebSocket DISCONNECT /ws/test/ [127.0.0.1:51551] Application instance <Task pending name='Task-4' coro=<StaticFilesWrapper.__call__() running at E:\intes\sync\shero\venv\lib\site-packages\channels\staticfiles.py:44> wait_for=<Future pending cb=[BaseSelectorEventLoop._sock_write_done(1216)(), <TaskWakeupMethWrapper object at 0x000001F7D5226C70>()]>> for connection <WebSocketProtocol client=['127.0.0.1', 51551] path=b'/ws/test/'> took too long to shut down and was killed. what … -
Error message on entering duplicate in django form
I am trying to avoid duplicate email in my website form . Till now I was able to do this: 1.Whenever I enter duplicate email, it navigate back to homepage and user is not saved{ In my case team is not joined}. 2.In admin page when I try to enter duplicate email , I get my error message of duplicate email address I want this message in my form too, but it navigates to homepage. This is my model in models.py: class Team(models.Model): username = models.CharField(max_length=100) email = models.EmailField(max_length=100,unique=True,error_messages={'unique':"Email already exists"}) contact=models.IntegerField(null=False,blank=False,default=1234567890) def __str__(self): return self.username This is my form in forms.py: class TeamMembers(forms.ModelForm): username = forms.CharField(required=True,max_length=100) email = forms.EmailField(required=True,max_length=100,error_messages={'unique':"Email already exists"}) contact=forms.IntegerField(required=True) class Meta: model=Team fields = ['username','email','contact'] This is my function in views.py class TeamMembers(forms.ModelForm): username = forms.CharField(required=True,max_length=100) email = forms.EmailField(required=True,max_length=100,error_messages={'unique':"Email already exists"}) contact=forms.IntegerField(required=True) class Meta: model=Team fields = ['username','email','contact'] This is my join_team.html {% extends 'base.html' %} {%load crispy_forms_tags%} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join our team</legend> {{form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Join</button> </div> </form> </div> {% endblock content %} I want to display error message on form page instead of going to homepage. I … -
I need to show date in formatted (like a short date ) in django page
I need to show date in formatted (like a short date ) in django page . I changed in settings.py USE_L10N = False and DATE_FORMAT = '%y-%m-%d' DATE_FORMAT = 'Y-m-d' And in templates : <h2> Created at : {{ data.date|date:'Y-m-d'}}</h2> But , I get blank output (no date displayed) , I get it when I print onlt data.date but in the following format : 2021-02-10T16:48:04.401985Z I need a cleaner format . my models.py : date = models.DateTimeField(default=now, editable=False) -
Why in an AllowAny view of Django I get 401 Unauthorized using Firefox but not using Edge or Postman?
I'm using knox LoginView to make the login of my backend. This is the code of the view: class Login(LoginView): permission_classes = (AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(Login, self).post(request, format=None) When I execute my frontend (developed with angular) and try to login using Microsoft Edge everything works fine. I get the token and save it in local. Same result if I execute a POST using Postman. But, If I try to do the same using Firefox I receive 401 Unauthorized with this JSON: {"detail":"Invalid token."} Why does it ask for a token if its an AllowAny view? Why does it work in Edge and Postman but not in Firefox? More data: This is the authentication class in settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'knox.auth.TokenAuthentication', ), } EDIT: Actually, it works usign Firefox Developer Edition. -
Triggers are not being created in django-transitions
I am trying to build a basic implementation of django-transitions following the example here. It seems to me that I did everything in line with the example. When I create an instance of my model, however (and even of just the defined mixin itself), there are no triggers. I'm at a loss at what I may have done wrong and why that leads to triggers not being created. Can anyone confirm/help? Here is my workflow definition (lifecycles.py): from django_transitions.workflow import StatusBase, StateMachineMixinBase from transitions import Machine class ContactLifecycleStatus(StatusBase): # Define states ACTIVE = "ACTIVE" INACTIVE = "INACTIVE" BLOCKED = "BLOCKED" # Define human-readable labels for states # TODO: translate labels STATE_CHOICES = ( (ACTIVE, "active"), (INACTIVE, "inactive"), (BLOCKED, "blocked"), ) # Define transitions as constants ACTIVATE = "activate" DEACTIVATE = "deactivate" BLOCK = "block" UNBLOCK = "unblock" # Define human-readable label and css class for use in Django admin # TODO: translate labels TRANSITION_LABELS = { ACTIVATE: {'label': 'Activate', 'cssclass': 'default'}, DEACTIVATE: {'label': 'Deactivate'}, BLOCK: {'label': 'Block', 'cssclass': 'deletelink'}, UNBLOCK: {'label': 'Unblock', 'cssclass': 'default'}, } # define collection of states for machine SM_STATES = [ACTIVE, INACTIVE, BLOCKED,] # define initial state for machine SM_INITIAL_STATE = ACTIVE # define transitions as … -
Django - how do create a model right after User creating form?
So I'm working on this school managing system and I would like to make a signup form, that not only create User, but also create an object with one-to-one link to user. I've tried dozens of options, and still nothing is working. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) teacher = models.BooleanField() forms.py class UserCreateForm(UserCreationForm): teacher = forms.BooleanField() class Meta: model = User fields = ('username', 'password1', 'password2, 'teacher') views.py class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy('accounts:login') template_name = 'signup.html' Do you have any ideas how can I do that? -
Django ModuleNotFoundError: No module named 'asgiref'
I have a Django service we are trying to schedule in conjunction with the main application that runs periodically to send automated emails via a batch script. The Django application itself starts up fine, but when I try running the batch script, I get the following traceback: Traceback (most recent call last): File "C:\Program Files\compuweather\compuweather\webapp\management\commands\send_all_clients.py", line 2, in <module> from django.core.management.base import BaseCommand File "C:\ProgramData\Anaconda3\lib\site-packages\django-3.2- py3.8.egg\django\core\management\__init__.py", line 13, in <module> from django.apps import apps File "C:\ProgramData\Anaconda3\lib\site-packages\django-3.2-py3.8.egg\django\apps\__init__.py", line 1, in <module> from .config import AppConfig File "C:\ProgramData\Anaconda3\lib\site-packages\django-3.2-py3.8.egg\django\apps\config.py", line 7, in <module> from django.utils.deprecation import RemovedInDjango41Warning File "C:\ProgramData\Anaconda3\lib\site-packages\django-3.2-py3.8.egg\django\utils\deprecation.py", line 5, in <module> from asgiref.sync import sync_to_async ModuleNotFoundError: No module named asgiref I find that odd considering I have the batch file set to run from an anaconda environment that has Asgiref installed. I can verify this with pip freeze. Here are the versions of the packages I'm using: asgiref==3.3.1 Django==3.1.6 I saw a similar issue here, that was due to the Django and asgiref packages being outdated. I've tried updating both asgiref and Django to the latest versions (those listed), but that also didn't help. My best guess after looking through the traceback is either something is trying to use a deprecated … -
STRIPE KEYS not being detected. Can someone tell me why? Thank you! Django [closed]
The stripe keys are not being detected correctly but I don't know where is wrong. It is programmed in Django. STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY, "sk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") STRIPE_PUBLIC_KEY = os.environ.get("STRIPE_PUBLIC_KEY", "pk_live_xxxxxxxxxxx") STRIPE_TEST_SECRET_KEY = STRIPE_SECRET_KEY STRIPE_TEST_PUBLIC_KEY = STRIPE_PUBLIC_KEY STRIPE_LIVE_MODE = False DJSTRIPE_WEBHOOK_SECRET = os.environ.get("STRIPE_WEBHOOK_SECRET") -
Django for loop only catching the last iteration on button click
I am building a Django movie app which makes use of the TMDB API. The way I have it set up currently is that I have a function in my main.js which is run when the page is loaded which makes the call to the API based on which media_id is clicked from the search results, which saves to local storage. This works fine in this regard. I implemented a review functionality where logged in users are able to leave reviews on whichever title they wish and it saves to the DB, and then on the user account page I have a list displayed of all the reviews a logged in user has left. Up till here everything works as intended but this is where my error lies. Next to each review in the users account page I have a button I want to take the user to the page in which they left the review, however I can only seem to get it to link me to the final title in the list of reviews. The code I have in my account.html file is as follows: <tbody> {% for review in reviews %} <script type="text/javascript"> function resetValues() { localStorage.setItem('movieId', … -
OSError: [WinError 127] The specified procedure could not be found
Context: I've been trying to create a spatial database for a geolocation-based app using GEOS/GIS/GDAL. First I had an issue saying windows could not find GDAL, so I followed these steps https://stackoverflow.com/a/49159195/9660287 which kind of worked but it now raises a WinError127. I checked for multiple versions of python on my system but I only have 1, version 3.9.1. Traceback (most recent call last): File "D:\health\manage.py", line 22, in <module> main() File "D:\health\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Python\lib\site-packages\django-3.1.5-py3.9.egg\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Python\lib\site-packages\django-3.1.5-py3.9.egg\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Python\lib\site-packages\django-3.1.5-py3.9.egg\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python\lib\site-packages\django-3.1.5-py3.9.egg\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Python\lib\site-packages\django-3.1.5-py3.9.egg\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "D:\health\facility\models.py", line 1, in <module> from django.contrib.gis.db import models File "C:\Python\lib\site-packages\django-3.1.5-py3.9.egg\django\contrib\gis\db\models\__init__.py", line 3, in <module> import django.contrib.gis.db.models.functions # NOQA File "C:\Python\lib\site-packages\django-3.1.5-py3.9.egg\django\contrib\gis\db\models\functions.py", line 3, in <module> from django.contrib.gis.db.models.fields import BaseSpatialField, GeometryField File "C:\Python\lib\site-packages\django-3.1.5-py3.9.egg\django\contrib\gis\db\models\fields.py", … -
i send my django project to my client and on his laptop it gives him error
Although I use python version 3and he use python version 3.8. and also he download database sqlite3 browser. the error is -
Celery shared_task hangs on task call
I have a simple celery task with print statement. The problem is in shared_task decorator, because if I change the decorator to app.task it works fine. @shared_task def generate_pdf(): print('Just to test if its working') But calling this task from a view or django shell just stucks until i hit Ctrl+C. Here is the traceback after keyboard interupt when celery hangs. ^CTraceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/kombu/utils/objects.py", line 41, in __get__ return obj.__dict__[self.__name__] KeyError: 'tasks' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/kombu/utils/objects.py", line 41, in __get__ return obj.__dict__[self.__name__] KeyError: 'data' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/kombu/utils/objects.py", line 41, in __get__ return obj.__dict__[self.__name__] KeyError: 'tasks' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.8/site-packages/celery/local.py", line 143, in __getattr__ return getattr(self._get_current_object(), name) File "/usr/local/lib/python3.8/site-packages/celery/local.py", line 105, in _get_current_object return loc(*self.__args, **self.__kwargs) File "/usr/local/lib/python3.8/site-packages/celery/app/__init__.py", line 69, in task_by_cons return app.tasks[ File "/usr/local/lib/python3.8/site-packages/kombu/utils/objects.py", line 43, in __get__ value = obj.__dict__[self.__name__] = self.__get(obj) File "/usr/local/lib/python3.8/site-packages/celery/app/base.py", line 1259, in tasks self.finalize(auto=True) File "/usr/local/lib/python3.8/site-packages/celery/app/base.py", line 511, in finalize _announce_app_finalized(self) File "/usr/local/lib/python3.8/site-packages/celery/_state.py", line 52, in … -
in django model foreign key not retrieving actual value
in django i defined two tables 1. country 2.state while i am trying to print country_id from State table its retriving like "State object (1)" i am expectin number alone like 1 ,2 3 # location lookup class Country(models.Model): country_id=models.AutoField(auto_created=True,primary_key=True) country_name=models.CharField(max_length=50) country_code=models.CharField(max_length=50,null=True,blank=True) # state lookup class State(models.Model): state_id=models.AutoField(auto_created=True,primary_key=True) state_name=models.CharField(max_length=50) country_id=models.ForeignKey(Country, on_delete=models.CASCADE,db_column='country_id') -
Django-Run a function in the background forever
In my case,I need to process something in the background indefinitely and as often as possible. Tools like Celery,RQ,etc have minimum limit as 1 second to run something periodically. But what I need is a way to run a function in the background without blocking the Django server from running. I tried while loop.But it blocks the server. I need something like below def call_me_once_and_run_forever_as_often_as_possible(): print("I am running here indefinitely without affecting serving of Web requests") call_me_once_and_run_forever_as_often_as_possible() I read about async.But can't quite understand how to run it forever. Any small snippet would be of great help. Thanks for helping -
NoReverseMatch at /listings/ Reverse for 'listing' not found. 'listing' is not a valid view function or pattern name
So I'm getting this error when I visit the page, I'm trying to use paginator and I don't know where i'm wrong, index function handles the page I'm talking about views.py def index(request): listings = Listing.objects.all() paginator = Paginator(listings, 3) page = request.GET.get('page') paged_listings = paginator.get_page(page) params = {'listings':paged_listings} return render(request, 'listings/listings.html', params) def listing(request, listing_id): return render(request, 'listings/listing.html') def search(request): return render(request, 'listings/search.html') listings.html {% extends 'base.html' %} {% block content %} {% load humanize %} <!-- Breadcrumb --> <section id="bc" class="mt-3"> <div class="container"> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="{% url 'index' %}"> <i class="fas fa-home"></i> Home</a> </li> <li class="breadcrumb-item active"> Browse Listings</li> </ol> </nav> </div> </section> <!-- Listings --> <section id="listings" class="py-4"> <div class="container"> <div class="row"> {% if listings %} {% for listing in listings %} <div class="col-md-6 col-lg-4 mb-4"> <div class="card listing-preview"> <img class="card-img-top" src="{{ listing.photo_main.url }}" alt=""> <div class="card-img-overlay"> <h2> <span class="badge badge-secondary text-white">${{ listing.price | intcomma}}</span> </h2> </div> <div class="card-body"> <div class="listing-heading text-center"> <h4 class="text-primary">{{ listing.title }}</h4> <p> <i class="fas fa-map-marker text-secondary"></i>{{ listing.city }} {{ listing.state }}, {{ listing.zipcode }}</p> </div> <hr> <div class="row py-2 text-secondary"> <div class="col-6"> <i class="fas fa-th-large"></i>Sqfit: {{ listing.sqft }}</div> <div class="col-6"> <i class="fas fa-car"></i>Garage: {{ listing.garage }}</div> </div> … -
django url parameter creating in the process
I have no idea how to solve this problem: I have a django webshop project. At the end of the order I would like to redirect the user to a new page about the confirmation. urls.py: `path('confirmation/<str:order_id>/', views.confirmation,` name="confirmation"), views.py: def confirmation(request, order_id): items = OrderItem.objects.filter(order__id = order_id) context = {'items':items} return render(request, 'store/pages/confirmation.html', context) I have a javascript part another view where I do a POST method. If it is successfully done I would like to navigate to the confirmation page. In the data I get back the order_id. var url = '/process_order/' fetch(url,{ method: 'POST', headers: { 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body: JSON.stringify({'myForm':myFormData}) }) .then((response) => response.json()) .then((data) => { window.location.href = "{% url 'confirmation' data %}" }) I guess the problem is that in the very beginning of the execution there is no value of the data, because it is creating in the process. So the view can not render because of the parameter. (But my problem is that the order_id is creating after the POST method). (The Exception Value: Reverse for 'confirmation' with arguments '('',)' not found. 1 pattern(s) tried: ['confirmation/(?P<order_id>[^/]+)/$'] ) What would be the good solution of this situation? -
Problem with pytest. Queryset in my model
I have problem with pytest. In file tests.py I have got this code @pytest.mark.django_db def test_AddCompany(client): response = client.post('/add-company/', {'name': 'Test Company', 'description': 'test description', 'contact': 'testingmail@mail.pl', 'services': '', 'city': '', 'have_stationary': ''}) assert Company.objects.filter(name='Test') And I got this error E + where <QuerySet []> = <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.db.models.manager.Manager object at 0x000002ACF3AD6C70>>(name='Test') E + where <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.db.models.manager.Manager object at 0x000002ACF3AD6C70>> = <django.db.models.manager.Manager object at 0x0 00002ACF3AD6C70>.filter E + where <django.db.models.manager.Manager object at 0x000002ACF3AD6C70> = Company.objects services, city and have_stationary its foreign key. -
Django how make makemigrations and migrate when making changes at models
Whenever I make changes to the models (and subsequently to the views) when I do makemigrations or migration, I always run into problems. Sometimes running makemigrations django notices the changes, but then when I run the command migrate django writes that there are no changes to be made. Other times, dozens of exceptions are generated during makemigrations. Django writes that he does not find certain tables or certain fields but I read that the errors report the names before my changes. The only solution to all this is to delete content of: _pycache_ views.py sql3.db3 database Leave only models.py. At this point I can proceed with the makemigrations and migrate commands. The question: is there an easier way? What am I wrong? -
Event handlers fires multiple times when triggered [duplicate]
For some reasons unbeknownst to me, the events for elements I created dynamically fires multiple times (mulitplying itself by three each time). Those, I added manually fire only ones. As you can see, I have some console.log() which I use to track if the function was called multiple times or it was the event handler that fired multiple times. Also added event.stopPropagation(), still fires. here is my html code {% extends "mail/layout.html" %} {% load static %} {% block body %} <h2>{{ request.user.email }}</h2> <button class="btn btn-sm btn-outline-primary" id="inbox">Inbox</button> <button class="btn btn-sm btn-outline-primary" id="compose">Compose</button> <button class="btn btn-sm btn-outline-primary" id="sent">Sent</button> <button class="btn btn-sm btn-outline-primary" id="archived">Archived</button> <a class="btn btn-sm btn-outline-primary" href="{% url 'logout' %}">Log Out</a> <hr> <div id="emails-view"> </div> <div id="mail-template"> </div> <div id="compose-view"> <h3>New Email</h3> <form id="compose-form" action="#"> <div class="form-group"> From: <input disabled class="form-control" value="{{ request.user.email }}"> </div> <div class="form-group"> To: <input id="compose-recipients" class="form-control" placeholder="Recipient"> </div> <div class="form-group"> <input class="form-control" id="compose-subject" placeholder="Subject" value="HOMES"> </div> <p><textarea class="form-control" id="compose-body" placeholder="Body"></textarea></p> <p><input value="Send" type="submit" class="btn btn-primary" id='compose-submit'/></p> <!--<p><button class="btn btn-primary" id="compose-submit">Send</button></p>--> </form> </div> {% endblock %} {% block script %} <script src="{% static 'mail/index.js' %}" type='text/javascript'></script> {% endblock %} here is my Javascript file function check_parent(e){ return e.id || e.parentNode.id || e.parentNode.parentNode.id; } function … -
Prevent redirection in Django template form
Currently, my application is rendering an Django Template model form wherein some images are referred from another model. In order to delete and add images for the other model, I am handling it with a button with an overriden formaction that points to a DRF-based REST endpoint which deals with the images. However, whenever the service is invoked, it redirects the app to API response page. I would like to if it is possible to prevent redirection after formaction for button or input html elements -
Fetch with same path, sometimes failed
StackOverflow Got an issue with fetch in js + Django document.addEventListener("DOMContentLoaded", function () { // Use buttons to toggle between views document .querySelector("#inbox") .addEventListener("click", () => load_mailbox("inbox")); document .querySelector("#sent") .addEventListener("click", () => load_mailbox("sent")); document .querySelector("#archived") .addEventListener("click", () => load_mailbox("archive")); document.querySelector("#compose").addEventListener("click", compose_email); // By default, load the inbox load_mailbox("inbox"); console.log("again loaded INBOX____________") // check is the compose submitted document.querySelector("#compose-form").onsubmit = function () { fetch("/emails", { method: "POST", body: JSON.stringify({ recipients: document.querySelector("#compose-recipients").value, subject: document.querySelector("#compose-subject").value, body: document.querySelector("#compose-body").value, }), }) .then((response) => response.json()) .then((result) => { // Print result console.log(result); load_mailbox("sent"); }); }; }); Inbox, Sent and Archive they are my buttons, which I used to navigate when it clicked, neededd div will be shown, others will be hidden. function load_mailbox(mailbox) { // Show the mailbox and hide other views document.querySelector("#emails-view").style.display = "block"; document.querySelector("#compose-view").style.display = "none"; document.querySelector("#email-click-view").style.display = "none"; // Show the mailbox name document.querySelector("#emails-view").innerHTML = `<h3>${ mailbox.charAt(0).toUpperCase() + mailbox.slice(1) }</h3>`; if (mailbox === "inbox") { fetch_mail_by_folder("inbox") } if (mailbox === "sent") { fetch_mail_by_folder("sent") } if (mailbox === "archive") { fetch_mail_by_folder("archive") } } Load mailbox will call other function, which will fetch the data for the page function fetch_mail_by_folder(folder) { fetch(`/emails/${folder}`) .then((response) => response.json()) .then((emails) => { // Print emails emails.forEach(email => { const … -
Library for developing datagrid?
I am about to develope a data management webapplication and I need a datagrid like airtable. What is the fast way to build a datagrid like that? What tecknology framework is he best choise? Is it a ready to go product with the compoment I need? Please help 🙌