Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to create 2 objects from separate models with a single serializer and also retrieve them from the database with a single serializer in Django RF?
I have 3 models: Maker, Item and MakerItem that creates the relation between the items and their makers: class Maker(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=100) class Item(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=100) class MakerItem(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) item_id = models.ForeignKey(Item, on_delete=models.CASCADE) maker_id = models.ForeignKey(Maker, on_delete=models.CASCADE) the items can have a random amount of makers. I want to create both the Item and the MakerItem objects at the same time with a single set of data, for example if a Maker with id = "abcd" already exists, and I go to /item and send a POST request with the following data: { "name": "item1", "makers": [ { "maker_id": "abcd" } ] } I want the serializer to create the Item object and the MakerItem object. I have achieved this, with the following setup: views.py class ItemListCreate(ListCreateAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer serializers.py class ItemSerializer(serializers.ModelSerializer): class MakerItemSerializer(serializers.ModelSerializer): class Meta: model = MakerItem exclude = ['id', 'item_id'] makers = MakerItemSerializer(many=True) class Meta: model = Item fields = ['id', 'name', 'makers'] def create(self, validated_data): maker_item_data = validated_data.pop('makers') item_instance = Item.objects.create(**validated_data) for each in maker_item_data: MakerItem.objects.create( item_id=check_instance, maker_id=each['maker_id'] ) return check_instance but when Django tries to return the created … -
Restricting Python type hints to values from a tuple
One of my methods takes a status argument that's used in a filter(). This argument is related to a model field defined like this : STATUS_CHOICES = ( (1, _("draft")), (2, _("private")), (3, _("published")), ) class MyModel(Model): status = models.PositiveSmallIntegerField(_("status"), choices=STATUS_CHOICES, default=1) I'd like to use Python's type hints in order to make its definition clearer. I could probably do something like : def my_method(status: int): ... But the status has to be included in STATUS_CHOICES. Can I make this hint more restrictive and limited to STATUS_CHOICES values? -
Django update profile
Hi guys I hope you'll be Great I have a question this day about how to update a profile in my Django app. the problem is that when I fill the spaces in the form and I click the save changes button the content doesn't update the info in the admin to the profile I'll appreciate your feedback thanks you can see it in https://github.com/edisonjao5/Django2App Or here is the code in profiles app models.py from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from sorl.thumbnail import ImageField class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='profile' ) SOCIAL = ( ('twitter', 'Twitter'), ('facebook', 'Facebook'), ('instagram', 'Instagram'), ('youtube', 'Youtube'), ('github', 'Github'), ) First_Name = models.CharField(max_length=30) Last_Name = models.CharField(max_length=30) Username = models.CharField(max_length=30) image = ImageField(upload_to='profiles') Password = models.CharField(max_length=30) Social = models.CharField(max_length=30, choices=SOCIAL) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def update_user_profile(sender, instance, **kwargs): instance.profile.save() views.py from django.views.generic import DetailView, View, FormView from django.contrib.auth.mixins import LoginRequiredMixin from .models import Profile from .forms import UpdateProfileForm class UpdateProfileView(LoginRequiredMixin, FormView): http_method_names =['get', 'post'] template_name = 'profiles/update.html' form_class = UpdateProfileForm success_url = '/' def dispatch(self, request, *args, **kwargs): self.request = request return … -
Can't query with Select2 in Django
I try to use Select2 API for JQuery, but I'm having issues with displaying the returned results. I want to be able to search the results I'm getting from my Ajax request. It gives me 0 errors, and I believe I followed the documentation correctly. When I log the returned data from the Ajax I also get the correct data back. What am I doing wrong that I can't see the results inside the select2 input field when searching? This is my Jquery code: $('.radiocheck2').on("click", function(){ console.log("test"); $('.nummerplaat').select2({ minimumInputLength: 2, placeholder: 'Nummerplaat', dataType: 'json', ajax: { url:getallnummerplaten, method: 'GET', data: function (params) { return { q: params.term, type: 'public' // search term }; }, beforeSend: function(xhr, settings) { if(!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, processResults: function (data) { arrNummerplaten = [] for(i=0; i < data['nummerPlaten'].length; i++){ arrNummerplaten[i] = data['nummerPlaten'][i].nummerPlaat } console.log(arrNummerplaten) return { results: arrNummerplaten, }; }, cache: true } }); }) This is my Django view to retrieve the data: class getAllNummerplaten(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): nummerPlaten = list(Voertuigen.objects.all().values("nummerPlaat")) print(nummerPlaten) nummerPlatenjson = json.dumps(nummerPlaten) return JsonResponse({'nummerPlaten': nummerPlaten }) And this is my template code: <!-- TestCode --> <div style="display:none" id="overzichttankbeurten" class="card shadow mb-4"> <div class="card-header py-3"> … -
django rest knox - get token expiry time from request
I'm using django-rest-knox to authenticate users. The token is stored in a cookie and I use a custom middleware to retrieve it. In addition to that, this middleware sets the cookie everytime a request is done to keep the cookie expiration time updated. Django rest knox, has a method to refresh token expiry time (renew_token) and I want to update my cookie if that field is changed. I tried to adapt the code like this: `class KnoxTokenAuthenticationMiddleware: def _update_cookie(self, request, response): response.set_cookie( settings.KNOX_COOKIE_NAME, request.COOKIES[settings.KNOX_COOKIE_NAME], domain=settings.KNOX_COOKIE_DOMAIN, httponly=settings.KNOX_COOKIE_HTTPONLY, secure=settings.KNOX_COOKIE_SECURE, samesite=settings.KNOX_COOKIE_SAMESITE, max_age=settings.KNOX_COOKIE_MAX_AGE, path=settings.KNOX_COOKIE_PATH, ) return response def __init__(self, get_response): # One-time configuration and initialization. self.get_response = get_response def __call__(self, request): if settings.KNOX_COOKIE_NAME in request.COOKIES: request.Authorization = 'Token {}'.format(request.COOKIES[settings.KNOX_COOKIE_NAME]) response = self.get_response(request) try: current_expiry = request.auth.expiry new_expiry = timezone.now() + settings.REST_KNOX.get('TOKEN_TTL') delta = (new_expiry - current_expiry).total_seconds() logging.basicConfig(level=logging.DEBUG) logging.debug('current expiry: {}'.format(current_expiry)) logging.debug('new expiry: {}'.format(new_expiry)) logging.debug('delta: {}'.format(delta)) logging.debug('refresh interval: {}'.format(settings.REST_KNOX.get('MIN_REFRESH_INTERVAL'))) if delta > settings.REST_KNOX.get('MIN_REFRESH_INTERVAL'): logging.basicConfig(level=logging.DEBUG) logging.debug('update cookie') response = self._update_cookie(request, response) except Exception as e: logging.basicConfig(level=logging.DEBUG) logging.debug(e) else: response = self.get_response(request) return response` The problem is that the request.auth.expiry time does not match the expiry time displayed in database: expiry time from middleware expiry time from database How can i get the expiry time displayed in … -
Using django-admin in Atom Powershell
I am trying for hours but can not get rid of these django error. I have also added the path variable. PS E:\atom\python> django-admin startproject mysite django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 django-admin startproject mysite + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
routing DRF with multi slashes lookup_field
i have views (readonlymodel) class Test(ReadOnlyModelViewSet): queryset = Test.objects.all() lookup_field = 'art' serializer_class = TestSerializer @action(methods=['GET'], detail=True) def chars(self, request, art): .... also urls: router = routers.SimpleRouter() router.register(r'api/test', Test) I need lookup_field to work for art with multiple slashes. Example art: "first_product/test" But action chars is also needed. Example 'first_product/test/chars' Examples of queries that should work: 0.0.0.0:8000/api/test/first_product/test 0.0.0.0:8000/api/test/first_product/test/chars 0.0.0.0:8000/api/test/second_product 0.0.0.0:8000/api/test/second_product/chars I tried to do it through lookup_value_regex, but unfortunately it didn't work out that way, either /chars doesn't work, or with /chars works, but it doesn't see without it. Those works either this or that: 0.0.0.0:8000/api/test/first_product/test 0.0.0.0:8000/api/test/first_product/test/chars -
Postgres "relation not found" after running a pg_restore with a Django management command
I'm creating a test database that needs to be sanitized from customer data and needs to stay in sync with our production database. So I have a cronjob in Kubernetes that does a pg_dump, pg_restore and then will run a Django management command to clean the database. The dump and restore work well. I can connect to it via psql and see all tables. The problem is that the management command is failing to find a table relation (literally the first row in the Django script) and if I run a psql right after the restore, it also doesn't find the table, even though I print all the tables to make sure. All this is done through a docker container that has a shell script that basically does the dump, restore and runs the command (unsuccessfully) and the cronjob is connected to the database via a Azure pgbouncer (that's why localhost). This is what I have so far: psql -h localhost -U user -d postgres -c "\i recreate_db.sql" recreate_db.sql: I use this script to close connections, drop and recreate database for simplicity: SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'my_db'; DROP DATABASE my_db; CREATE DATABASE my_db; This works and show … -
ModuleNotFoundError: No module named 'django' even if it is installed (vs code)
I have install django in my virtual environment also activated virtual environment but still it is showing these error python from django.urls import path output Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows PS E:\django\project\telusko> & C:/Users/hp/AppData/Local/Programs/Python/Python39/python.exe e:/django/project/telusko/calc/urls.py Traceback (most recent call last): File "e:\django\project\telusko\calc\urls.py", line 1, in <module> from django.urls import path ModuleNotFoundError: No module named 'django' PS E:\django\project\telusko> -
Django count data apperance in database and send to Django-template
I have this system where i would like to be able to see some staticists over the attendancelog data. I would like to search on the class and the subject and the i get the: attendancename / username_fk the number af times this attendance has attened the subject from the specific class The total amount of times this subject and class has been on different dates the username_fk should also only appear one time My django list view look like this: class AttendanceList(LoginRequiredMixin, ListView): model = AttendanceLog template_name = "./attendancecode/showattendance.html" def get_queryset(self): class_val = self.request.GET.get('class') subject_val = self.request.GET.get('subject') sub = Subject.objects.filter(name=subject_val).first() new_context = AttendanceLog.objects.filter(keaclass_id=class_val, subject_id=sub) return new_context def get_context_data(self, **kwargs): context = super(AttendanceList, self).get_context_data(**kwargs) context['class'] = self.request.GET.get('class') context['subject'] = self.request.GET.get('subject') return context and the result of that is this: My data in the AttendanceLog table look like this so for example the username_fk "nadi6548" has attended "subject_id 2/Large" 4 out of 4 so out from nadi6548 the number 4 stands there and then again 4. I do know the last value of how many time the subject has been there is going to be the same value though the whole list and that is okay. end result: