Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-channels: no route found for path
I've been following this tutorial on django-channels: https://youtu.be/RVH05S1qab8 I followed every step that's in the video, first when i encountered the issue, i rewatched it and followed along once again to make sure i did everything correctly, but that wasn't it. i'm fairly new to django so i'm sorry if my explanation is imprecise i set up the websocket in the thread.html file: <script> // websocket scripts var loc = window.location var wsStart = 'ws://' if(loc.protocol == 'https:'){ wsStart = 'wss://' } var endpoint = wsStart + loc.host + loc.pathname var socket = new WebSocket(endpoint) socket.onmessage = function(e){ console.log('message', e) } socket.onopen = function(e){ console.log('open', e) } socket.onerror = function(e){ console.log('error', e) } socket.onclose = function(e){ console.log('close', e) } </script> my consumers.py file: import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from .models import Thread, ChatMessage class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print('connected', event) async def websocket_disconnect(self, event): print('disconnected', event) async def websocket_receive(self, event): print('receive', event) and routing.py: from django.conf.urls import url from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator from chat.consumers import ChatConsumer application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r"^messages/(?P<username>[\w.@+-]+)/$", ChatConsumer), ] ) … -
Problem with validation. Choose the correct option. Your option is not among the valid values
I'm begginer in Python and Django. I'm trying to write simple Property management System. I've got problem with asigning existing house association to new property entry. My files: models.py class Property(models.Model): # Fields id = models.AutoField(primary_key=True) name = models.CharField(max_length=45, blank=False) # Property name address = models.CharField(max_length=198, blank=False) # Property address postalcode = models.CharField(max_length=6, blank=False) # Property postalcode city = models.CharField(max_length=45, blank=False) # Property city kw_number = models.CharField(max_length=15, blank=True) # Numer KW ha_choice = models.CharField(max_length=2, choices=[(i.pk, i.name) for i in HousingAssociation.objects.all()]) # Foreign Keys # TODO zmiana on_delete na inny! house_association = models.ForeignKey(HousingAssociation, on_delete=models.CASCADE) # Metadata class Meta: ordering = ['id'] # Methods def add(self): self.save() def __str__(self): """String for representing the MyModelName object (in Admin site etc.).""" # return self.id, self.name, self.address, self.postalcode, self.city, self.kw_number return self.name forms.py class PropertyForm(forms.ModelForm): class Meta: model = Property fields = ('name', 'address', 'postalcode', 'city', 'ha_choice', 'kw_number') views.py def property_form_new(request): if request.method == "POST": form = PropertyForm(request.POST) if form.is_valid(): form.save() return render(request, 'registration/prop/success.html') else: form = PropertyForm() return render(request, 'registration/prop/prop_new.html', {'property_new': form}) In case of that django returns to me this: screenshot It means 'Choose the correct option. 14 is not among the valid values.' 14 is an id of existing entry in db … -
Why does python give FileNotFoundError: [Errno 2] No such file or directory error even though the file exists?
I am trying to make a machine learning model and use django rest framework to connect it. My folder structure is like this server | +-- chat | | | +-- DistilBertModel | | | | | +-- OurModel | | | | | | | +-- BERT_model.py | | | +-- chatbot.py | | | +-- chatbot_predict.py | | | +-- model.sav | | +-- data | | | | | | | +-- test_chatbot.csv | | | +-- answers.json | +-- migrations | +-- __init__.py | +-- admin.py | +-- apps.py | +-- models.py | +-- serializers.py | +-- tests.py | +-- urls.py | +-- views.py +-- core | +-- templates | +-- db.sqlite3 | +-- manage.py | +-- requirements.txt In chatbot_predict.py file I am trying to load the model and get a prediction using that model. The code is like this import joblib loaded_model = joblib.load ('model.sav') def get_prediction (message, loaded_model = loaded_model): return prediction When I run this file using python chatbot_predict.py using command line it works fine. However when I import this get_prediction function in server/chat/views.py and run python manage.py runserver it gives the error What am I doing wrong to get that FileNotFoundError ? -
share variable between SerializerMethodField methods
First of all, I would like to mention that I read this question but it doesn't really answer mine. I would like to "share" a variable between two SerializerMethodField methods to avoid computing it twice. My first idea would have been to do something similar to this: an additional attribute which I only set if the value is None. However, Django doesn't allow to add attributes which are not present in Meta.fields # code modified to include only what's important for this question class MySerializer(serializers.ModelSerializer): a = serializers.SerializerMethodField() b = serializers.SerializerMethodField() sum = None def compute_sum(self, id): if self.sum is None: self.sum = AnotherModel.objects.all().aggregate(Sum('amount'))['amount__sum'] return self.sum def get_a(self, obj): return self.compute_sum(obj.id) def get_b(self, obj): return self.compute_sum(obj.id) / 100 >= obj.target class Meta: model = MySuperModel fields = ['asdf', 'a', 'b'] Furthermore, I feel like there is probably a way easier way to accomplish this. -
PermissionRequiredMixin with django view method
I know, that we have a PermissionRequiredMixin and it has got permission_required. I have a question, how to do that with on django view method. Thank you, guys!! -
django server running Error. modul not found. can someone please tell me what exactly the problem is?
i've already added the App to my setting.py INSTALLED_APPS and also Edited my MIDDLEWARE enter image description here -
How Do I Fix An Exception Error for Django/Sendgrid?
I have a little problem sending emails via sendgrid When I send out an activation email I get the follow error back: exception ("'int' object has no attribute 'get'",) I have done some debugging and an email is being generated with a unique activation key. All the fields needed(from, recipients, subject, html email) have been filled in I have also created a new api_key on sendgrid and it has full access. I would appreciate any feedback, if you need any more information, please let me know. below is the code I'm using: View.py: class AccountEmailActivateView(FormMixin, View): success_url = '/' form_class = ReactivateEmailForm key = None def get(self, request, key=None, *args, **kwargs): self.key = key if key is not None: qs = EmailActivation.objects.filter(key__iexact=key) confirm_qs = qs.confirmable() if confirm_qs.count() == 1: obj = confirm_qs.first() obj.activate() messages.success(request, "your email has been confirmed, please login.") return redirect("account:login") else: activated_qs = qs.filter(activated=True) if activated_qs.exists(): reset_link = reverse("password_reset") msg = """Your email has already been confirmed Do you need to <a href="{link}">reset your password?</a> """.format(link=reset_link) messages.success(request, mark_safe(msg)) return redirect("account:login") context = { 'form': self.get_form(), 'key': key, } return render(request, 'registration/activation-error.html', context) def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) … -
Sending data from import button directly to database
What i need to do is to import a txt file from the html: <form method="post" enctype="multipart/form-data" action="/import_csv/"> {% csrf_token %} <input type="file" name="document" class="btn btn-sm btn-primary shadow-sm"/> <input type="submit" class="btn btn-md btn-primary shadow-sm mr-1"></input> </form> I tried also using button with an onclick event, but got the same error so i converted into input tag. The action on the form tag is the name of the function in the view.py, that does the following: def import_csv(request): context = {} # data from the txt files if request.method == 'POST': my_file = request.FILES['document'] txtData = my_file.read() html = txtData.decode('utf-8') df = pd.read_csv(html, delimiter='\t+|\t\t', header=1) print(df) df.rename(columns={'Type d’enregistrement': 'Type', 'Historique du taux de glucose (mg/dL)': 'GlucoseHistorique'}, inplace=True) df.drop('Taux de glucose scanné (mg/dL)', inplace=True, axis=1) df.drop('Insuline à action rapide (sans valeur numérique)', inplace=True, axis=1) df.drop('Insuline à action rapide (unités)', inplace=True, axis=1) df.drop('Nourriture (sans valeur numérique)', inplace=True, axis=1) df.drop('Glucides (grammes)', inplace=True, axis=1) df.drop('Insuline à action lente (sans valeur numérique)', inplace=True, axis=1) df.drop('Insuline à action lente (unités)', inplace=True, axis=1) df.drop('Commentaires', inplace=True, axis=1) df.drop('Glycémie avec électrode de dosage (mg/dL)', inplace=True, axis=1) df.drop('Cétonémie (mmol/L)', inplace=True, axis=1) df.drop('Insuline repas (unités)', inplace=True, axis=1) df.drop('Insuline de correction (unités)', inplace=True, axis=1) df.drop('Insuline modifiée par l’utilisateur (unités)', inplace=True, axis=1) df.drop('Heure précédente', … -
django sort export csv by date most recent first
I'm a beginner in django, I'm trying to sort my csv by date In my view. I can export my schedules in csv and display them in my view but I don’t know how to sort them by date by the most recent one. But in My view not in my directory. In my template it's Like this : export_21_11_2021-151707.csv export_22_11_2021-151707.csv export_23_11_2021-151707.csv But I want to sort by date the most recent like this : export_23_11_2021-151707.csv export_22_11_2021-151707.csv export_21_11_2021-151707.csv My fonction export def vm_schedule_export(): timestr = time.strftime("%d_%m_%Y-%H%M%S") schedules = VmSchedule.objects.all().values('schedule', 'action', 'dow', 'dom', 'mon', 'h', 'm', 'pause', 'vms__name') media_url = settings.MEDIA_ROOT if not os.path.exists(f'{media_url}appli'): os.makedirs(f'{media_url}appli') if not os.path.exists(f'{media_url}appli/vm'): os.makedirs(f'{media_url}appli/vm') if not os.path.exists(f'{media_url}' f'appli/vm/schedule_export'): os.makedirs(f'{media_url}appli/vm/schedule_export') with open( f'{media_url}appli/vm/schedule_export/export_' + timestr + '.csv', mode='w', encoding='utf8') as csv_file: fieldnames = ['nom', 'action', 'dow', 'dom', 'mon', 'h', 'm', 'pause', 'vms'] writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader() for k in range(schedules.count()): writer.writerow({'nom': schedules[k]["schedule"], 'action': schedules[k]["action"], 'dow': schedules[k]["dow"], 'dom': schedules[k]["dom"], 'mon': schedules[k]["mon"], 'h': schedules[k]["h"], 'm': schedules[k]["m"], 'pause': schedules[k]["pause"], 'vms': smart_str(schedules[k]["vms__name"])}) and where I show all export : def vm_schedule_download(request): media_url = settings.MEDIA_ROOT if not os.path.exists(f'{media_url}appli'): os.makedirs(f'{media_url}appli') if not os.path.exists(f'{media_url}appli/vm'): os.makedirs(f'{media_url}appli/vm') if not os.path.exists(f'{media_url}' f'appli/vm/schedule_export'): os.makedirs(f'{media_url}appli/vm/schedule_export') filenames = os.listdir(f'{media_url}appli/vm/schedule_export') return render(request, 'appli/vm/vm_schedule_download.html', {'filenames': filenames}) My template : {% for … -
How to count items containing specific value in Django Many to Many relationship
I have a django application used for annotation where i save information regarding image annotations into the model BiomarkerAnnotations through a many-to-many relationship. I keep track of which users have annotated the images with the annotated field. from django.contrib.auth.models import User class Biomarker(models.Model): name = models.CharField(max_length=256) description = models.CharField(max_length=1024) class Image(models.Model): number = models.IntegerField(default=0) absolute_path = models.CharField(max_length=2560) biomarkers = models.ManyToManyField(Biomarker, through='BiomarkerAnnotations', related_name="biomarker_annotations") annotated = models.ManyToManyField(User, related_name="annotated_by") class BiomarkerAnnotations(models.Model): _image = models.ForeignKey(Image, on_delete=models.CASCADE) biomarker = models.ForeignKey(Biomarker, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True,on_delete=models.SET_DEFAULT, default=1) I would like to create a view that returns, for a specific user (the one sending the request), how many images he has annotated and how many are left to annotate. So far I've reached this point, but it doesn't seem to work: the total count returned by the query is bigger than the images count. class AnnotStatsSerializer(serializers.ModelSerializer): annotations = serializers.IntegerField() count = serializers.IntegerField() class Meta: model = Image fields = ("count", "annotations") class AnnotatedStatsViewSet(viewsets.ReadOnlyModelViewSet): queryset = Image.objects.all() serializer_class = AnnotStatsSerializer def get_queryset(self): queryset = self.queryset user_object = self.request.user project_id = self.request.query_params.get('project', None) if project_id is None: raise Http404 queryset = queryset.annotate(annotations=Case(When(annotated__id__exact=user_object.id, then=Value(1)), default=Value(0), output_field=IntegerField())) \ .values('annotations').annotate(count=Count('annotations')).order_by('annotations') \ .values('count', 'annotations') return queryset Any help appreciated. -
Adding google maps markers from admin django
I am trying to add a marker from my admin panel to the html in django. You can see screenshot that i can input the data on my admin page. admin screen But how do I connect this code to js actually? I follow these guides: https://developers.google.com/maps/documentation/javascript/examples/marker-simple https://developers.google.com/maps/documentation/javascript/examples/marker-remove from .models import Camera # Register your models here. # admin.site.register(Camera) @admin.register(Camera) class CameraAdmin(admin.ModelAdmin): list_display = ('id', 'area', 'street', 'postcode', 'type', 'latitude', 'longitude',) search_fields = ('id', 'area', 'type', 'postcode',) fieldsets = ( (None, { 'fields': ('area', 'street', 'postcode', 'type', 'latitude', 'longitude',) }), ) -
i want to print time since on posts
i have a model post which has a created field so i cant print the day created, but it comes out as a full date while all i need is the time since i.e(3 hrs ago, not 21st Month/Year) class post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) Topic = models.ForeignKey(topic, on_delete=models.CASCADE) post = models.TextField(max_length=500) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) liked = models.ManyToManyField(User, related_name='likes', default=None, blank=True) def __str__(self): return f'{self.post}' @property def num_likes(self): return self.liked.all().count() my views.py def index(request): posts = post.objects.all().order_by('-created') topics = topic.objects.all() comment = comments.objects.all() return render(request, 'base/home.html', {'posts' : posts, 'topics' : topics, 'comments' : comment}) in my template {% for post in posts %} <div class="post-body-content"> @{{post.author}} - <small><i>{{post.created}} </i></small> <br> Topic: <a href="{% url 'topic' post.Topic %}">{{post.Topic}}</a> <br> <a href="{% url 'post' post.id %}">{{post}}</a> <br> -
How do I display comments that are using a foreign key of another model in Django class based views?
I would like to list out the comments on my Post Detail page and wanted to see how I can connect a view to the specific comments for a given post? Models.py class Post(models.Model): owner = models.ForeignKey( Profile, null=True, blank=True, on_delete=models.SET_NULL) title = models.CharField(max_length=200) body = models.TextField() Post_image = models.ImageField( null=True, blank=True, default='default.jpeg') create_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post', kwargs={'pk': self.pk}) class Meta: ordering = ['-create_date'] class Comment(models.Model): owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE) text = models.TextField() create_date = models.DateTimeField(auto_now_add=True) Views.py class PostDetailView(DetailView): model = Post def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comment_list'] = Post.comment_set.all() return context -
TemplateDoesNotExist at / templates/main/index.html
Start to learn django from guide. And get this error every time. TemplateDoesNotExist at / templates/main/index.html I read about this error from official DJango documentation, but I couldn't find enter from situation my project my project's ways settings.py from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-s%$#ykq62b_1q)#574(c7djut6bn66m5!i+3x&ypj*2h^k&%_f' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'taskmanager.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'main' ], }, }, ] WSGI_APPLICATION = 'taskmanager.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'ru' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' taskmanger\urls.py from django.urls import path, include urlpatterns = [ path('', include('main.urls')), ] main\urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), ] views.py from django.shortcuts import render def index(request): return render(request, 'templates/main/index.html') -
format issue when saving captured data with request.POST
The data is being captured, however when saving to the database it is being saved with quotes and square brackets. def create_flow_and_phases(request): phases = [{ "name": "andre", "description": "andre", "sequence_number": 1, "precedents": [] }] data = { "name": request.POST['new_flow_name'], "description": request.POST['flow_description'], "category": request.POST['select_category'], "precedents": [request.POST['precedent_list']], "users": [1], "phases": '' } # Making a POST request to save flow_and_phases url = API_HOST + "/api/flows/save_flow_and_phases/" answer = requests.post(url, data=data, headers={'Authorization': 'Token ' + request.session['user_token']}) if not answer.ok: raise Exception("An error occurred while creating flow.") Example of data in DB: Name: ['test'] I'm using Django Framework -
how to add a javascript event in a formset?
I want to add an onchange event to the formset, I tried to do this in views.py, but it adds this error to me: 'name':input(attrs={ TypeError: input() takes no keyword arguments views.py ParteFormSet = formset_factory(ParteForm, extra=extra_forms, max_num=20, widgets={ 'name':input(attrs={ 'onchange': 'multiplicar()' }) }) formset = ParteFormSet() -
Date/Time Field Django Models
I am looking for some help on a appointment booking system i am building. Basically when creating my models i only want my user to be able to select week days & specific hours. Is this possible with django models. Here is my code class Appointment(models.Model): appointmentUser = models.ForeignKey(User, on_delete=models.CASCADE, related_name="appointmentfor") attendee = models.CharField(max_length=80) apointmentDate = models.DateTimeField(auto_now=True) -
Django how to over ride created date
We have a base model that sets a created and modified field: class BaseModel(models.Model): created = models.DateTimeField(_('created'), auto_now_add=True) modified = models.DateTimeField(_('modified'), auto_now=True) ... other default properties We use this class to extend our models: class Event(BaseModel): Is there a way to over ride the created date when creating new Events? This is a stripped down version of our code. We are sending an array of event objects containing a created timestamp in our request payload. After the objects are added to the db, the created property is set to now and not the value from the payload. I would like to still extend from the BaseModel as other areas of the code may not explicitly set a created value, in which case it should default to now. events = [] for e in payload['events']: event = Event( created='datetime.datetime.fromisoformat(e['created'])' name='foo' ) events.append(event) Event.objects.bulk_create(events) -
Error in sending mail via STMP in aws elasticbeanstalk
I am unable to resolve this error. I am running django. It works properly on my local, but I have deployed the code to aws elasticbeanstalk where it throws the below error. Also my smtp configuration is something like this. I have aslo tried to ALLOW low secure apps in Google settings. But nothing seems to work. Kindly help # SMTP configuration EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'email@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True Please help me to resolve this Environment: Request Method: POST Request URL: http://odm-masala-app-env.eba-ijhfppue.us-west-2.elasticbeanstalk.com/accounts/register/ Django Version: 3.1 Python Version: 3.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'category', 'accounts', 'store', 'carts', 'orders', 'admin_honeypot', 'storages'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_session_timeout.middleware.SessionTimeoutMiddleware'] Traceback (most recent call last): File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/app/current/accounts/views.py", line 53, in register send_email.send() File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 69, in open self.connection.login(self.username, self.password) File "/usr/lib64/python3.7/smtplib.py", line 730, in login raise last_exception File "/usr/lib64/python3.7/smtplib.py", line 721, in login initial_response_ok=initial_response_ok) File "/usr/lib64/python3.7/smtplib.py", line 642, in auth raise … -
How to change Price when click on Color in Django with Jquery?
I am trying to change the price of my product according to color select, I have 6 color code on my product view page, and I am selecting the color but the price is not changing, it's working perfect with dropdown. Could someone help me to change the price according to color selection. Here is my code: <div class="pr_switch_wrap tranactionID"> <span class="switch_lable">Color</span> <div class="product_color_switch tranactionID"> {% for size in product.STOREPRODUCTSKU.all %} <span data-color="{{size.variantcolor.color_code}}" class="price_value" id="{{size.variantcolor.id}}" title="{{size.variantcolor.name}}" style="background-color: rgb(51, 51, 51); width: 23px; height: 23px;"></span> {% endfor %} </div> </div> <div class="pricing"> <p class="price"><span class="mr-2 price-dc">Rs. </span><span class="price-sale" id='id_price'>Rs. </span></p> </div> and here is jquery code.. <script src="https://code.jquery.com/jquery-3.5.0.js"></script> <script> $(document).on("click", '.tranactionID', function(event) { event.preventDefault(); console.log($('#id_price').text($(this).children(":selected").attr("price"))); }); </script> Please help me about this. -
Pre-filling the date and time fields of a form created with SplitDateTimeWidget
For events, I store the start and end dates of the event with DateTime. To create an event, I used SplitDateTimeWidget to separate date and time in the form. it's OK ! But to edit an event, I can't find how to pre-fill the date and time fields of the edit form, they remain empty. models.py class Event(models.Model): """ Model of the "contents_event" table in the database """ category = models.CharField(max_length=30, choices=EVENT_CATEGORY, default=MISCELLANEOUS, verbose_name='Catégorie') title = models.CharField(blank=False, max_length=100, verbose_name='Titre') content = models.TextField(blank=False, verbose_name='Evènement') start_date = models.DateTimeField(verbose_name='Début de l\'évènement') end_date = models.DateTimeField(verbose_name='Fin de l\'évènement') status = models.CharField(max_length=30, choices=CONTENT_STATUS, default=ACTIVATED, verbose_name='Statut') last_edit = models.DateTimeField(auto_now=True, verbose_name='Dernière modification') creation_date = models.DateTimeField(auto_now_add=True, verbose_name='Publication le') photos = models.ManyToManyField(Photo, blank=True) uuid = models.UUIDField(default=uuid.uuid4, unique=True, verbose_name='UUID') author = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='Auteur', related_name='create_events') def __str__(self): return f'Evènement - {self.title}' def display_author(self): """Create a string for the author. This is required to display author in Admin.""" return self.author.get_full_name() display_author.short_description = 'Auteur' class Meta: verbose_name_plural = "events" forms.py : class EventForm(ModelForm): """ Form used for create an event """ start_date = SplitDateTimeField( label='Début de l\'évènement (Date / Heure)', widget=widgets.SplitDateTimeWidget( date_attrs={'type': 'date', 'style': 'width:25%;'}, time_attrs={'type': 'time', 'style': 'width:25%;'}, date_format='%d/%m/%Y', time_format="'%H:%M'"), ) end_date = SplitDateTimeField( label='Fin de l\'évènement (Date / Heure)', widget=widgets.SplitDateTimeWidget( date_attrs={'type': … -
Django - MySQL | select_related() doesn't work
I'm a newbie to Django and I'm using MySQL as a database for my application (I've inspected database to generate models). Django version - 2.2 Models look like this, class CommodityCategory(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. name = models.CharField(db_column='NAME', max_length=200) # Field name made lowercase. description = models.CharField(db_column='DESCRIPTION', max_length=200, blank=True, null=True) # Field name made lowercase. created_by = models.CharField(db_column='CREATED_BY', max_length=30) # Field name made lowercase. created_dttm = models.DateTimeField(db_column='CREATED_DTTM') # Field name made lowercase. modified_by = models.CharField(db_column='MODIFIED_BY', max_length=30) # Field name made lowercase. modified_dttm = models.DateTimeField(db_column='MODIFIED_DTTM') # Field name made lowercase. def __str__(self): return self.name class Meta: managed = False db_table = 'commodity_category' class CommodityInfo(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. commodity_category = models.ForeignKey(CommodityCategory, models.DO_NOTHING, db_column='COMMODITY_CATEGORY_ID') # Field name made lowercase. name = models.CharField(db_column='NAME', max_length=200) # Field name made lowercase. description = models.CharField(db_column='DESCRIPTION', max_length=200, blank=True, null=True) # Field name made lowercase. created_by = models.CharField(db_column='CREATED_BY', max_length=30) # Field name made lowercase. created_dttm = models.DateTimeField(db_column='CREATED_DTTM') # Field name made lowercase. modified_by = models.CharField(db_column='MODIFIED_BY', max_length=30) # Field name made lowercase. modified_dttm = models.DateTimeField(db_column='MODIFIED_DTTM') # Field name made lowercase. commodity_link = models.CharField(db_column='COMMODITY_LINK', max_length=400, blank=True, null=True) # Field name made lowercase. def __str__(self): return self.name class Meta: managed = … -
Display data in a table only of the user logged in
Hello I want to display data of the user that is logged in form models into a table written in html My views.py { I am displaying data from two different models in one table } def managestugriev(request): from_stugrievance = studentgriev.objects.all() from_facgriev = facgrieve.objects.all() return render(request,'manageGriev.html', {"data_form_stu":from_stugrievance,"data_from_fac":from_facgriev}) template.html <div> <div> <h2><center>Manage Your Grievances Here </h2> <h3>Your Total Grievances: {{data|length}}</h3> <h3></h3> <table class="center"> <thead> <tr text-align="justify"> <th>ID</th> <th>Grievance</th> <th>Date & Time</th> <th>Status</th> <th>Solution</th> </tr> </thead> <tbody> {% for i in data_form_stu %} <tr text-align="justify"> <td padding:10px>{{forloop.counter}}</td> <td>{{i.grievance}}</td> <td>{{i.date_time}}</td> <td>{{i.status}}</td> {% for i in data_from_fac%} <td>{{i.solution}}</td> {% endfor %} </div> </div> </td> </tr> {% endfor %} </tbody> </table> </div> </div> models.py {Two models from which I am displaying the data} class studentgriev(models.Model): ch = ( ("Solved","Solved"),("Pending","Pending"),("Not Solved","Not Solved") ) name = models.CharField(max_length=30,default='',null=False) contactnum = models.IntegerField(default='',null=False) email = models.EmailField(max_length=50,default='',null=False) grievance = models.TextField(default='',null=False) date_time = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=100,choices=ch,default='') def __str__(self): return self.name + " " class facgrieve(models.Model): solution = models.TextField(default='',null=False) def __str__(self): return self.solution + " " Please can anyone help ! -
AJAX or Javascript POST request for Django form and get the result
I am working on a django based project in which I have integrated ML trained models to check if a https url is legitimate or not. for this I need javascript or ajax to call a rest api for my form in which I want to send a post request so that I can check if a https url is legitimate or not. NOTE: My code is running successfully and giving correct answers on postman. so just want to integrate it with my HTML form form.html: <form role="form" class="form" onsubmit="return false;"> {% csrf_token %} <div class="form-group"> <label for="data">SITE URL</label> <textarea id="data" class="form-control" rows="5"></textarea> </div> <button id="post" type="button" class="btn btn-primary">POST</button> </form> <div id="output" class="container"></div> <script src="/axios.min.js"></script> <script> (function () { var output = document.getElementById('output'); document.getElementById('post').onclick = function () { var data = document.getElementById('data').value; axios.post('http://127.0.0.1:8000/predict/', JSON.parse(data)) .then(function (res) { output.className = 'container'; output.innerHTML = res.data; }) .catch(function (err) { output.className = 'container text-danger'; output.innerHTML = err.message; }); }; })(); </script> urls.py: path('form/', form, name="form"), path('predict/', predict, name='predict') here predict/ URL is for my ML model to validate a https URL ML Model: I am returning this response: if list(model.predict([test]))[0] == 1: return JsonResponse({"Response":"Legitimate"}) else: return JsonResponse({"Response":"Phishing or fake"}) -
Django httpresponse is using get instead of post
Thank you for taking the time to help! I've been stuck for hours. I'm learning django by going through this fantastic youtube video: https://www.youtube.com/watch?v=sm1mokevMWk&t=4252s. I believe I copied the code from the video exactly, and I double and triple checked it. Yet, despite declaring method = "post" in "create".html django consistently uses a get response. WHY?! #urls.py from django.urls import path from . import views urlpatterns = [ path('<int:id>', views.index, name='index'), path("",views.home, name = 'home'), path("create/", views.create, name="create"), ] #views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .models import ToDoList, Item from .forms import CreateNewList def index(response, id): ls = ToDoList.objects.get(id=id) return render(response, 'main/list.html', {"ls":ls}) def home(response): return render(response, "main/home.html", {}) def create(response): print(response.method) if response.method == "POST": form = CreateNewList(response.POST) if form.is_valid(): n = form.cleaned_data['name'] t = ToDoList(name=n) t.save() return HttpResponseRedirect("/%i" %t.id) else: form = CreateNewList() return render(response, "main/create.html", {"form":form}) #create.html {% extends 'main/base.html' %} {% block title %} Create New List {% endblock %} {% block content %} Create Pages <form method="post" action="/create/"> {{form.as_p}} <button type="submit", name ="save" >Create New</button> </form> {% endblock %} #base.html <html> <head> <title>{% block title %}Jeff's website{% endblock %}</title> </head> <body> <div id="content", name="content"> {% block content %} {% endblock …